Ignore unreadable SSH private keys when autoloading identities
[egit.git] / org.spearce.jgit / src / org / spearce / jgit / transport / DefaultSshSessionFactory.java
blob74fca66f824983818f0f2c9cf0e14153bedf575a
1 /*
2 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
3 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
9 * conditions are met:
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * - Neither the name of the Git Development Community nor the
20 * names of its contributors may be used to endorse or promote
21 * products derived from this software without specific prior
22 * written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
25 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
26 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 package org.spearce.jgit.transport;
41 import java.awt.Container;
42 import java.awt.GridBagConstraints;
43 import java.awt.GridBagLayout;
44 import java.awt.Insets;
45 import java.io.File;
46 import java.io.FileInputStream;
47 import java.io.FileNotFoundException;
48 import java.io.IOException;
49 import java.io.OutputStream;
50 import java.security.AccessController;
51 import java.security.PrivilegedAction;
52 import java.util.HashSet;
53 import java.util.Set;
55 import javax.swing.JLabel;
56 import javax.swing.JOptionPane;
57 import javax.swing.JPanel;
58 import javax.swing.JPasswordField;
59 import javax.swing.JTextField;
61 import org.spearce.jgit.util.FS;
63 import com.jcraft.jsch.JSch;
64 import com.jcraft.jsch.JSchException;
65 import com.jcraft.jsch.Session;
66 import com.jcraft.jsch.UIKeyboardInteractive;
67 import com.jcraft.jsch.UserInfo;
69 /**
70 * Loads known hosts and private keys from <code>$HOME/.ssh</code>.
71 * <p>
72 * This is the default implementation used by JGit and provides most of the
73 * compatibility necessary to match OpenSSH, a popular implementation of SSH
74 * used by C Git.
75 * <p>
76 * If user interactivity is required by SSH (e.g. to obtain a password) AWT is
77 * used to display a password input field to the end-user.
79 class DefaultSshSessionFactory extends SshSessionFactory {
80 /** IANA assigned port number for SSH. */
81 static final int SSH_PORT = 22;
83 private Set<String> loadedIdentities;
85 private JSch userJSch;
87 private OpenSshConfig config;
89 @Override
90 public synchronized Session getSession(String user, String pass,
91 String host, int port) throws JSchException {
92 final OpenSshConfig.Host hc = getConfig().lookup(host);
93 host = hc.getHostName();
94 if (port <= 0)
95 port = hc.getPort();
96 if (user == null)
97 user = hc.getUser();
99 final Session session = getUserJSch().getSession(user, host, port);
100 if (hc.getIdentityFile() != null)
101 addIdentity(hc.getIdentityFile());
102 if (pass != null)
103 session.setPassword(pass);
104 else
105 session.setUserInfo(new AWT_UserInfo());
106 return session;
109 static String userName() {
110 return AccessController.doPrivileged(new PrivilegedAction<String>() {
111 public String run() {
112 return System.getProperty("user.name");
117 private JSch getUserJSch() throws JSchException {
118 if (userJSch == null) {
119 loadedIdentities = new HashSet<String>();
120 userJSch = new JSch();
121 knownHosts(userJSch);
122 identities();
124 return userJSch;
127 private OpenSshConfig getConfig() {
128 if (config == null)
129 config = OpenSshConfig.get();
130 return config;
133 private void knownHosts(final JSch sch) throws JSchException {
134 final File home = FS.userHome();
135 if (home == null)
136 return;
137 final File known_hosts = new File(new File(home, ".ssh"), "known_hosts");
138 try {
139 final FileInputStream in = new FileInputStream(known_hosts);
140 try {
141 sch.setKnownHosts(in);
142 } finally {
143 in.close();
145 } catch (FileNotFoundException none) {
146 // Oh well. They don't have a known hosts in home.
147 } catch (IOException err) {
148 // Oh well. They don't have a known hosts in home.
152 private void identities() throws JSchException {
153 final File home = FS.userHome();
154 if (home == null)
155 return;
156 final File sshdir = new File(home, ".ssh");
157 final File[] keys = sshdir.listFiles();
158 if (keys == null)
159 return;
160 for (int i = 0; i < keys.length; i++) {
161 final File pk = keys[i];
162 final String n = pk.getName();
163 if (!n.endsWith(".pub"))
164 continue;
165 final File k = new File(sshdir, n.substring(0, n.length() - 4));
166 if (!k.isFile())
167 continue;
169 try {
170 addIdentity(k);
171 } catch (JSchException e) {
172 continue;
177 private void addIdentity(final File identityFile) throws JSchException {
178 final String path = identityFile.getAbsolutePath();
179 if (!loadedIdentities.contains(path)) {
180 userJSch.addIdentity(path);
181 loadedIdentities.add(path);
185 private static class AWT_UserInfo implements UserInfo,
186 UIKeyboardInteractive {
187 private String passwd;
189 private String passphrase;
191 public void showMessage(final String msg) {
192 JOptionPane.showMessageDialog(null, msg);
195 public boolean promptYesNo(final String msg) {
196 return JOptionPane.showConfirmDialog(null, msg, "Warning",
197 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
200 public boolean promptPassword(final String msg) {
201 passwd = null;
202 final JPasswordField passwordField = new JPasswordField(20);
203 final int result = JOptionPane.showConfirmDialog(null,
204 new Object[] { passwordField }, msg,
205 JOptionPane.OK_CANCEL_OPTION);
206 if (result == JOptionPane.OK_OPTION) {
207 passwd = new String(passwordField.getPassword());
208 return true;
210 return false;
213 public boolean promptPassphrase(final String msg) {
214 passphrase = null;
215 final JPasswordField passwordField = new JPasswordField(20);
216 final int result = JOptionPane.showConfirmDialog(null,
217 new Object[] { passwordField }, msg,
218 JOptionPane.OK_CANCEL_OPTION);
219 if (result == JOptionPane.OK_OPTION) {
220 passphrase = new String(passwordField.getPassword());
221 return true;
223 return false;
226 public String getPassword() {
227 return passwd;
230 public String getPassphrase() {
231 return passphrase;
234 public String[] promptKeyboardInteractive(final String destination,
235 final String name, final String instruction,
236 final String[] prompt, final boolean[] echo) {
237 final GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1,
238 1, 1, GridBagConstraints.NORTHWEST,
239 GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
240 final Container panel = new JPanel();
241 panel.setLayout(new GridBagLayout());
243 gbc.weightx = 1.0;
244 gbc.gridwidth = GridBagConstraints.REMAINDER;
245 gbc.gridx = 0;
246 panel.add(new JLabel(instruction), gbc);
247 gbc.gridy++;
249 gbc.gridwidth = GridBagConstraints.RELATIVE;
251 final JTextField[] texts = new JTextField[prompt.length];
252 for (int i = 0; i < prompt.length; i++) {
253 gbc.fill = GridBagConstraints.NONE;
254 gbc.gridx = 0;
255 gbc.weightx = 1;
256 panel.add(new JLabel(prompt[i]), gbc);
258 gbc.gridx = 1;
259 gbc.fill = GridBagConstraints.HORIZONTAL;
260 gbc.weighty = 1;
261 if (echo[i]) {
262 texts[i] = new JTextField(20);
263 } else {
264 texts[i] = new JPasswordField(20);
266 panel.add(texts[i], gbc);
267 gbc.gridy++;
270 if (JOptionPane.showConfirmDialog(null, panel, destination + ": "
271 + name, JOptionPane.OK_CANCEL_OPTION,
272 JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
273 String[] response = new String[prompt.length];
274 for (int i = 0; i < prompt.length; i++) {
275 response[i] = texts[i].getText();
277 return response;
279 return null; // cancel
283 @Override
284 public OutputStream getErrorStream() {
285 return new OutputStream() {
286 private StringBuilder all = new StringBuilder();
288 private StringBuilder sb = new StringBuilder();
290 public String toString() {
291 String r = all.toString();
292 while (r.endsWith("\n"))
293 r = r.substring(0, r.length() - 1);
294 return r;
297 @Override
298 public void write(final int b) throws IOException {
299 if (b == '\r') {
300 System.err.print('\r');
301 return;
304 sb.append((char) b);
306 if (b == '\n') {
307 final String line = sb.toString();
308 System.err.print(line);
309 all.append(line);
310 sb = new StringBuilder();