upd: new Manager function, adding exp-points
[gigi.git] / util-testing / org / cacert / gigi / pages / Manager.java
1 package org.cacert.gigi.pages;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.lang.reflect.Field;
6 import java.security.GeneralSecurityException;
7 import java.security.KeyPair;
8 import java.security.KeyPairGenerator;
9 import java.security.Signature;
10 import java.sql.Date;
11 import java.util.Base64;
12 import java.util.Calendar;
13 import java.util.GregorianCalendar;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.LinkedList;
17 import java.util.Locale;
18 import java.util.Map;
19 import java.util.Properties;
20 import java.util.TreeSet;
21
22 import javax.servlet.http.HttpServletRequest;
23 import javax.servlet.http.HttpServletResponse;
24
25 import org.cacert.gigi.Gigi;
26 import org.cacert.gigi.GigiApiException;
27 import org.cacert.gigi.crypto.SPKAC;
28 import org.cacert.gigi.database.GigiPreparedStatement;
29 import org.cacert.gigi.dbObjects.Assurance.AssuranceType;
30 import org.cacert.gigi.dbObjects.Certificate;
31 import org.cacert.gigi.dbObjects.Certificate.CertificateStatus;
32 import org.cacert.gigi.dbObjects.CertificateOwner;
33 import org.cacert.gigi.dbObjects.Digest;
34 import org.cacert.gigi.dbObjects.Domain;
35 import org.cacert.gigi.dbObjects.DomainPingType;
36 import org.cacert.gigi.dbObjects.EmailAddress;
37 import org.cacert.gigi.dbObjects.Group;
38 import org.cacert.gigi.dbObjects.Name;
39 import org.cacert.gigi.dbObjects.User;
40 import org.cacert.gigi.email.EmailProvider;
41 import org.cacert.gigi.localisation.Language;
42 import org.cacert.gigi.output.template.IterableDataset;
43 import org.cacert.gigi.output.template.Template;
44 import org.cacert.gigi.pages.account.certs.CertificateRequest;
45 import org.cacert.gigi.ping.DomainPinger;
46 import org.cacert.gigi.ping.PingerDaemon;
47 import org.cacert.gigi.util.AuthorizationContext;
48 import org.cacert.gigi.util.Notary;
49
50 import sun.security.x509.X509Key;
51
52 public class Manager extends Page {
53
54     public static final String PATH = "/manager";
55
56     Field f;
57
58     private static HashMap<DomainPingType, DomainPinger> dps;
59
60     private Manager() {
61         super("Test Manager");
62         try {
63             f = EmailAddress.class.getDeclaredField("hash");
64             f.setAccessible(true);
65         } catch (ReflectiveOperationException e) {
66             // TODO
67             System.out.println("I don't have 'hash', we are working probably in layered mode. Test Manager may not work.");
68             // throw new Error(e);
69         }
70
71         try {
72             Field gigiInstance = Gigi.class.getDeclaredField("instance");
73             gigiInstance.setAccessible(true);
74             Gigi g = (Gigi) gigiInstance.get(null);
75
76             Field gigiPinger = Gigi.class.getDeclaredField("pinger");
77             gigiPinger.setAccessible(true);
78             PingerDaemon pd = (PingerDaemon) gigiPinger.get(g);
79
80             Field f = PingerDaemon.class.getDeclaredField("pingers");
81             f.setAccessible(true);
82             dps = (HashMap<DomainPingType, DomainPinger>) f.get(pd);
83             HashMap<DomainPingType, DomainPinger> pingers = new HashMap<>();
84             for (DomainPingType dpt : DomainPingType.values()) {
85                 pingers.put(dpt, new PingerFetcher(dpt));
86             }
87             f.set(pd, pingers);
88         } catch (ReflectiveOperationException e) {
89             e.printStackTrace();
90         }
91     }
92
93     public User getAssurer(int i) {
94         if (assurers[i] != null) {
95             return assurers[i];
96         }
97         try {
98             User u = createAssurer(i);
99             assurers[i] = u;
100
101         } catch (ReflectiveOperationException | GigiApiException e) {
102             e.printStackTrace();
103         }
104         return assurers[i];
105     }
106
107     private User createAssurer(int i) throws GigiApiException, IllegalAccessException {
108         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?")) {
109             String mail = "test-assurer" + i + "@example.com";
110             User u = User.getByEmail(mail);
111             if (u == null) {
112                 System.out.println("Creating assurer");
113                 createUser(mail);
114                 u = User.getByEmail(mail);
115                 passCATS(u);
116                 ps.setInt(1, u.getId());
117                 ps.setInt(2, u.getId());
118                 ps.setInt(3, 100);
119                 ps.setString(4, "Manager init code");
120                 ps.setString(5, "1990-01-01");
121                 ps.execute();
122             }
123             return u;
124         }
125     }
126
127     private void passCATS(User u) {
128         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO cats_passed SET user_id=?, variant_id=1")) {
129             ps.setInt(1, u.getId());
130             ps.execute();
131         }
132     }
133
134     private static Manager instance;
135
136     Template t = new Template(Manager.class.getResource("ManagerMails.templ"));
137
138     HashMap<String, LinkedList<String>> emails = new HashMap<>();
139
140     private static TreeSet<String> pingExempt = new TreeSet<>();
141
142     public static Manager getInstance() {
143         if (instance == null) {
144             instance = new Manager();
145         }
146         return instance;
147     }
148
149     public static class MailFetcher extends EmailProvider {
150
151         public MailFetcher(Properties p) {}
152
153         @Override
154         public String checkEmailServer(int forUid, String address) throws IOException {
155             return OK;
156         }
157
158         @Override
159         public synchronized void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
160             HashMap<String, LinkedList<String>> mails = Manager.getInstance().emails;
161             LinkedList<String> hismails = mails.get(to);
162             if (hismails == null) {
163                 mails.put(to, hismails = new LinkedList<>());
164             }
165             hismails.addFirst(subject + "\n" + message);
166         }
167
168     }
169
170     public class PingerFetcher extends DomainPinger {
171
172         private DomainPingType dpt;
173
174         public PingerFetcher(DomainPingType dpt) {
175             this.dpt = dpt;
176         }
177
178         @Override
179         public void ping(Domain domain, String configuration, CertificateOwner target, int confId) {
180             System.out.println("Test: " + domain);
181             if (pingExempt.contains(domain.getSuffix())) {
182                 enterPingResult(confId, DomainPinger.PING_SUCCEDED, "Succeeded by TestManager pass-by", null);
183             } else {
184                 dps.get(dpt).ping(domain, configuration, target, confId);
185             }
186         }
187
188     }
189
190     public void batchCreateUsers(String mailPrefix, String domain, int amount, PrintWriter out) {
191
192         try {
193             if (amount > 100) {
194                 out.print("100 at most, please.");
195                 return;
196             }
197             for (int i = 0; i < amount; i++) {
198                 String email = mailPrefix + i + "@" + domain;
199                 createUser(email);
200             }
201         } catch (ReflectiveOperationException e) {
202             out.println("failed");
203             e.printStackTrace();
204         } catch (GigiApiException e) {
205             out.println("failed: " + e.getMessage());
206             e.printStackTrace();
207         }
208     }
209
210     private void createUser(String email) throws GigiApiException, IllegalAccessException {
211         Calendar gc = GregorianCalendar.getInstance();
212         gc.set(1990, 0, 1);
213         User u = new User(email, "xvXV12°§", new Name("Först", "Läst", "Müddle", "Süffix"), new Date(gc.getTime().getTime()), Locale.ENGLISH);
214         EmailAddress ea = u.getEmails()[0];
215         if (f == null) {
216             System.out.println("verification failed");
217             return;
218         }
219         String hash = (String) f.get(ea);
220
221         ea.verify(hash);
222     }
223
224     User[] assurers = new User[25];
225
226     @Override
227     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
228         if (req.getParameter("create") != null) {
229             batchCreateUsers(req.getParameter("prefix"), req.getParameter("suffix"), Integer.parseInt(req.getParameter("amount")), resp.getWriter());
230             resp.getWriter().println("User batch created.");
231         } else if (req.getParameter("addpriv") != null || req.getParameter("delpriv") != null) {
232             User u = User.getByEmail(req.getParameter("email"));
233             if (u == null) {
234                 resp.getWriter().println("User not found.");
235                 return;
236             }
237             if (req.getParameter("addpriv") != null) {
238                 u.grantGroup(u, Group.getByString(req.getParameter("priv")));
239                 resp.getWriter().println("Privilege granted");
240             } else {
241                 u.revokeGroup(u, Group.getByString(req.getParameter("priv")));
242                 resp.getWriter().println("Privilege revoked");
243             }
244         } else if (req.getParameter("fetch") != null) {
245             String mail = req.getParameter("femail");
246             fetchMails(req, resp, mail);
247         } else if (req.getParameter("cats") != null) {
248             String mail = req.getParameter("catsEmail");
249             User byEmail = User.getByEmail(mail);
250             if (byEmail == null) {
251                 resp.getWriter().println("User not found.");
252                 return;
253             }
254             passCATS(byEmail);
255             resp.getWriter().println("User has been passed CATS");
256         } else if (req.getParameter("assure") != null) {
257             String mail = req.getParameter("assureEmail");
258             User byEmail = User.getByEmail(mail);
259             if (byEmail == null) {
260                 resp.getWriter().println("User not found.");
261                 return;
262             }
263             try {
264                 for (int i = 0; i < 10; i++) {
265                     Notary.assure(getAssurer(i), byEmail, byEmail.getName(), byEmail.getDoB(), 10, "Testmanager Assure up code", "2014-11-06", AssuranceType.FACE_TO_FACE);
266                 }
267             } catch (GigiApiException e) {
268                 throw new Error(e);
269             }
270             resp.getWriter().println("User has been assured.");
271         } else if (req.getParameter("letassure") != null) {
272             String mail = req.getParameter("letassureEmail");
273             User byEmail = User.getByEmail(mail);
274             try {
275                 for (int i = 0; i < 25; i++) {
276                     User a = getAssurer(i);
277                     Notary.assure(byEmail, a, a.getName(), a.getDoB(), 10, "Testmanager exp up code", "2014-11-06", AssuranceType.FACE_TO_FACE);
278                 }
279             } catch (GigiApiException e) {
280                 throw new Error(e);
281             }
282         } else if (req.getParameter("addEmail") != null) {
283             User u = User.getByEmail(req.getParameter("addEmailEmail"));
284             try {
285                 EmailAddress ea = new EmailAddress(u, req.getParameter("addEmailNew"), Locale.ENGLISH);
286                 if (f != null) {
287                     String hash = (String) f.get(ea);
288                     ea.verify(hash);
289                     resp.getWriter().println("Email added and verified");
290                 } else {
291                     resp.getWriter().println("Email added but verificatio failed.");
292                 }
293             } catch (IllegalArgumentException e) {
294                 e.printStackTrace();
295                 resp.getWriter().println("An internal error occured.");
296             } catch (IllegalAccessException e) {
297                 e.printStackTrace();
298                 resp.getWriter().println("An internal error occured.");
299             } catch (GigiApiException e) {
300                 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH));
301             }
302         } else if (req.getParameter("addCert") != null) {
303             User u = User.getByEmail(req.getParameter("addCertEmail"));
304             try {
305                 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
306                 kpg.initialize(4096);
307                 KeyPair kp = kpg.generateKeyPair();
308                 SPKAC s = new SPKAC((X509Key) kp.getPublic(), "challange");
309                 Signature sign = Signature.getInstance("SHA512withRSA");
310                 sign.initSign(kp.getPrivate());
311
312                 byte[] res = s.getEncoded(sign);
313
314                 CertificateRequest cr = new CertificateRequest(new AuthorizationContext(u, u), Base64.getEncoder().encodeToString(res), "challange");
315                 cr.update(CertificateRequest.DEFAULT_CN, Digest.SHA512.toString(), "client", null, "", "email:" + u.getEmail(), resp.getWriter(), req);
316                 Certificate draft = cr.draft();
317                 draft.issue(null, "2y", u).waitFor(10000);
318                 if (draft.getStatus() == CertificateStatus.ISSUED) {
319                     resp.getWriter().println("added certificate");
320                 } else {
321                     resp.getWriter().println("signer failed");
322                 }
323             } catch (GeneralSecurityException e1) {
324                 e1.printStackTrace();
325                 resp.getWriter().println("error");
326             } catch (GigiApiException e) {
327                 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH));
328             } catch (InterruptedException e) {
329                 e.printStackTrace();
330                 resp.getWriter().println("interrupted");
331             }
332
333         } else if (req.getParameter("addExDom") != null) {
334             String dom = req.getParameter("exemtDom");
335             pingExempt.add(dom);
336             resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
337             resp.getWriter().println(pingExempt);
338         } else if (req.getParameter("delExDom") != null) {
339             String dom = req.getParameter("exemtDom");
340             pingExempt.remove(dom);
341             resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
342             resp.getWriter().println(pingExempt);
343         }
344     }
345
346     private void fetchMails(HttpServletRequest req, HttpServletResponse resp, String mail) throws IOException {
347         final LinkedList<String> mails = emails.get(mail);
348         HashMap<String, Object> vars = new HashMap<>();
349         vars.put("mail", mail);
350         if (mails != null) {
351             vars.put("mails", new IterableDataset() {
352
353                 Iterator<String> s = mails.iterator();
354
355                 @Override
356                 public boolean next(Language l, Map<String, Object> vars) {
357                     if ( !s.hasNext()) {
358                         return false;
359                     }
360                     vars.put("body", s.next().replaceAll("(https?://\\S+)", "<a href=\"$1\">$1</a>"));
361                     return true;
362                 }
363             });
364         }
365         t.output(resp.getWriter(), getLanguage(req), vars);
366         if (mails == null) {
367             resp.getWriter().println("No mails");
368
369         }
370     }
371
372     private Template form = new Template(Manager.class.getResource("Manager.templ"));
373
374     @Override
375     public boolean needsLogin() {
376         return false;
377     }
378
379     @Override
380     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
381         String pi = req.getPathInfo().substring(PATH.length());
382         if (pi.length() > 1 && pi.startsWith("/fetch-")) {
383             String mail = pi.substring(pi.indexOf('-', 2) + 1);
384             fetchMails(req, resp, mail);
385             return;
386         }
387
388         form.output(resp.getWriter(), getLanguage(req), new HashMap<String, Object>());
389     }
390 }