Use exponential backoff when updating the password or last login time in WebDAV.
[pithos] / src / gr / ebs / gss / server / Login.java
1 /*
2  * Copyright 2008, 2009 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.server;
20
21 import static gr.ebs.gss.server.configuration.GSSConfigurationFactory.getConfiguration;
22 import gr.ebs.gss.client.exceptions.DuplicateNameException;
23 import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
24 import gr.ebs.gss.client.exceptions.RpcException;
25 import gr.ebs.gss.server.domain.Nonce;
26 import gr.ebs.gss.server.domain.User;
27 import gr.ebs.gss.server.ejb.ExternalAPI;
28
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.io.UnsupportedEncodingException;
32 import java.net.URI;
33 import java.net.URISyntaxException;
34 import java.net.URLEncoder;
35 import java.util.Date;
36 import java.util.Formatter;
37
38 import javax.naming.Context;
39 import javax.naming.InitialContext;
40 import javax.naming.NamingException;
41 import javax.rmi.PortableRemoteObject;
42 import javax.servlet.http.Cookie;
43 import javax.servlet.http.HttpServlet;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.apache.commons.codec.binary.Base64;
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50
51 /**
52  * The servlet that handles user logins.
53  *
54  * @author past
55  */
56 public class Login extends HttpServlet {
57         /**
58          * The request parameter name for the nonce.
59          */
60         private static final String NONCE_PARAM = "nonce";
61
62         /**
63          * The request parameter name for the URL to redirect
64          * to after authentication.
65          */
66         private static final String NEXT_URL_PARAM = "next";
67
68         /**
69          * The request parameter name for the GWT code server URL, used when
70          * debugging.
71          */
72         private static final String GWT_SERVER_PARAM = "gwt.codesvr";
73
74         /**
75          * The serial version UID of the class.
76          */
77         private static final long serialVersionUID = 1L;
78
79         /**
80          * The name of the authentication cookie.
81          */
82         private static final String AUTH_COOKIE = "_gss_a";
83
84         /**
85          * The separator character for the authentication cookie.
86          */
87         private static final char COOKIE_SEPARATOR = '|';
88
89         /**
90          * The name of the the webdav cookie.
91          */
92         public static final String WEBDAV_COOKIE = "_gss_wd";
93
94         /**
95          * The logger.
96          */
97         private static Log logger = LogFactory.getLog(Login.class);
98
99         /**
100          * A helper method that retrieves a reference to the ExternalAPI bean and
101          * stores it for future use.
102          *
103          * @return an ExternalAPI instance
104          * @throws RpcException in case an error occurs
105          */
106         private ExternalAPI getService() throws RpcException {
107                 try {
108                         final Context ctx = new InitialContext();
109                         final Object ref = ctx.lookup(getConfiguration().getString("externalApiPath"));
110                         return (ExternalAPI) PortableRemoteObject.narrow(ref, ExternalAPI.class);
111                 } catch (final NamingException e) {
112                         logger.error("Unable to retrieve the ExternalAPI EJB", e);
113                         throw new RpcException("An error occurred while contacting the naming service");
114                 }
115         }
116
117         /**
118          * Return the name of the service.
119          */
120         private String getServiceName() {
121                 return getConfiguration().getString("serviceName", "GSS");
122         }
123
124         @Override
125         public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
126                 // Fetch the next URL to display, if any.
127                 String nextUrl = request.getParameter(NEXT_URL_PARAM);
128                 // Fetch the supplied nonce, if any.
129                 String nonce = request.getParameter(NONCE_PARAM);
130                 String[] attrs = new String[] {"REMOTE_USER", "HTTP_SHIB_INETORGPERSON_DISPLAYNAME",
131                                         "HTTP_SHIB_INETORGPERSON_GIVENNAME", "HTTP_SHIB_PERSON_COMMONNAME",
132                                         "HTTP_SHIB_PERSON_SURNAME", "HTTP_SHIB_INETORGPERSON_MAIL",
133                                         "HTTP_SHIB_EP_UNSCOPEDAFFILIATION", "HTTP_PERSISTENT_ID"};
134                 StringBuilder buf = new StringBuilder("Shibboleth Attributes\n");
135                 for (String attr: attrs)
136                         buf.append(attr+": ").append(request.getAttribute(attr)).append('\n');
137                 logger.info(buf);
138                 if (logger.isDebugEnabled()) {
139                         buf = new StringBuilder("Shibboleth Attributes as bytes\n");
140                         for (String attr: attrs)
141                                 if (request.getAttribute(attr) != null)
142                                         buf.append(attr+": ").append(getHexString(request.getAttribute(attr).toString().getBytes("UTF-8"))).append('\n');
143                         logger.debug(buf);
144                 }
145                 User user = null;
146                 response.setContentType("text/html");
147                 Object usernameAttr = request.getAttribute("REMOTE_USER");
148                 Object nameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_DISPLAYNAME");
149                 Object givennameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_GIVENNAME"); // Multi-valued
150                 Object cnAttr = request.getAttribute("HTTP_SHIB_PERSON_COMMONNAME"); // Multi-valued
151                 Object snAttr = request.getAttribute("HTTP_SHIB_PERSON_SURNAME"); // Multi-valued
152                 Object mailAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_MAIL"); // Multi-valued
153                 Object userclassAttr = request.getAttribute("HTTP_SHIB_EP_UNSCOPEDAFFILIATION"); // Multi-valued
154                 Object persistentIdAttr = request.getAttribute("HTTP_PERSISTENT_ID");
155                 // Use a configured test username if found, as a shortcut for development deployments.
156                 String gwtServer = null;
157                 if (getConfiguration().getString("testUsername") != null) {
158                         usernameAttr = getConfiguration().getString("testUsername");
159                         // Fetch the GWT code server URL, if any.
160                         gwtServer = request.getParameter(GWT_SERVER_PARAM);
161                 }
162                 if (usernameAttr == null) {
163                         String authErrorUrl = "authenticationError.jsp";
164                         authErrorUrl += "?name=" + (nameAttr==null? "-": nameAttr.toString());
165                         authErrorUrl += "&givenname=" + (givennameAttr==null? "-": givennameAttr.toString());
166                         authErrorUrl += "&sn=" + (snAttr==null? "-": snAttr.toString());
167                         authErrorUrl += "&cn=" + (cnAttr==null? "-": cnAttr.toString());
168                         authErrorUrl += "&mail=" + (mailAttr==null? "-": mailAttr.toString());
169                         authErrorUrl += "&userclass=" + (userclassAttr==null? "-": userclassAttr.toString());
170                         response.sendRedirect(authErrorUrl);
171                         return;
172                 }
173                 String username = decodeAttribute(usernameAttr);
174                 String name;
175                 if (nameAttr != null && !nameAttr.toString().isEmpty())
176                         name = decodeAttribute(nameAttr);
177                 else if (cnAttr != null && !cnAttr.toString().isEmpty()) {
178                         name = decodeAttribute(cnAttr);
179                         if (name.indexOf(';') != -1)
180                                 name = name.substring(0, name.indexOf(';'));
181                 } else if (givennameAttr != null && snAttr != null && !givennameAttr.toString().isEmpty() && !snAttr.toString().isEmpty()) {
182                         String givenname = decodeAttribute(givennameAttr);
183                         if (givenname.indexOf(';') != -1)
184                                 givenname = givenname.substring(0, givenname.indexOf(';'));
185                         String sn = decodeAttribute(snAttr);
186                         if (sn.indexOf(';') != -1)
187                                 sn = sn.substring(0, sn.indexOf(';'));
188                         name = givenname + ' ' + sn;
189                 } else if (givennameAttr == null && snAttr != null && !snAttr.toString().isEmpty()) {
190                         name = decodeAttribute(snAttr);
191                         if (name.indexOf(';') != -1)
192                                 name = name.substring(0, name.indexOf(';'));
193                 } else
194                         name = username;
195                 String mail = mailAttr != null ? mailAttr.toString() : username;
196                 if (mail.indexOf(';') != -1)
197                         mail = mail.substring(0, mail.indexOf(';'));
198                 // XXX we are not using the user class currently
199                 String userclass = userclassAttr != null ? userclassAttr.toString() : "";
200                 if (userclass.indexOf(';') != -1)
201                         userclass = userclass.substring(0, userclass.indexOf(';'));
202                 String persistentId = persistentIdAttr != null ? persistentIdAttr.toString() : "";
203                 try {
204                         user = getService().findUser(username);
205                         if (user == null)
206                                 user = getService().createUser(username, name, mail, persistentId);
207                         if (!user.hasAcceptedPolicy()) {
208                                 String policyUrl = "policy.jsp";
209                                 if (request.getQueryString() != null)
210                                         policyUrl += "?user=" + username + "&" + request.getQueryString();
211                                 response.sendRedirect(policyUrl);
212                                 return;
213                         }
214                         user.setName(name);
215                         user.setEmail(mail);
216                         user.setPersistentId(persistentId);
217                         user.setLastLogin(new Date());
218                         if (user.getAuthToken() == null)
219                                 user = getService().updateUserToken(user.getId());
220                         // Set WebDAV password to token if it's never been set.
221                         if (user.getWebDAVPassword() == null || user.getWebDAVPassword().length() == 0) {
222                                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
223                                 user.setWebDAVPassword(tokenEncoded);
224                         }
225                         getService().updateUser(user);
226                 } catch (RpcException e) {
227                         String error = "An error occurred while communicating with the service";
228                         logger.error(error, e);
229                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
230                         return;
231                 } catch (DuplicateNameException e) {
232                         String error = "User with username " + username + " already exists";
233                         logger.error(error, e);
234                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
235                         return;
236                 } catch (ObjectNotFoundException e) {
237                         String error = "No username was provided";
238                         logger.error(error, e);
239                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
240                         return;
241                 }
242                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
243                 String userEncoded = URLEncoder.encode(user.getUsername(), "US-ASCII");
244                 if (logger.isDebugEnabled())
245                         logger.debug("user: "+userEncoded+" token: "+tokenEncoded);
246                 if (nextUrl != null && !nextUrl.isEmpty()) {
247                         URI next;
248                         if (gwtServer != null)
249                                 nextUrl += '?' + GWT_SERVER_PARAM + '=' + gwtServer;
250                         try {
251                                 next = new URI(nextUrl);
252                         } catch (URISyntaxException e) {
253                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
254                                 return;
255                         }
256                         if ("x-gr-ebs-igss".equalsIgnoreCase(next.getScheme()))
257                                 nextUrl += "?u=" + userEncoded + "&t=" + tokenEncoded;
258                         else {
259                                 String domain = next.getHost();
260                                 String path = next.getPath();
261                                 Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR +
262                                                         tokenEncoded);
263                                 cookie.setMaxAge(-1);
264                                 cookie.setDomain(domain);
265                                 cookie.setPath(path);
266                             response.addCookie(cookie);
267                             cookie = new Cookie(WEBDAV_COOKIE, user.getWebDAVPassword());
268                                 cookie.setMaxAge(-1);
269                                 cookie.setDomain(domain);
270                                 cookie.setPath(path);
271                                 response.addCookie(cookie);
272                         }
273                     response.sendRedirect(nextUrl);
274                 } else if (nonce != null) {
275                         nonce = URLEncoder.encode(nonce, "US-ASCII");
276                         Nonce n = null;
277                         try {
278                                 if (logger.isDebugEnabled())
279                                         logger.debug("user: "+user.getId()+" nonce: "+nonce);
280                                 n = getService().getNonce(nonce, user.getId());
281                         } catch (ObjectNotFoundException e) {
282                             PrintWriter out = response.getWriter();
283                             out.println("<HTML>");
284                             out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
285                                         "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
286                             out.println("<BODY><CENTER><P>");
287                             out.println("The supplied nonce could not be found!");
288                             out.println("</CENTER></BODY></HTML>");
289                             return;
290                         } catch (RpcException e) {
291                                 String error = "An error occurred while communicating with the service";
292                                 logger.error(error, e);
293                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
294                                 return;
295                         }
296                         try {
297                                 getService().activateUserNonce(user.getId(), nonce, n.getNonceExpiryDate());
298                         } catch (ObjectNotFoundException e) {
299                                 String error = "Unable to find user";
300                                 logger.error(error, e);
301                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
302                                 return;
303                         } catch (RpcException e) {
304                                 String error = "An error occurred while communicating with the service";
305                                 logger.error(error, e);
306                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
307                                 return;
308                         }
309                         try {
310                                 getService().removeNonce(n.getId());
311                         } catch (ObjectNotFoundException e) {
312                                 logger.info("Nonce already removed!", e);
313                         } catch (RpcException e) {
314                                 logger.warn("Could not remove nonce from data store", e);
315                         }
316                     PrintWriter out = response.getWriter();
317                     out.println("<HTML>");
318                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
319                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
320                     out.println("<BODY><CENTER><P>");
321                     out.println("You can now close this browser window and return to your application.");
322                     out.println("</CENTER></BODY></HTML>");
323                 } else {
324                     PrintWriter out = response.getWriter();
325                     out.println("<HTML>");
326                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
327                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
328                     out.println("<BODY><CENTER><P>");
329                     out.println("Name: " + user.getName() + "<BR>");
330                     out.println("E-mail: " + user.getEmail() + "<BR><P>");
331                     out.println("Username: " + user.getUsername() + "<BR>");
332                     out.println("Athentication token: " + tokenEncoded + "<BR>");
333                     out.println("</CENTER></BODY></HTML>");
334                 }
335         }
336
337         /**
338          * Decode the request attribute provided by the container to a UTF-8
339          * string, since GSS assumes all data to be encoded in UTF-8. The
340          * servlet container's encoding can be specified in gss.properties.
341          */
342         private String decodeAttribute(Object attribute) throws UnsupportedEncodingException {
343                 return new String(attribute.toString().getBytes(getConfiguration().getString("requestAttributeEncoding")), "UTF-8");
344         }
345
346         /**
347          * A helper method that converts a byte buffer to a printable list of
348          * hexadecimal numbers.
349          */
350         private String getHexString(byte[] buffer) {
351                 StringBuilder sb = new StringBuilder();
352                 Formatter formatter = new Formatter(sb);
353                 for (int i=0; i<buffer.length; i++)
354                         formatter.format("0x%x, ", buffer[i]);
355                 return sb.toString();
356         }
357
358 }