View Javadoc
1   /*
2    * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.internal.transport.sshd.auth;
44  
45  import static java.nio.charset.StandardCharsets.UTF_8;
46  
47  import java.net.Authenticator;
48  import java.net.Authenticator.RequestorType;
49  import java.net.InetSocketAddress;
50  import java.net.PasswordAuthentication;
51  import java.nio.ByteBuffer;
52  import java.nio.CharBuffer;
53  import java.security.AccessController;
54  import java.security.PrivilegedAction;
55  import java.util.Arrays;
56  import java.util.concurrent.CancellationException;
57  
58  import org.eclipse.jgit.internal.transport.sshd.SshdText;
59  import org.eclipse.jgit.transport.SshConstants;
60  
61  /**
62   * An abstract implementation of a username-password authentication. It can be
63   * given an initial known username-password pair; if so, this will be tried
64   * first. Subsequent rounds will then try to obtain a user name and password via
65   * the global {@link Authenticator}.
66   *
67   * @param <ParameterType>
68   *            defining the parameter type for the authentication
69   * @param <TokenType>
70   *            defining the token type for the authentication
71   */
72  public abstract class BasicAuthentication<ParameterType, TokenType>
73  		extends AbstractAuthenticationHandler<ParameterType, TokenType> {
74  
75  	/** The current user name. */
76  	protected String user;
77  
78  	/** The current password. */
79  	protected byte[] password;
80  
81  	/**
82  	 * Creates a new {@link BasicAuthentication} to authenticate with the given
83  	 * {@code proxy}.
84  	 *
85  	 * @param proxy
86  	 *            {@link InetSocketAddress} of the proxy to connect to
87  	 * @param initialUser
88  	 *            initial user name to try; may be {@code null}
89  	 * @param initialPassword
90  	 *            initial password to try, may be {@code null}
91  	 */
92  	public BasicAuthentication(InetSocketAddress proxy, String initialUser,
93  			char[] initialPassword) {
94  		super(proxy);
95  		this.user = initialUser;
96  		this.password = convert(initialPassword);
97  	}
98  
99  	private byte[] convert(char[] pass) {
100 		if (pass == null) {
101 			return new byte[0];
102 		}
103 		ByteBuffer bytes = UTF_8.encode(CharBuffer.wrap(pass));
104 		byte[] pwd = new byte[bytes.remaining()];
105 		bytes.get(pwd);
106 		if (bytes.hasArray()) {
107 			Arrays.fill(bytes.array(), (byte) 0);
108 		}
109 		Arrays.fill(pass, '\000');
110 		return pwd;
111 	}
112 
113 	/**
114 	 * Clears the {@link #password}.
115 	 */
116 	protected void clearPassword() {
117 		if (password != null) {
118 			Arrays.fill(password, (byte) 0);
119 		}
120 		password = new byte[0];
121 	}
122 
123 	@Override
124 	public final void close() {
125 		clearPassword();
126 		done = true;
127 	}
128 
129 	@Override
130 	public final void start() throws Exception {
131 		if (user != null && !user.isEmpty()
132 				|| password != null && password.length > 0) {
133 			return;
134 		}
135 		askCredentials();
136 	}
137 
138 	@Override
139 	public void process() throws Exception {
140 		askCredentials();
141 	}
142 
143 	/**
144 	 * Asks for credentials via the global {@link Authenticator}.
145 	 */
146 	protected void askCredentials() {
147 		clearPassword();
148 		PasswordAuthentication auth = AccessController
149 				.doPrivileged(new PrivilegedAction<PasswordAuthentication>() {
150 
151 					@Override
152 					public PasswordAuthentication run() {
153 						return Authenticator.requestPasswordAuthentication(
154 								proxy.getHostString(), proxy.getAddress(),
155 								proxy.getPort(), SshConstants.SSH_SCHEME,
156 								SshdText.get().proxyPasswordPrompt, "Basic", //$NON-NLS-1$
157 								null, RequestorType.PROXY);
158 					}
159 				});
160 		if (auth == null) {
161 			user = ""; //$NON-NLS-1$
162 			throw new CancellationException(
163 					SshdText.get().authenticationCanceled);
164 		}
165 		user = auth.getUserName();
166 		password = convert(auth.getPassword());
167 	}
168 }