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 net.sourceforge.guacamole.net.auth.AuthenticationProvider;
24 import java.io.IOException;
25 import java.security.MessageDigest;
26 import java.security.NoSuchAlgorithmException;
27 import java.util.Collections;
28 import java.util.HashMap;
30 import net.sourceforge.guacamole.GuacamoleException;
31 import net.sourceforge.guacamole.net.auth.UsernamePassword;
32 import net.sourceforge.guacamole.net.basic.properties.BasicGuacamoleProperties;
33 import net.sourceforge.guacamole.properties.GuacamoleProperties;
34 import net.sourceforge.guacamole.protocol.GuacamoleConfiguration;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.xml.sax.Attributes;
38 import org.xml.sax.SAXException;
39 import org.xml.sax.XMLReader;
40 import org.xml.sax.helpers.DefaultHandler;
41 import org.xml.sax.helpers.XMLReaderFactory;
43 public class BasicFileAuthenticationProvider implements AuthenticationProvider<UsernamePassword> {
45 private Logger logger = LoggerFactory.getLogger(BasicFileAuthenticationProvider.class);
47 private long mappingTime;
48 private Map<String, AuthInfo> mapping;
50 private File getUserMappingFile() throws GuacamoleException {
52 // Get user mapping file
53 return GuacamoleProperties.getProperty(BasicGuacamoleProperties.BASIC_USER_MAPPING);
57 public synchronized void init() throws GuacamoleException {
59 // Get user mapping file
60 File mapFile = getUserMappingFile();
62 throw new GuacamoleException("Missing \"basic-user-mapping\" parameter required for basic login.");
64 logger.info("Reading user mapping file: {}", mapFile);
69 BasicUserMappingContentHandler contentHandler = new BasicUserMappingContentHandler();
71 XMLReader parser = XMLReaderFactory.createXMLReader();
72 parser.setContentHandler(contentHandler);
73 parser.parse(mapFile.getAbsolutePath());
75 mappingTime = mapFile.lastModified();
76 mapping = contentHandler.getUserMapping();
79 catch (IOException e) {
80 throw new GuacamoleException("Error reading basic user mapping file.", e);
82 catch (SAXException e) {
83 throw new GuacamoleException("Error parsing basic user mapping XML.", e);
89 public Map<String, GuacamoleConfiguration> getAuthorizedConfigurations(UsernamePassword credentials) throws GuacamoleException {
91 // Check mapping file mod time
92 File userMappingFile = getUserMappingFile();
93 if (userMappingFile.exists() && mappingTime < userMappingFile.lastModified()) {
95 // If modified recently, gain exclusive access and recheck
97 if (userMappingFile.exists() && mappingTime < userMappingFile.lastModified()) {
98 logger.info("User mapping file {} has been modified.", userMappingFile);
99 init(); // If still not up to date, re-init
105 // If no mapping available, report as such
107 throw new GuacamoleException("User mapping could not be read.");
109 Map<String, GuacamoleConfiguration> configs = new HashMap<String, GuacamoleConfiguration>();
111 // Validate and return info for given user and pass
112 AuthInfo info = mapping.get(credentials.getUsername());
113 if (info != null && info.validate(credentials.getUsername(), credentials.getPassword()))
114 configs.put("DEFAULT", info.getConfiguration());
120 public static class AuthInfo {
122 public static enum Encoding {
127 private String auth_username;
128 private String auth_password;
129 private Encoding auth_encoding;
131 private GuacamoleConfiguration config;
133 public AuthInfo(String auth_username, String auth_password, Encoding auth_encoding) {
134 this.auth_username = auth_username;
135 this.auth_password = auth_password;
136 this.auth_encoding = auth_encoding;
138 config = new GuacamoleConfiguration();
141 private static final char HEX_CHARS[] = {
142 '0', '1', '2', '3', '4', '5', '6', '7',
143 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
146 public static String getHexString(byte[] bytes) {
151 StringBuilder hex = new StringBuilder(2 * bytes.length);
152 for (byte b : bytes) {
153 hex.append(HEX_CHARS[(b & 0xF0) >> 4])
154 .append(HEX_CHARS[(b & 0x0F) ]);
157 return hex.toString();
162 public boolean validate(String username, String password) {
164 // If username matches
165 if (username != null && password != null && username.equals(auth_username)) {
167 switch (auth_encoding) {
172 return password.equals(auth_password);
176 // Compare hashed password
178 MessageDigest digest = MessageDigest.getInstance("MD5");
179 String hashedPassword = getHexString(digest.digest(password.getBytes()));
180 return hashedPassword.equals(auth_password.toUpperCase());
182 catch (NoSuchAlgorithmException e) {
183 throw new UnsupportedOperationException("Unexpected lack of MD5 support.", e);
194 public GuacamoleConfiguration getConfiguration() {
201 private static class BasicUserMappingContentHandler extends DefaultHandler {
203 private Map<String, AuthInfo> authMapping = new HashMap<String, AuthInfo>();
205 public Map<String, AuthInfo> getUserMapping() {
206 return Collections.unmodifiableMap(authMapping);
218 private State state = State.ROOT;
219 private AuthInfo current = null;
220 private String currentParameter = null;
223 public void endElement(String uri, String localName, String qName) throws SAXException {
229 if (localName.equals("user-mapping")) {
238 if (localName.equals("authorize")) {
240 // Finalize mapping for this user
242 current.auth_username,
246 state = State.USER_MAPPING;
254 if (localName.equals("protocol")) {
255 state = State.AUTH_INFO;
263 if (localName.equals("param")) {
264 state = State.AUTH_INFO;
272 throw new SAXException("Tag not yet complete: " + localName);
277 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
281 // Document must be <user-mapping>
284 if (localName.equals("user-mapping")) {
285 state = State.USER_MAPPING;
291 // Only <authorize> tags allowed in main document
294 if (localName.equals("authorize")) {
296 AuthInfo.Encoding encoding;
297 String encodingString = attributes.getValue("encoding");
298 if (encodingString == null)
299 encoding = AuthInfo.Encoding.PLAIN_TEXT;
300 else if (encodingString.equals("plain"))
301 encoding = AuthInfo.Encoding.PLAIN_TEXT;
302 else if (encodingString.equals("md5"))
303 encoding = AuthInfo.Encoding.MD5;
305 throw new SAXException("Invalid encoding type");
308 current = new AuthInfo(
309 attributes.getValue("username"),
310 attributes.getValue("password"),
315 state = State.AUTH_INFO;
323 if (localName.equals("protocol")) {
325 state = State.PROTOCOL;
329 if (localName.equals("param")) {
331 currentParameter = attributes.getValue("name");
332 if (currentParameter == null)
333 throw new SAXException("Attribute \"name\" required for param tag.");
336 state = State.PARAMETER;
344 throw new SAXException("Unexpected tag: " + localName);
349 public void characters(char[] ch, int start, int length) throws SAXException {
351 String str = new String(ch, start, length);
355 current.getConfiguration()
360 current.getConfiguration()
361 .setParameter(currentParameter, str);
366 if (str.trim().length() != 0)
367 throw new SAXException("Unexpected character data.");