upd: terminology in code
[gigi.git] / util-testing / club / wpia / gigi / pages / Manager.java
1 package club.wpia.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.text.SimpleDateFormat;
11 import java.util.Base64;
12 import java.util.Calendar;
13 import java.util.Date;
14 import java.util.GregorianCalendar;
15 import java.util.HashMap;
16 import java.util.Iterator;
17 import java.util.LinkedList;
18 import java.util.List;
19 import java.util.Locale;
20 import java.util.Map;
21 import java.util.Properties;
22 import java.util.Random;
23 import java.util.TreeSet;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26
27 import javax.servlet.http.HttpServletRequest;
28 import javax.servlet.http.HttpServletResponse;
29
30 import club.wpia.gigi.Gigi;
31 import club.wpia.gigi.GigiApiException;
32 import club.wpia.gigi.crypto.SPKAC;
33 import club.wpia.gigi.database.GigiPreparedStatement;
34 import club.wpia.gigi.dbObjects.CATS;
35 import club.wpia.gigi.dbObjects.CATS.CATSType;
36 import club.wpia.gigi.dbObjects.Certificate;
37 import club.wpia.gigi.dbObjects.Certificate.CertificateStatus;
38 import club.wpia.gigi.dbObjects.CertificateOwner;
39 import club.wpia.gigi.dbObjects.Country;
40 import club.wpia.gigi.dbObjects.Digest;
41 import club.wpia.gigi.dbObjects.Domain;
42 import club.wpia.gigi.dbObjects.DomainPingType;
43 import club.wpia.gigi.dbObjects.EmailAddress;
44 import club.wpia.gigi.dbObjects.Group;
45 import club.wpia.gigi.dbObjects.NamePart;
46 import club.wpia.gigi.dbObjects.NamePart.NamePartType;
47 import club.wpia.gigi.dbObjects.User;
48 import club.wpia.gigi.dbObjects.Verification.VerificationType;
49 import club.wpia.gigi.email.DelegateMailProvider;
50 import club.wpia.gigi.localisation.Language;
51 import club.wpia.gigi.output.template.IterableDataset;
52 import club.wpia.gigi.output.template.Template;
53 import club.wpia.gigi.pages.account.certs.CertificateRequest;
54 import club.wpia.gigi.ping.DomainPinger;
55 import club.wpia.gigi.ping.PingerDaemon;
56 import club.wpia.gigi.util.AuthorizationContext;
57 import club.wpia.gigi.util.DayDate;
58 import club.wpia.gigi.util.HTMLEncoder;
59 import club.wpia.gigi.util.Notary;
60 import club.wpia.gigi.util.TimeConditions;
61 import sun.security.x509.X509Key;
62
63 public class Manager extends Page {
64
65     public static String validVerificationDateString() {
66         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
67         Calendar c = Calendar.getInstance();
68         c.setTimeInMillis(System.currentTimeMillis());
69         c.add(Calendar.MONTH, -Notary.LIMIT_MAX_MONTHS_VERIFICATION + 1);
70         return sdf.format(new Date(c.getTimeInMillis()));
71     }
72
73     public static Country getRandomCountry() {
74         List<Country> cc = Country.getCountries();
75         int rnd = new Random().nextInt(cc.size());
76         return cc.get(rnd);
77     }
78
79     public static final String PATH = "/manager";
80
81     private static HashMap<DomainPingType, DomainPinger> dps;
82
83     private Manager() {
84         super("Test Manager");
85
86         try {
87             Field gigiInstance = Gigi.class.getDeclaredField("instance");
88             gigiInstance.setAccessible(true);
89             Gigi g = (Gigi) gigiInstance.get(null);
90
91             Field gigiPinger = Gigi.class.getDeclaredField("pinger");
92             gigiPinger.setAccessible(true);
93             PingerDaemon pd = (PingerDaemon) gigiPinger.get(g);
94
95             Field f = PingerDaemon.class.getDeclaredField("pingers");
96             f.setAccessible(true);
97             dps = (HashMap<DomainPingType, DomainPinger>) f.get(pd);
98             HashMap<DomainPingType, DomainPinger> pingers = new HashMap<>();
99             for (DomainPingType dpt : DomainPingType.values()) {
100                 pingers.put(dpt, new PingerFetcher(dpt));
101             }
102             f.set(pd, pingers);
103         } catch (ReflectiveOperationException e) {
104             e.printStackTrace();
105         }
106     }
107
108     public User getSupporter() {
109         if (supporter != null) {
110             return supporter;
111         }
112         try {
113             User u = createAgent( -1);
114             if ( !u.isInGroup(Group.SUPPORTER)) {
115                 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
116                     ps.setInt(1, u.getId());
117                     ps.setString(2, Group.SUPPORTER.getDBName());
118                     ps.setInt(3, u.getId());
119                     ps.execute();
120                 }
121                 u.refreshGroups();
122             }
123             supporter = u;
124         } catch (ReflectiveOperationException | GigiApiException e) {
125             e.printStackTrace();
126         }
127         return supporter;
128     }
129
130     public User getAgent(int i) {
131         if (agents[i] != null) {
132             return agents[i];
133         }
134         try {
135             User u = createAgent(i);
136             agents[i] = u;
137
138         } catch (ReflectiveOperationException | GigiApiException e) {
139             e.printStackTrace();
140         }
141         return agents[i];
142     }
143
144     private User createAgent(int i) throws GigiApiException, IllegalAccessException {
145         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?, `country`=?")) {
146             String mail = "test-agent" + i + "@example.com";
147             User u = User.getByEmail(mail);
148             if (u == null) {
149                 System.out.println("Creating RA-Agent");
150                 createUser(mail);
151                 u = User.getByEmail(mail);
152                 passCATS(u, CATSType.AGENT_CHALLENGE);
153                 ps.setInt(1, u.getId());
154                 ps.setInt(2, u.getPreferredName().getId());
155                 ps.setInt(3, 100);
156                 ps.setString(4, "Manager init code");
157                 ps.setString(5, "1990-01-01");
158                 ps.setString(6, getRandomCountry().getCode());
159                 ps.execute();
160             }
161             return u;
162         }
163     }
164
165     private void passCATS(User u, CATSType t) {
166         CATS.enterResult(u, t, new Date(System.currentTimeMillis()), "en_EN", "1");
167     }
168
169     private static Manager instance;
170
171     private static final Template t = new Template(Manager.class.getResource("ManagerMails.templ"));
172
173     HashMap<String, LinkedList<String>> emails = new HashMap<>();
174
175     private static TreeSet<String> pingExempt = new TreeSet<>();
176
177     public static Manager getInstance() {
178         if (instance == null) {
179             instance = new Manager();
180         }
181         return instance;
182     }
183
184     public static class MailFetcher extends DelegateMailProvider {
185
186         Pattern[] toForward;
187
188         public MailFetcher(Properties props) {
189             super(props, props.getProperty("emailProvider.manager.target"));
190             String str = props.getProperty("emailProvider.manager.filter");
191             if (str == null) {
192                 toForward = new Pattern[0];
193             } else {
194                 String[] parts = str.split(" ");
195                 toForward = new Pattern[parts.length];
196                 for (int i = 0; i < parts.length; i++) {
197                     toForward[i] = Pattern.compile(parts[i]);
198                 }
199             }
200         }
201
202         @Override
203         public String checkEmailServer(int forUid, String address) throws IOException {
204             return OK;
205         }
206
207         @Override
208         public synchronized void sendMail(String to, String subject, String message, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
209             HashMap<String, LinkedList<String>> mails = Manager.getInstance().emails;
210             LinkedList<String> hismails = mails.get(to);
211             if (hismails == null) {
212                 mails.put(to, hismails = new LinkedList<>());
213             }
214             hismails.addFirst(subject + "\n" + message);
215             for (int i = 0; i < toForward.length; i++) {
216                 if (toForward[i].matcher(to).matches()) {
217                     super.sendMail(to, subject, message, replyto, toname, fromname, errorsto, extra);
218                     return;
219                 }
220             }
221         }
222
223     }
224
225     public class PingerFetcher extends DomainPinger {
226
227         private DomainPingType dpt;
228
229         public PingerFetcher(DomainPingType dpt) {
230             this.dpt = dpt;
231         }
232
233         @Override
234         public void ping(Domain domain, String configuration, CertificateOwner target, int confId) {
235             System.out.println("Test: " + domain);
236             if (pingExempt.contains(domain.getSuffix())) {
237                 enterPingResult(confId, DomainPinger.PING_SUCCEDED, "Succeeded by TestManager pass-by", null);
238             } else {
239                 dps.get(dpt).ping(domain, configuration, target, confId);
240             }
241         }
242
243     }
244
245     public void batchCreateUsers(String mailPrefix, String domain, int amount, PrintWriter out) {
246
247         try {
248             if (amount > 100) {
249                 out.print("100 at most, please.");
250                 return;
251             }
252             for (int i = 0; i < amount; i++) {
253                 String email = mailPrefix + i + "@" + domain;
254                 createUser(email);
255             }
256         } catch (ReflectiveOperationException e) {
257             out.println("failed");
258             e.printStackTrace();
259         } catch (GigiApiException e) {
260             out.println("failed: " + e.getMessage());
261             e.printStackTrace();
262         }
263     }
264
265     private void createUser(String email) throws GigiApiException, IllegalAccessException {
266         Calendar gc = GregorianCalendar.getInstance();
267         gc.setTimeInMillis(0);
268         gc.set(1990, 0, 1);
269
270         Country country = getRandomCountry();
271
272         User u = new User(email, "xvXV12°§", new DayDate(gc.getTime().getTime()), Locale.ENGLISH, country, //
273                 new NamePart(NamePartType.FIRST_NAME, "Först"), new NamePart(NamePartType.FIRST_NAME, "Müddle"), //
274                 new NamePart(NamePartType.LAST_NAME, "Läst"), new NamePart(NamePartType.SUFFIX, "Süffix"));
275         EmailAddress ea = u.getEmails()[0];
276         verify(email, ea);
277     }
278
279     private void verify(String email, EmailAddress ea) throws GigiApiException {
280         LinkedList<String> i = emails.get(email);
281         while (i.size() > 0 && !ea.isVerified()) {
282             String lst = i.getLast();
283             Pattern p = Pattern.compile("hash=([a-zA-Z0-9]+)");
284             Matcher m = p.matcher(lst);
285             if (m.find()) {
286                 ea.verify(m.group(1));
287             }
288             i.removeLast();
289         }
290         // ea.verify(hash);
291     }
292
293     User[] agents = new User[25];
294
295     User supporter;
296
297     @Override
298     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
299         if (req.getParameter("create") != null) {
300             batchCreateUsers(req.getParameter("prefix"), req.getParameter("suffix"), Integer.parseInt(req.getParameter("amount")), resp.getWriter());
301             resp.getWriter().println("User batch created.");
302         } else if (req.getParameter("addpriv") != null || req.getParameter("delpriv") != null) {
303             User u = User.getByEmail(req.getParameter("email"));
304             if (u == null) {
305                 resp.getWriter().println("User not found.");
306                 return;
307             }
308             try {
309                 if (req.getParameter("addpriv") != null) {
310                     u.grantGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
311                     resp.getWriter().println("Privilege granted");
312                 } else {
313                     u.revokeGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
314                     resp.getWriter().println("Privilege revoked");
315                 }
316             } catch (GigiApiException e) {
317                 throw new Error(e);
318             }
319         } else if (req.getParameter("fetch") != null) {
320             String mail = req.getParameter("femail");
321             fetchMails(req, resp, mail);
322         } else if (req.getParameter("cats") != null) {
323             String mail = req.getParameter("catsEmail");
324             String testId = req.getParameter("catsType");
325             User byEmail = User.getByEmail(mail);
326             if (byEmail == null) {
327                 resp.getWriter().println("User not found.");
328                 return;
329             }
330             if (testId == null) {
331                 resp.getWriter().println("No test given.");
332                 return;
333             }
334             CATSType test = CATSType.values()[Integer.parseInt(testId)];
335             passCATS(byEmail, test);
336             resp.getWriter().println("Test '" + test.getDisplayName() + "' was added to user account.");
337         } else if (req.getParameter("verify") != null) {
338             String mail = req.getParameter("verifyEmail");
339             String verificationPoints = req.getParameter("verificationPoints");
340             User byEmail = User.getByEmail(mail);
341
342             if (byEmail == null) {
343                 resp.getWriter().println("User not found.");
344                 return;
345             }
346
347             int vp = 0;
348             int agentNumber = 0;
349
350             try {
351                 try {
352                     vp = Integer.parseInt(verificationPoints);
353                 } catch (NumberFormatException e) {
354                     throw new GigiApiException("No valid Verification Points entered.");
355                 }
356
357                 if (vp > 100) { // only allow max 100 Verification points
358                     vp = 100;
359                 }
360
361                 while (vp > 0) {
362                     int currentVP = 10;
363                     if (vp < 10) {
364                         currentVP = vp;
365                     }
366                     Notary.verify(getAgent(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
367                     agentNumber += 1;
368                     vp -= currentVP;
369                 }
370
371             } catch (GigiApiException e) {
372                 throw new Error(e);
373             }
374
375             resp.getWriter().println("User has been verified " + agentNumber + " times.");
376
377         } else if (req.getParameter("letverify") != null) {
378             String mail = req.getParameter("letverifyEmail");
379             User byEmail = User.getByEmail(mail);
380             try {
381                 for (int i = 0; i < 25; i++) {
382                     User a = getAgent(i);
383                     Notary.verify(byEmail, a, a.getNames()[0], a.getDoB(), 10, "Testmanager exp up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
384                 }
385             } catch (GigiApiException e) {
386                 throw new Error(e);
387             }
388         } else if (req.getParameter("addEmail") != null) {
389             User u = User.getByEmail(req.getParameter("addEmailEmail"));
390             try {
391                 EmailAddress ea = new EmailAddress(u, req.getParameter("addEmailNew"), Locale.ENGLISH);
392                 verify(ea.getAddress(), ea);
393             } catch (IllegalArgumentException e) {
394                 e.printStackTrace();
395                 resp.getWriter().println("An internal error occured.");
396             } catch (GigiApiException e) {
397                 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH));
398             }
399         } else if (req.getParameter("addCert") != null) {
400             User u = User.getByEmail(req.getParameter("addCertEmail"));
401             try {
402                 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
403                 kpg.initialize(4096);
404                 KeyPair kp = kpg.generateKeyPair();
405                 SPKAC s = new SPKAC((X509Key) kp.getPublic(), "challenge");
406                 Signature sign = Signature.getInstance("SHA512withRSA");
407                 sign.initSign(kp.getPrivate());
408
409                 byte[] res = s.getEncoded(sign);
410
411                 CertificateRequest cr = new CertificateRequest(new AuthorizationContext(u, u), Base64.getEncoder().encodeToString(res), "challenge");
412                 cr.update(CertificateRequest.DEFAULT_CN, Digest.SHA512.toString(), "client", null, "", "email:" + u.getEmail());
413                 Certificate draft = cr.draft();
414                 draft.issue(null, "2y", u).waitFor(10000);
415                 if (draft.getStatus() == CertificateStatus.ISSUED) {
416                     resp.getWriter().println("added certificate");
417                 } else {
418                     resp.getWriter().println("signer failed");
419                 }
420             } catch (GeneralSecurityException e1) {
421                 e1.printStackTrace();
422                 resp.getWriter().println("error");
423             } catch (GigiApiException e) {
424                 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH));
425             }
426
427         } else if (req.getParameter("addExDom") != null) {
428             String dom = req.getParameter("exemptDom");
429             pingExempt.add(dom);
430             resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
431             resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
432         } else if (req.getParameter("delExDom") != null) {
433             String dom = req.getParameter("exemptDom");
434             pingExempt.remove(dom);
435             resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
436             resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
437         }
438     }
439
440     private void fetchMails(HttpServletRequest req, HttpServletResponse resp, String mail) throws IOException {
441         final LinkedList<String> mails = emails.get(mail);
442         HashMap<String, Object> vars = new HashMap<>();
443         vars.put("mail", mail);
444         if (mails != null) {
445             vars.put("mails", new IterableDataset() {
446
447                 Iterator<String> s = mails.iterator();
448
449                 @Override
450                 public boolean next(Language l, Map<String, Object> vars) {
451                     if ( !s.hasNext()) {
452                         return false;
453                     }
454                     vars.put("body", s.next().replaceAll("(https?://\\S+)", "<a href=\"$1\">$1</a>"));
455                     return true;
456                 }
457             });
458         }
459         t.output(resp.getWriter(), getLanguage(req), vars);
460         if (mails == null) {
461             resp.getWriter().println("No mails");
462
463         }
464     }
465
466     private static final Template form = new Template(Manager.class.getResource("Manager.templ"));
467
468     @Override
469     public boolean needsLogin() {
470         return false;
471     }
472
473     @Override
474     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
475         String pi = req.getPathInfo().substring(PATH.length());
476         if (pi.length() > 1 && pi.startsWith("/fetch-")) {
477             String mail = pi.substring(pi.indexOf('-', 2) + 1);
478             fetchMails(req, resp, mail);
479             return;
480         }
481         HashMap<String, Object> vars = new HashMap<>();
482         vars.put("cats_types", new IterableDataset() {
483
484             CATSType[] type = CATSType.values();
485
486             int i = 0;
487
488             @Override
489             public boolean next(Language l, Map<String, Object> vars) {
490                 if (i >= type.length) {
491                     return false;
492                 }
493                 CATSType t = type[i++];
494                 vars.put("id", i - 1);
495                 vars.put("name", t.getDisplayName());
496                 return true;
497             }
498         });
499
500         vars.put("testValidMonths", TimeConditions.getInstance().getTestMonths());
501         vars.put("reverificationDays", TimeConditions.getInstance().getVerificationLimitDays());
502         vars.put("verificationFreshMonths", TimeConditions.getInstance().getVerificationMonths());
503         vars.put("verificationMaxAgeMonths", TimeConditions.getInstance().getVerificationMaxAgeMonths());
504         vars.put("emailPingMonths", TimeConditions.getInstance().getEmailPingMonths());
505
506         form.output(resp.getWriter(), getLanguage(req), vars);
507     }
508 }