2 package net.sourceforge.guacamole.net.basic;
5 * Guacamole - Clientless Remote Desktop
6 * Copyright (C) 2010 Michael Jumper
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 import java.io.BufferedReader;
23 import net.sourceforge.guacamole.net.auth.AuthenticationProvider;
25 import java.io.FileReader;
26 import java.io.IOException;
27 import java.io.Reader;
28 import java.security.MessageDigest;
29 import java.security.NoSuchAlgorithmException;
30 import java.util.Collections;
31 import java.util.HashMap;
33 import net.sourceforge.guacamole.GuacamoleException;
34 import net.sourceforge.guacamole.net.auth.UsernamePassword;
35 import net.sourceforge.guacamole.properties.FileGuacamoleProperty;
36 import net.sourceforge.guacamole.properties.GuacamoleProperties;
37 import net.sourceforge.guacamole.protocol.GuacamoleConfiguration;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.xml.sax.Attributes;
41 import org.xml.sax.InputSource;
42 import org.xml.sax.SAXException;
43 import org.xml.sax.XMLReader;
44 import org.xml.sax.helpers.DefaultHandler;
45 import org.xml.sax.helpers.XMLReaderFactory;
48 * Authenticates users against a static list of username/password pairs.
49 * Each username/password may be associated with exactly one configuration.
50 * This list is stored in an XML file which is reread if modified.
52 * @author Michael Jumper
54 public class BasicFileAuthenticationProvider implements AuthenticationProvider<UsernamePassword> {
56 private Logger logger = LoggerFactory.getLogger(BasicFileAuthenticationProvider.class);
58 private long mappingTime;
59 private Map<String, AuthInfo> mapping;
62 * The filename of the XML file to read the user mapping from.
64 public static final FileGuacamoleProperty BASIC_USER_MAPPING = new FileGuacamoleProperty() {
67 public String getName() { return "basic-user-mapping"; }
71 private File getUserMappingFile() throws GuacamoleException {
73 // Get user mapping file
74 return GuacamoleProperties.getProperty(BASIC_USER_MAPPING);
78 public synchronized void init() throws GuacamoleException {
80 // Get user mapping file
81 File mapFile = getUserMappingFile();
83 throw new GuacamoleException("Missing \"basic-user-mapping\" parameter required for basic login.");
85 logger.info("Reading user mapping file: {}", mapFile);
91 BasicUserMappingContentHandler contentHandler = new BasicUserMappingContentHandler();
93 XMLReader parser = XMLReaderFactory.createXMLReader();
94 parser.setContentHandler(contentHandler);
96 // Read and parse file
97 Reader reader = new BufferedReader(new FileReader(mapFile));
98 parser.parse(new InputSource(reader));
101 // Init mapping and record mod time of file
102 mappingTime = mapFile.lastModified();
103 mapping = contentHandler.getUserMapping();
106 catch (IOException e) {
107 throw new GuacamoleException("Error reading basic user mapping file.", e);
109 catch (SAXException e) {
110 throw new GuacamoleException("Error parsing basic user mapping XML.", e);
116 public Map<String, GuacamoleConfiguration> getAuthorizedConfigurations(UsernamePassword credentials) throws GuacamoleException {
118 // Check mapping file mod time
119 File userMappingFile = getUserMappingFile();
120 if (userMappingFile.exists() && mappingTime < userMappingFile.lastModified()) {
122 // If modified recently, gain exclusive access and recheck
123 synchronized (this) {
124 if (userMappingFile.exists() && mappingTime < userMappingFile.lastModified()) {
125 logger.info("User mapping file {} has been modified.", userMappingFile);
126 init(); // If still not up to date, re-init
132 // If no mapping available, report as such
134 throw new GuacamoleException("User mapping could not be read.");
136 Map<String, GuacamoleConfiguration> configs = new HashMap<String, GuacamoleConfiguration>();
138 // Validate and return info for given user and pass
139 AuthInfo info = mapping.get(credentials.getUsername());
140 if (info != null && info.validate(credentials.getUsername(), credentials.getPassword())) {
141 configs.put("DEFAULT", info.getConfiguration());
150 public static class AuthInfo {
152 public static enum Encoding {
157 private String auth_username;
158 private String auth_password;
159 private Encoding auth_encoding;
161 private GuacamoleConfiguration config;
163 public AuthInfo(String auth_username, String auth_password, Encoding auth_encoding) {
164 this.auth_username = auth_username;
165 this.auth_password = auth_password;
166 this.auth_encoding = auth_encoding;
168 config = new GuacamoleConfiguration();
171 private static final char HEX_CHARS[] = {
172 '0', '1', '2', '3', '4', '5', '6', '7',
173 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
176 public static String getHexString(byte[] bytes) {
181 StringBuilder hex = new StringBuilder(2 * bytes.length);
182 for (byte b : bytes) {
183 hex.append(HEX_CHARS[(b & 0xF0) >> 4])
184 .append(HEX_CHARS[(b & 0x0F) ]);
187 return hex.toString();
192 public boolean validate(String username, String password) {
194 // If username matches
195 if (username != null && password != null && username.equals(auth_username)) {
197 switch (auth_encoding) {
202 return password.equals(auth_password);
206 // Compare hashed password
208 MessageDigest digest = MessageDigest.getInstance("MD5");
209 String hashedPassword = getHexString(digest.digest(password.getBytes()));
210 return hashedPassword.equals(auth_password.toUpperCase());
212 catch (NoSuchAlgorithmException e) {
213 throw new UnsupportedOperationException("Unexpected lack of MD5 support.", e);
224 public GuacamoleConfiguration getConfiguration() {
231 private static class BasicUserMappingContentHandler extends DefaultHandler {
233 private Map<String, AuthInfo> authMapping = new HashMap<String, AuthInfo>();
235 public Map<String, AuthInfo> getUserMapping() {
236 return Collections.unmodifiableMap(authMapping);
248 private State state = State.ROOT;
249 private AuthInfo current = null;
250 private String currentParameter = null;
253 public void endElement(String uri, String localName, String qName) throws SAXException {
259 if (localName.equals("user-mapping")) {
268 if (localName.equals("authorize")) {
270 // Finalize mapping for this user
272 current.auth_username,
276 state = State.USER_MAPPING;
284 if (localName.equals("protocol")) {
285 state = State.AUTH_INFO;
293 if (localName.equals("param")) {
294 state = State.AUTH_INFO;
302 throw new SAXException("Tag not yet complete: " + localName);
307 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
311 // Document must be <user-mapping>
314 if (localName.equals("user-mapping")) {
315 state = State.USER_MAPPING;
321 // Only <authorize> tags allowed in main document
324 if (localName.equals("authorize")) {
326 AuthInfo.Encoding encoding;
327 String encodingString = attributes.getValue("encoding");
328 if (encodingString == null)
329 encoding = AuthInfo.Encoding.PLAIN_TEXT;
330 else if (encodingString.equals("plain"))
331 encoding = AuthInfo.Encoding.PLAIN_TEXT;
332 else if (encodingString.equals("md5"))
333 encoding = AuthInfo.Encoding.MD5;
335 throw new SAXException("Invalid encoding type");
338 current = new AuthInfo(
339 attributes.getValue("username"),
340 attributes.getValue("password"),
345 state = State.AUTH_INFO;
353 if (localName.equals("protocol")) {
355 state = State.PROTOCOL;
359 if (localName.equals("param")) {
361 currentParameter = attributes.getValue("name");
362 if (currentParameter == null)
363 throw new SAXException("Attribute \"name\" required for param tag.");
366 state = State.PARAMETER;
374 throw new SAXException("Unexpected tag: " + localName);
379 public void characters(char[] ch, int start, int length) throws SAXException {
381 String str = new String(ch, start, length);
385 current.getConfiguration()
390 current.getConfiguration()
391 .setParameter(currentParameter, str);
396 if (str.trim().length() != 0)
397 throw new SAXException("Unexpected character data.");