James Moger
2012-12-02 f1c3a882d12aede461e3c8ca3ebd298bdb28bc5d
src/com/gitblit/authority/GitblitAuthority.java
@@ -17,6 +17,7 @@
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
@@ -35,6 +36,7 @@
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URI;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
@@ -61,9 +63,11 @@
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;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
@@ -89,6 +93,7 @@
import com.gitblit.client.Translation;
import com.gitblit.models.UserModel;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.FileUtils;
import com.gitblit.utils.StringUtils;
import com.gitblit.utils.TimeUtils;
import com.gitblit.utils.X509Utils;
@@ -116,7 +121,7 @@
   
   private IUserService userService;
   
   private String caKeystorePassword = null;
   private String caKeystorePassword;
   private JTable table;
   
@@ -127,6 +132,8 @@
   private MailExecutor mail;
   private JButton certificateDefaultsButton;
   private JButton newSSLCertificate;
   public static void main(String... args) {
      EventQueue.invokeLater(new Runnable() {
@@ -234,7 +241,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;
@@ -294,15 +300,54 @@
         
         File caKeystore = new File(folder, X509Utils.CA_KEY_STORE);
         if (!caKeystore.exists()) {
            if (!X509Utils.unlimitedStrength) {
               // prompt to confirm user understands JCE Standard Strength encryption
               int res = JOptionPane.showConfirmDialog(GitblitAuthority.this, Translation.get("gb.jceWarning"),
                     Translation.get("gb.warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
               if (res != JOptionPane.YES_OPTION) {
                  if (Desktop.isDesktopSupported()) {
                     if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                        try {
                           Desktop.getDesktop().browse(URI.create("http://www.oracle.com/technetwork/java/javase/downloads/index.html"));
                        } catch (IOException e) {
                        }
                     }
                  }
                  System.exit(1);
               }
            }
            // 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);
         pass.setText(caKeystorePassword);
         pass.addAncestorListener(new RequestFocusListener());
         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);
      setMetadataDefaults(metadata);
      metadata.notAfter = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
      X509Utils.prepareX509Infrastructure(metadata, folder, this);
      return true;
   }
   
   private List<X509Certificate> findCerts(File folder, String username) {
@@ -357,37 +402,22 @@
         }
         
         @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, Constants.NAME);
            if (StringUtils.isEmpty(metadata.serverHostname)) {
               metadata.serverHostname = Constants.NAME;
            }
            UserModel user = ucm.user;
            // set default values from config file
            File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
            FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
            if (certificatesConfigFile.exists()) {
               try {
                  config.load();
               } catch (Exception e) {
                  Utils.showException(GitblitAuthority.this, e);
               }
               NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
               certificateConfig.update(metadata);
            }
            // restore expiration date
            setMetadataDefaults(metadata);
            metadata.notAfter = notAfter;
            
            // set user's specified OID values
            UserModel user = ucm.user;
            if (!StringUtils.isEmpty(user.organizationalUnit)) {
               metadata.oids.put("OU", user.organizationalUnit);
            }
@@ -408,15 +438,11 @@
            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);
            try {
               config.save();
            } catch (Exception e) {
               Utils.showException(GitblitAuthority.this, e);
            }
            updateAuthorityConfig(ucm);
            
            // refresh user
            ucm.certs = null;
@@ -427,10 +453,15 @@
            if (sendEmail) {
               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)) {
@@ -458,7 +489,10 @@
               tableModel.fireTableDataChanged();
               table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
               
               return true;
            }
            return false;
         }
      };
      
@@ -551,8 +585,6 @@
                  certificateConfig.duration = Integer.parseInt(durationTF.getText());
                  certificateConfig.store(config, metadata);
                  config.save();
                  prepareX509Infrastructure();
               } catch (Exception e1) {
                  Utils.showException(GitblitAuthority.this, e1);
               }
@@ -560,7 +592,7 @@
         }
      });
      
      JButton newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
      newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
      newSSLCertificate.setFocusable(false);
      newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));      
      newSSLCertificate.addActionListener(new ActionListener() {
@@ -580,7 +612,9 @@
               @Override
               protected Boolean doRequest() throws IOException {
                  prepareX509Infrastructure();
                  if (!prepareX509Infrastructure()) {
                     return false;
                  }
                  
                  // read CA private key and certificate
                  File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
@@ -636,8 +670,7 @@
                     metadata.serverHostname = Constants.NAME;
                  }
                  metadata.userDisplayname = ucm.user.getDisplayName();
                  sendEmail(ucm.user, metadata, zip);
                  return true;
                  return sendEmail(ucm.user, metadata, zip);
               }
               @Override
@@ -648,6 +681,23 @@
               
            };
            worker.execute();            
         }
      });
      JButton logButton = new JButton(new ImageIcon(getClass().getResource("/script_16x16.png")));
      logButton.setFocusable(false);
      logButton.setToolTipText(Translation.get("gb.log"));
      logButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            File log = new File(folder, X509Utils.CERTS + File.separator + "log.txt");
            if (log.exists()) {
               String content = FileUtils.readContent(log,  "\n");
               JTextArea textarea = new JTextArea(content);
               JScrollPane scrollPane = new JScrollPane(textarea);
               scrollPane.setPreferredSize(new Dimension(700, 400));
               JOptionPane.showMessageDialog(GitblitAuthority.this, scrollPane, log.getAbsolutePath(), JOptionPane.INFORMATION_MESSAGE);
            }
         }
      });
      
@@ -667,6 +717,7 @@
      buttonControls.add(certificateDefaultsButton);
      buttonControls.add(newSSLCertificate);
      buttonControls.add(emailBundle);
      buttonControls.add(logButton);
      JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
      userControls.add(new JLabel(Translation.get("gb.filter")));
@@ -744,7 +795,7 @@
      }
   }
   
   private void sendEmail(UserModel user, X509Metadata metadata, File zip) {
   private boolean sendEmail(UserModel user, X509Metadata metadata, File zip) {
      // send email
      try {
         if (mail.isReady()) {
@@ -771,11 +822,51 @@
            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;
   }
   private void setMetadataDefaults(X509Metadata metadata) {
      metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
      if (StringUtils.isEmpty(metadata.serverHostname)) {
         metadata.serverHostname = Constants.NAME;
      }
      // set default values from config file
      File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
      FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
      if (certificatesConfigFile.exists()) {
         try {
            config.load();
         } catch (Exception e) {
            Utils.showException(GitblitAuthority.this, e);
         }
         NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
         certificateConfig.update(metadata);
      }
   }
   private void updateAuthorityConfig(UserCertificateModel ucm) {
      File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
      FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
      if (certificatesConfigFile.exists()) {
         try {
            config.load();
         } catch (Exception e) {
            Utils.showException(GitblitAuthority.this, e);
         }
      }
      ucm.update(config);
      try {
         config.save();
      } catch (Exception e) {
         Utils.showException(GitblitAuthority.this, e);
      }
   }
}