blob: 92353430650ff7a87f12d61fd96dd682c0606e0d [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26package com.sun.net.httpserver;
27import java.net.*;
28import java.io.*;
29import java.util.*;
30
31/**
32 * BasicAuthenticator provides an implementation of HTTP Basic
33 * authentication. It is an abstract class and must be extended
34 * to provide an implementation of {@link #checkCredentials(String,String)}
35 * which is called to verify each incoming request.
36 */
37public abstract class BasicAuthenticator extends Authenticator {
38
39 protected String realm;
40
41 /**
42 * Creates a BasicAuthenticator for the given HTTP realm
43 * @param realm The HTTP Basic authentication realm
44 * @throws NullPointerException if the realm is an empty string
45 */
46 public BasicAuthenticator (String realm) {
47 this.realm = realm;
48 }
49
50 /**
51 * returns the realm this BasicAuthenticator was created with
52 * @return the authenticator's realm string.
53 */
54 public String getRealm () {
55 return realm;
56 }
57
58 public Result authenticate (HttpExchange t)
59 {
60 HttpContext context = t.getHttpContext();
61 Headers rmap = (Headers) t.getRequestHeaders();
62 /*
63 * look for auth token
64 */
65 String auth = rmap.getFirst ("Authorization");
66 if (auth == null) {
67 Headers map = (Headers) t.getResponseHeaders();
68 map.set ("WWW-Authenticate", "Basic realm=" + "\""+realm+"\"");
69 return new Authenticator.Retry (401);
70 }
71 int sp = auth.indexOf (' ');
72 if (sp == -1 || !auth.substring(0, sp).equals ("Basic")) {
73 return new Authenticator.Failure (401);
74 }
75 byte[] b = Base64.base64ToByteArray (auth.substring(sp+1));
76 String userpass = new String (b);
77 int colon = userpass.indexOf (':');
78 String uname = userpass.substring (0, colon);
79 String pass = userpass.substring (colon+1);
80
81 if (checkCredentials (uname, pass)) {
82 return new Authenticator.Success (
83 new HttpPrincipal (
84 uname, realm
85 )
86 );
87 } else {
88 /* reject the request again with 401 */
89
90 Headers map = (Headers) t.getResponseHeaders();
91 map.set ("WWW-Authenticate", "Basic realm=" + "\""+realm+"\"");
92 return new Authenticator.Failure(401);
93 }
94 }
95
96 /**
97 * called for each incoming request to verify the
98 * given name and password in the context of this
99 * Authenticator's realm. Any caching of credentials
100 * must be done by the implementation of this method
101 * @param username the username from the request
102 * @param password the password from the request
103 * @return <code>true</code> if the credentials are valid,
104 * <code>false</code> otherwise.
105 */
106 public abstract boolean checkCredentials (String username, String password);
107}
108
109class Base64 {
110
111 /**
112 * Translates the specified byte array into a Base64 string as per
113 * Preferences.put(byte[]).
114 */
115 static String byteArrayToBase64(byte[] a) {
116 return byteArrayToBase64(a, false);
117 }
118
119 /**
120 * Translates the specified byte array into an "aternate representation"
121 * Base64 string. This non-standard variant uses an alphabet that does
122 * not contain the uppercase alphabetic characters, which makes it
123 * suitable for use in situations where case-folding occurs.
124 */
125 static String byteArrayToAltBase64(byte[] a) {
126 return byteArrayToBase64(a, true);
127 }
128
129 private static String byteArrayToBase64(byte[] a, boolean alternate) {
130 int aLen = a.length;
131 int numFullGroups = aLen/3;
132 int numBytesInPartialGroup = aLen - 3*numFullGroups;
133 int resultLen = 4*((aLen + 2)/3);
134 StringBuffer result = new StringBuffer(resultLen);
135 char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64);
136
137 // Translate all full groups from byte array elements to Base64
138 int inCursor = 0;
139 for (int i=0; i<numFullGroups; i++) {
140 int byte0 = a[inCursor++] & 0xff;
141 int byte1 = a[inCursor++] & 0xff;
142 int byte2 = a[inCursor++] & 0xff;
143 result.append(intToAlpha[byte0 >> 2]);
144 result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
145 result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]);
146 result.append(intToAlpha[byte2 & 0x3f]);
147 }
148
149 // Translate partial group if present
150 if (numBytesInPartialGroup != 0) {
151 int byte0 = a[inCursor++] & 0xff;
152 result.append(intToAlpha[byte0 >> 2]);
153 if (numBytesInPartialGroup == 1) {
154 result.append(intToAlpha[(byte0 << 4) & 0x3f]);
155 result.append("==");
156 } else {
157 // assert numBytesInPartialGroup == 2;
158 int byte1 = a[inCursor++] & 0xff;
159 result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
160 result.append(intToAlpha[(byte1 << 2)&0x3f]);
161 result.append('=');
162 }
163 }
164 // assert inCursor == a.length;
165 // assert result.length() == resultLen;
166 return result.toString();
167 }
168
169 /**
170 * This array is a lookup table that translates 6-bit positive integer
171 * index values into their "Base64 Alphabet" equivalents as specified
172 * in Table 1 of RFC 2045.
173 */
174 private static final char intToBase64[] = {
175 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
176 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
177 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
178 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
179 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
180 };
181
182 /**
183 * This array is a lookup table that translates 6-bit positive integer
184 * index values into their "Alternate Base64 Alphabet" equivalents.
185 * This is NOT the real Base64 Alphabet as per in Table 1 of RFC 2045.
186 * This alternate alphabet does not use the capital letters. It is
187 * designed for use in environments where "case folding" occurs.
188 */
189 private static final char intToAltBase64[] = {
190 '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':',
191 ';', '<', '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~',
192 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
193 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
194 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '?'
195 };
196
197 /**
198 * Translates the specified Base64 string (as per Preferences.get(byte[]))
199 * into a byte array.
200 *
201 * @throw IllegalArgumentException if <tt>s</tt> is not a valid Base64
202 * string.
203 */
204 static byte[] base64ToByteArray(String s) {
205 return base64ToByteArray(s, false);
206 }
207
208 /**
209 * Translates the specified "aternate representation" Base64 string
210 * into a byte array.
211 *
212 * @throw IllegalArgumentException or ArrayOutOfBoundsException
213 * if <tt>s</tt> is not a valid alternate representation
214 * Base64 string.
215 */
216 static byte[] altBase64ToByteArray(String s) {
217 return base64ToByteArray(s, true);
218 }
219
220 private static byte[] base64ToByteArray(String s, boolean alternate) {
221 byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt);
222 int sLen = s.length();
223 int numGroups = sLen/4;
224 if (4*numGroups != sLen)
225 throw new IllegalArgumentException(
226 "String length must be a multiple of four.");
227 int missingBytesInLastGroup = 0;
228 int numFullGroups = numGroups;
229 if (sLen != 0) {
230 if (s.charAt(sLen-1) == '=') {
231 missingBytesInLastGroup++;
232 numFullGroups--;
233 }
234 if (s.charAt(sLen-2) == '=')
235 missingBytesInLastGroup++;
236 }
237 byte[] result = new byte[3*numGroups - missingBytesInLastGroup];
238
239 // Translate all full groups from base64 to byte array elements
240 int inCursor = 0, outCursor = 0;
241 for (int i=0; i<numFullGroups; i++) {
242 int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
243 int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
244 int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
245 int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);
246 result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
247 result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
248 result[outCursor++] = (byte) ((ch2 << 6) | ch3);
249 }
250
251 // Translate partial group, if present
252 if (missingBytesInLastGroup != 0) {
253 int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
254 int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
255 result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
256
257 if (missingBytesInLastGroup == 1) {
258 int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
259 result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
260 }
261 }
262 // assert inCursor == s.length()-missingBytesInLastGroup;
263 // assert outCursor == result.length;
264 return result;
265 }
266
267 /**
268 * Translates the specified character, which is assumed to be in the
269 * "Base 64 Alphabet" into its equivalent 6-bit positive integer.
270 *
271 * @throw IllegalArgumentException or ArrayOutOfBoundsException if
272 * c is not in the Base64 Alphabet.
273 */
274 private static int base64toInt(char c, byte[] alphaToInt) {
275 int result = alphaToInt[c];
276 if (result < 0)
277 throw new IllegalArgumentException("Illegal character " + c);
278 return result;
279 }
280
281 /**
282 * This array is a lookup table that translates unicode characters
283 * drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)
284 * into their 6-bit positive integer equivalents. Characters that
285 * are not in the Base64 alphabet but fall within the bounds of the
286 * array are translated to -1.
287 */
288 private static final byte base64ToInt[] = {
289 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
290 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
291 -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
292 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
293 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
294 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
295 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
296 };
297
298 /**
299 * This array is the analogue of base64ToInt, but for the nonstandard
300 * variant that avoids the use of uppercase alphabetic characters.
301 */
302 private static final byte altBase64ToInt[] = {
303 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
304 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
305 2, 3, 4, 5, 6, 7, 8, -1, 62, 9, 10, 11, -1 , 52, 53, 54, 55, 56, 57,
306 58, 59, 60, 61, 12, 13, 14, -1, 15, 63, 16, -1, -1, -1, -1, -1, -1,
307 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
308 -1, -1, -1, 17, -1, 18, 19, 21, 20, 26, 27, 28, 29, 30, 31, 32, 33,
309 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
310 51, 22, 23, 24, 25
311 };
312
313}