]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/LoginPage.java
upd: enforce a more strict Form call pattern.
[gigi.git] / src / org / cacert / gigi / pages / LoginPage.java
1 package org.cacert.gigi.pages;
2
3 import static org.cacert.gigi.Gigi.*;
4
5 import java.io.IOException;
6 import java.io.PrintWriter;
7 import java.security.cert.X509Certificate;
8 import java.util.HashMap;
9 import java.util.Map;
10
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14
15 import org.cacert.gigi.GigiApiException;
16 import org.cacert.gigi.database.GigiPreparedStatement;
17 import org.cacert.gigi.database.GigiResultSet;
18 import org.cacert.gigi.dbObjects.CertificateOwner;
19 import org.cacert.gigi.dbObjects.Group;
20 import org.cacert.gigi.dbObjects.User;
21 import org.cacert.gigi.localisation.Language;
22 import org.cacert.gigi.output.template.Form;
23 import org.cacert.gigi.output.template.TranslateCommand;
24 import org.cacert.gigi.pages.main.RegisterPage;
25 import org.cacert.gigi.util.AuthorizationContext;
26 import org.cacert.gigi.util.PasswordHash;
27 import org.cacert.gigi.util.RateLimit;
28 import org.cacert.gigi.util.RateLimit.RateLimitException;
29 import org.cacert.gigi.util.ServerConstants;
30
31 public class LoginPage extends Page {
32
33     public static final RateLimit RATE_LIMIT = new RateLimit(10, 5 * 60 * 1000);
34
35     public class LoginForm extends Form {
36
37         public LoginForm(HttpServletRequest hsr) {
38             super(hsr);
39         }
40
41         @Override
42         public RedirectResult submit(HttpServletRequest req) throws GigiApiException {
43             if (RegisterPage.RATE_LIMIT.isLimitExceeded(req.getRemoteAddr())) {
44                 throw new RateLimitException();
45             }
46             tryAuthWithUnpw(req);
47             return new RedirectResult(redirectPath(req));
48         }
49
50         @Override
51         protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
52             getDefaultTemplate().output(out, l, vars);
53         }
54
55     }
56
57     public static final String LOGIN_RETURNPATH = "login-returnpath";
58
59     public LoginPage() {
60         super("Password Login");
61     }
62
63     @Override
64     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
65         if (req.getHeader("Host").equals(ServerConstants.getSecureHostNamePort())) {
66             resp.getWriter().println(getLanguage(req).getTranslation("Authentication with certificate failed. Try another certificate or use a password."));
67         } else {
68             new LoginForm(req).output(resp.getWriter(), getLanguage(req), new HashMap<String, Object>());
69         }
70     }
71
72     @Override
73     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
74         if (Form.printFormErrors(req, resp.getWriter())) {
75             Form.getForm(req, LoginForm.class).output(resp.getWriter(), getLanguage(req), new HashMap<String, Object>());
76         }
77     }
78
79     @Override
80     public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
81         if (req.getSession().getAttribute("loggedin") == null) {
82             X509Certificate cert = getCertificateFromRequest(req);
83             if (cert != null) {
84                 tryAuthWithCertificate(req, cert);
85             }
86             if (req.getMethod().equals("POST")) {
87                 return Form.getForm(req, LoginForm.class).submitExceptionProtected(req, resp);
88             }
89         }
90
91         if (req.getSession().getAttribute("loggedin") != null) {
92             resp.sendRedirect(redirectPath(req));
93             return true;
94         }
95         return false;
96     }
97
98     private static String redirectPath(HttpServletRequest req) {
99         String redir = (String) req.getSession().getAttribute(LOGIN_RETURNPATH);
100         String s = redir;
101         if (s != null) {
102             if ( !s.startsWith("/")) {
103                 s = "/" + s;
104             }
105             return s;
106         } else {
107             return "/";
108         }
109     }
110
111     @Override
112     public boolean needsLogin() {
113         return false;
114     }
115
116     private void tryAuthWithUnpw(HttpServletRequest req) throws GigiApiException {
117         String un = req.getParameter("username");
118         String pw = req.getParameter("password");
119         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password`, `id` FROM `users` WHERE `email`=? AND verified='1'")) {
120             ps.setString(1, un);
121             GigiResultSet rs = ps.executeQuery();
122             if (rs.next()) {
123                 String dbHash = rs.getString(1);
124                 String hash = PasswordHash.verifyHash(pw, dbHash);
125                 if (hash != null) {
126                     if ( !hash.equals(dbHash)) {
127                         try (GigiPreparedStatement gps = new GigiPreparedStatement("UPDATE `users` SET `password`=? WHERE `email`=?")) {
128                             gps.setString(1, hash);
129                             gps.setString(2, un);
130                             gps.executeUpdate();
131                         }
132                     }
133                     loginSession(req, User.getById(rs.getInt(2)));
134                     req.getSession().setAttribute(LOGIN_METHOD, new TranslateCommand("Password"));
135                     return;
136                 }
137             }
138         }
139         throw new GigiApiException("Username and password didn't match.");
140     }
141
142     public static User getUser(HttpServletRequest req) {
143         AuthorizationContext ac = getAuthorizationContext(req);
144         if (ac == null) {
145             return null;
146         }
147         return ac.getActor();
148     }
149
150     public static AuthorizationContext getAuthorizationContext(HttpServletRequest req) {
151         return ((AuthorizationContext) req.getSession().getAttribute(AUTH_CONTEXT));
152     }
153
154     private void tryAuthWithCertificate(HttpServletRequest req, X509Certificate x509Certificate) {
155         String serial = extractSerialFormCert(x509Certificate);
156         User user = fetchUserBySerial(serial);
157         if (user == null) {
158             return;
159         }
160         loginSession(req, user);
161         req.getSession().setAttribute(CERT_SERIAL, serial);
162         req.getSession().setAttribute(CERT_ISSUER, x509Certificate.getIssuerDN());
163         req.getSession().setAttribute(LOGIN_METHOD, new TranslateCommand("Certificate"));
164     }
165
166     public static String extractSerialFormCert(X509Certificate x509Certificate) {
167         return x509Certificate.getSerialNumber().toString(16).toUpperCase();
168     }
169
170     public static User fetchUserBySerial(String serial) {
171         if ( !serial.matches("[A-Fa-f0-9]+")) {
172             throw new Error("serial malformed.");
173         }
174
175         CertificateOwner o = CertificateOwner.getByEnabledSerial(serial);
176         if (o == null || !(o instanceof User)) {
177             return null;
178         }
179         return (User) o;
180     }
181
182     public static X509Certificate getCertificateFromRequest(HttpServletRequest req) {
183         X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
184         X509Certificate uc = null;
185         if (cert != null && cert[0] != null) {
186             uc = cert[0];
187         }
188         return uc;
189     }
190
191     private static final Group LOGIN_BLOCKED = Group.BLOCKEDLOGIN;
192
193     private void loginSession(HttpServletRequest req, User user) {
194         if (user.isInGroup(LOGIN_BLOCKED)) {
195             return;
196         }
197         req.getSession().invalidate();
198         HttpSession hs = req.getSession();
199         hs.setAttribute(LOGGEDIN, true);
200         hs.setAttribute(Language.SESSION_ATTRIB_NAME, user.getPreferredLocale());
201         hs.setAttribute(AUTH_CONTEXT, new AuthorizationContext(user, user));
202     }
203
204     @Override
205     public boolean isPermitted(AuthorizationContext ac) {
206         return ac == null;
207     }
208 }