1
2
3
4
5
6
7
8
9
10 package org.eclipse.jgit.internal.transport.sshd.auth;
11
12 import static java.nio.charset.StandardCharsets.UTF_8;
13
14 import java.net.Authenticator;
15 import java.net.Authenticator.RequestorType;
16 import java.net.InetSocketAddress;
17 import java.net.PasswordAuthentication;
18 import java.nio.ByteBuffer;
19 import java.nio.CharBuffer;
20 import java.security.AccessController;
21 import java.security.PrivilegedAction;
22 import java.util.Arrays;
23 import java.util.concurrent.CancellationException;
24
25 import org.eclipse.jgit.internal.transport.sshd.SshdText;
26 import org.eclipse.jgit.transport.SshConstants;
27
28
29
30
31
32
33
34
35
36
37
38
39 public abstract class BasicAuthentication<ParameterType, TokenType>
40 extends AbstractAuthenticationHandler<ParameterType, TokenType> {
41
42
43 protected String user;
44
45
46 protected byte[] password;
47
48
49
50
51
52
53
54
55
56
57
58
59 public BasicAuthentication(InetSocketAddress proxy, String initialUser,
60 char[] initialPassword) {
61 super(proxy);
62 this.user = initialUser;
63 this.password = convert(initialPassword);
64 }
65
66 private byte[] convert(char[] pass) {
67 if (pass == null) {
68 return new byte[0];
69 }
70 ByteBuffer bytes = UTF_8.encode(CharBuffer.wrap(pass));
71 byte[] pwd = new byte[bytes.remaining()];
72 bytes.get(pwd);
73 if (bytes.hasArray()) {
74 Arrays.fill(bytes.array(), (byte) 0);
75 }
76 Arrays.fill(pass, '\000');
77 return pwd;
78 }
79
80
81
82
83 protected void clearPassword() {
84 if (password != null) {
85 Arrays.fill(password, (byte) 0);
86 }
87 password = new byte[0];
88 }
89
90 @Override
91 public final void close() {
92 clearPassword();
93 done = true;
94 }
95
96 @Override
97 public final void start() throws Exception {
98 if (user != null && !user.isEmpty()
99 || password != null && password.length > 0) {
100 return;
101 }
102 askCredentials();
103 }
104
105 @Override
106 public void process() throws Exception {
107 askCredentials();
108 }
109
110
111
112
113 protected void askCredentials() {
114 clearPassword();
115 PasswordAuthentication auth = AccessController.doPrivileged(
116 (PrivilegedAction<PasswordAuthentication>) () -> Authenticator
117 .requestPasswordAuthentication(proxy.getHostString(),
118 proxy.getAddress(), proxy.getPort(),
119 SshConstants.SSH_SCHEME,
120 SshdText.get().proxyPasswordPrompt, "Basic",
121 null, RequestorType.PROXY));
122 if (auth == null) {
123 user = "";
124 throw new CancellationException(
125 SshdText.get().authenticationCanceled);
126 }
127 user = auth.getUserName();
128 password = convert(auth.getPassword());
129 }
130 }