1 package club.wpia.gigi.pages;
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.Timestamp;
11 import java.text.SimpleDateFormat;
12 import java.util.Base64;
13 import java.util.Calendar;
14 import java.util.Date;
15 import java.util.GregorianCalendar;
16 import java.util.HashMap;
17 import java.util.Iterator;
18 import java.util.LinkedList;
19 import java.util.List;
20 import java.util.Locale;
22 import java.util.Properties;
23 import java.util.Random;
24 import java.util.TreeSet;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
31 import club.wpia.gigi.Gigi;
32 import club.wpia.gigi.GigiApiException;
33 import club.wpia.gigi.crypto.SPKAC;
34 import club.wpia.gigi.database.GigiPreparedStatement;
35 import club.wpia.gigi.database.GigiResultSet;
36 import club.wpia.gigi.dbObjects.CATS;
37 import club.wpia.gigi.dbObjects.CATS.CATSType;
38 import club.wpia.gigi.dbObjects.Certificate;
39 import club.wpia.gigi.dbObjects.Certificate.CertificateStatus;
40 import club.wpia.gigi.dbObjects.CertificateOwner;
41 import club.wpia.gigi.dbObjects.Contract;
42 import club.wpia.gigi.dbObjects.Contract.ContractType;
43 import club.wpia.gigi.dbObjects.Country;
44 import club.wpia.gigi.dbObjects.Digest;
45 import club.wpia.gigi.dbObjects.Domain;
46 import club.wpia.gigi.dbObjects.DomainPingConfiguration;
47 import club.wpia.gigi.dbObjects.DomainPingExecution;
48 import club.wpia.gigi.dbObjects.DomainPingType;
49 import club.wpia.gigi.dbObjects.EmailAddress;
50 import club.wpia.gigi.dbObjects.Group;
51 import club.wpia.gigi.dbObjects.Name;
52 import club.wpia.gigi.dbObjects.NamePart;
53 import club.wpia.gigi.dbObjects.NamePart.NamePartType;
54 import club.wpia.gigi.dbObjects.User;
55 import club.wpia.gigi.dbObjects.Verification.VerificationType;
56 import club.wpia.gigi.email.DelegateMailProvider;
57 import club.wpia.gigi.email.EmailProvider;
58 import club.wpia.gigi.localisation.Language;
59 import club.wpia.gigi.output.template.IterableDataset;
60 import club.wpia.gigi.output.template.Template;
61 import club.wpia.gigi.pages.account.certs.CertificateRequest;
62 import club.wpia.gigi.ping.DomainPinger;
63 import club.wpia.gigi.ping.PingerDaemon;
64 import club.wpia.gigi.util.AuthorizationContext;
65 import club.wpia.gigi.util.DayDate;
66 import club.wpia.gigi.util.DomainAssessment;
67 import club.wpia.gigi.util.HTMLEncoder;
68 import club.wpia.gigi.util.Notary;
69 import club.wpia.gigi.util.TimeConditions;
70 import sun.security.x509.X509Key;
72 public class Manager extends Page {
74 public static String validVerificationDateString() {
75 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
76 Calendar c = Calendar.getInstance();
77 c.setTimeInMillis(System.currentTimeMillis());
78 c.add(Calendar.MONTH, -Notary.LIMIT_MAX_MONTHS_VERIFICATION + 1);
79 return sdf.format(new Date(c.getTimeInMillis()));
82 public static Country getRandomCountry() {
83 List<Country> cc = Country.getCountries();
84 int rnd = new Random().nextInt(cc.size());
88 public static final String PATH = "/manager";
90 private static HashMap<DomainPingType, DomainPinger> dps;
93 super("Test Manager");
96 Field gigiInstance = Gigi.class.getDeclaredField("instance");
97 gigiInstance.setAccessible(true);
98 Gigi g = (Gigi) gigiInstance.get(null);
100 Field gigiPinger = Gigi.class.getDeclaredField("pinger");
101 gigiPinger.setAccessible(true);
102 PingerDaemon pd = (PingerDaemon) gigiPinger.get(g);
104 Field f = PingerDaemon.class.getDeclaredField("pingers");
105 f.setAccessible(true);
106 dps = (HashMap<DomainPingType, DomainPinger>) f.get(pd);
107 HashMap<DomainPingType, DomainPinger> pingers = new HashMap<>();
108 for (DomainPingType dpt : DomainPingType.values()) {
109 pingers.put(dpt, new PingerFetcher(dpt));
112 } catch (ReflectiveOperationException e) {
117 public User getSupporter() {
118 if (supporter != null) {
122 User u = createAgent( -1);
123 if ( !u.isInGroup(Group.SUPPORTER)) {
124 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
125 ps.setInt(1, u.getId());
126 ps.setString(2, Group.SUPPORTER.getDBName());
127 ps.setInt(3, u.getId());
133 } catch (ReflectiveOperationException | GigiApiException e) {
139 public User getAgent(int i) {
140 if (agents[i] != null) {
144 User u = createAgent(i);
147 } catch (ReflectiveOperationException | GigiApiException e) {
153 private User createAgent(int i) throws GigiApiException, IllegalAccessException {
154 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?, `country`=?")) {
155 String mail = "test-agent" + i + "@example.com";
156 User u = User.getByEmail(mail);
158 System.out.println("Creating RA-Agent");
160 u = User.getByEmail(mail);
161 passCATS(u, CATSType.AGENT_CHALLENGE);
162 ps.setInt(1, u.getId());
163 ps.setInt(2, u.getPreferredName().getId());
165 ps.setString(4, "Manager init code");
166 ps.setString(5, "1990-01-01");
167 ps.setString(6, getRandomCountry().getCode());
170 new Contract(u, ContractType.RA_AGENT_CONTRACT);
175 private void passCATS(User u, CATSType t) {
176 CATS.enterResult(u, t, new Date(System.currentTimeMillis()), "en_EN", "1");
179 private void expireCATS(User u, CATSType t) {
180 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `cats_passed` WHERE `user_id`=? AND `variant_id`=? AND `pass_date`>?")) {
181 ps.setInt(1, u.getId());
182 ps.setInt(2, t.getId());
183 ps.setTimestamp(3, new Timestamp(System.currentTimeMillis() - DayDate.MILLI_DAY * 366));
185 GigiResultSet rs = ps.executeQuery();
187 GigiPreparedStatement ps1 = new GigiPreparedStatement("UPDATE `cats_passed` SET `pass_date`=? WHERE `id`=?");
188 ps1.setTimestamp(1, new Timestamp(System.currentTimeMillis() - DayDate.MILLI_DAY * 367));
189 ps1.setInt(2, rs.getInt(1));
197 private static Manager instance;
199 private static final Template t = new Template(Manager.class.getResource("ManagerMails.templ"));
201 HashMap<String, LinkedList<String>> emails = new HashMap<>();
203 private static TreeSet<String> pingExempt = new TreeSet<>();
205 public static Manager getInstance() {
206 if (instance == null) {
207 instance = new Manager();
212 public static class MailFetcher extends DelegateMailProvider {
216 public MailFetcher(Properties props) {
217 super(props, props.getProperty("emailProvider.manager.target"));
218 String str = props.getProperty("emailProvider.manager.filter");
220 toForward = new Pattern[0];
222 String[] parts = str.split(" ");
223 toForward = new Pattern[parts.length];
224 for (int i = 0; i < parts.length; i++) {
225 toForward[i] = Pattern.compile(parts[i]);
231 public String checkEmailServer(int forUid, String address) throws IOException {
236 public synchronized void sendMail(String to, String subject, String message, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
237 HashMap<String, LinkedList<String>> mails = Manager.getInstance().emails;
238 LinkedList<String> hismails = mails.get(to);
239 if (hismails == null) {
240 mails.put(to, hismails = new LinkedList<>());
242 hismails.addFirst(subject + "\n" + message);
243 for (int i = 0; i < toForward.length; i++) {
244 if (toForward[i].matcher(to).matches()) {
245 super.sendMail(to, subject, message, replyto, toname, fromname, errorsto, extra);
253 public class PingerFetcher extends DomainPinger {
255 private DomainPingType dpt;
257 public PingerFetcher(DomainPingType dpt) {
262 public DomainPingExecution ping(Domain domain, String configuration, CertificateOwner target, DomainPingConfiguration conf) {
263 System.err.println("TestManager: " + domain.getSuffix());
264 if (pingExempt.contains(domain.getSuffix())) {
265 return enterPingResult(conf, DomainPinger.PING_SUCCEDED, "Succeeded by TestManager pass-by", null);
267 DomainPinger pinger = dps.get(dpt);
268 System.err.println("Forward to old pinger: " + pinger);
269 return pinger.ping(domain, configuration, target, conf);
275 public void batchCreateUsers(String mailPrefix, String domain, int amount, PrintWriter out) {
279 out.print("100 at most, please.");
282 for (int i = 0; i < amount; i++) {
283 String email = mailPrefix + i + "@" + domain;
286 } catch (ReflectiveOperationException e) {
287 out.println("failed");
289 } catch (GigiApiException e) {
290 out.println("failed: " + e.getMessage());
295 private void createUser(String email) throws GigiApiException, IllegalAccessException {
296 Calendar gc = GregorianCalendar.getInstance();
297 gc.setTimeInMillis(0);
300 Country country = getRandomCountry();
302 User u = new User(email, "xvXV12°§", new DayDate(gc.getTime().getTime()), Locale.ENGLISH, country, //
303 new NamePart(NamePartType.FIRST_NAME, "Först"), new NamePart(NamePartType.FIRST_NAME, "Müddle"), //
304 new NamePart(NamePartType.LAST_NAME, "Läst"), new NamePart(NamePartType.SUFFIX, "Süffix"));
305 EmailAddress ea = u.getEmails()[0];
309 private void verify(String email, EmailAddress ea) throws GigiApiException {
310 LinkedList<String> i = emails.get(email);
311 while (i.size() > 0 && !ea.isVerified()) {
312 String lst = i.getLast();
313 Pattern p = Pattern.compile("hash=([a-zA-Z0-9]+)");
314 Matcher m = p.matcher(lst);
316 ea.verify(m.group(1));
323 User[] agents = new User[25];
328 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
329 AuthorizationContext sessionAc = (AuthorizationContext) req.getSession().getAttribute(Gigi.AUTH_CONTEXT);
330 if (req.getParameter("create") != null) {
331 String prefix = req.getParameter("prefix");
332 String domain = req.getParameter("suffix");
334 if (null == prefix) {
335 throw new GigiApiException("No prefix given.");
337 if (null == domain) {
338 throw new GigiApiException("No domain given.");
341 DomainAssessment.checkCertifiableDomain(domain, false, true);
343 if ( !EmailProvider.isValidMailAddress(prefix + "@" + domain)) {
344 throw new GigiApiException("Invalid email address template.");
347 batchCreateUsers(prefix, domain, Integer.parseInt(req.getParameter("amount")), resp.getWriter());
348 resp.getWriter().println("User batch created.");
349 } catch (GigiApiException e) {
352 } else if (req.getParameter("addpriv") != null || req.getParameter("delpriv") != null) {
353 User u = User.getByEmail(req.getParameter("email"));
355 resp.getWriter().println("User not found.");
359 if (req.getParameter("addpriv") != null) {
360 u.grantGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
361 resp.getWriter().println("Privilege granted");
363 u.revokeGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
364 resp.getWriter().println("Privilege revoked");
366 } catch (GigiApiException e) {
369 } else if (req.getParameter("fetch") != null) {
370 String mail = req.getParameter("femail");
371 fetchMails(req, resp, mail);
372 } else if (req.getParameter("cats") != null) {
373 String mail = req.getParameter("catsEmail");
374 String testId = req.getParameter("catsType");
375 User byEmail = User.getByEmail(mail);
376 if (byEmail == null) {
377 resp.getWriter().println("User not found.");
380 if (testId == null) {
381 resp.getWriter().println("No test given.");
384 CATSType test = CATSType.values()[Integer.parseInt(testId)];
385 passCATS(byEmail, test);
386 resp.getWriter().println("Test '" + test.getDisplayName() + "' was added to user account.");
387 } else if (req.getParameter("catsexpire") != null) {
388 String mail = req.getParameter("catsEmail");
389 String testId = req.getParameter("catsType");
390 User byEmail = User.getByEmail(mail);
391 if (byEmail == null) {
392 resp.getWriter().println("User not found.");
395 if (testId == null) {
396 resp.getWriter().println("No test given.");
399 CATSType test = CATSType.values()[Integer.parseInt(testId)];
400 expireCATS(byEmail, test);
401 resp.getWriter().println("Test '" + test.getDisplayName() + "' is set expired for user account.");
402 } else if (req.getParameter("verify") != null) {
403 String mail = req.getParameter("verifyEmail");
404 String verificationPoints = req.getParameter("verificationPoints");
405 User byEmail = User.getByEmail(mail);
407 if (byEmail == null) {
408 resp.getWriter().println("User not found.");
413 int verifications = 0;
418 vp = Integer.parseInt(verificationPoints);
419 } catch (NumberFormatException e) {
420 resp.getWriter().println("The value for Verification Points must be an integer.</br>");
424 int agentNumber = addVerificationPoints(vp, byEmail);
431 if (Notary.checkVerificationIsPossible(getAgent(agentNumber), byEmail.getPreferredName())) {
433 Notary.verify(getAgent(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
439 if (agentNumber >= agents.length) {
440 info = "<br/>The limit of agents is reached. You cannot add any more Verification Points to the preferred name of this user using this method.";
445 } catch (GigiApiException e) {
449 resp.getWriter().println("User has been verified " + verifications + " times." + info);
451 } else if (req.getParameter("verifyexpire") != null) {
452 String mail = req.getParameter("verifyEmail");
453 User byEmail = User.getByEmail(mail);
454 if (byEmail == null) {
455 resp.getWriter().println("User not found.");
458 setVerificationDateToPast(byEmail.getPreferredName());
461 resp.getWriter().println("Verification set to time past the limit.");
462 } else if (req.getParameter("letverify") != null) {
463 String mail = req.getParameter("letverifyEmail");
464 User byEmail = User.getByEmail(mail);
465 if (byEmail == null || !byEmail.canVerify()) {
466 resp.getWriter().println("User not found, or found user is not allowed to verify.");
469 for (int i = 0; i < 25; i++) {
470 User a = getAgent(i);
471 Notary.verify(byEmail, a, a.getNames()[0], a.getDoB(), 10, "Testmanager exp up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
473 resp.getWriter().println("Successfully added experience points.");
474 } catch (GigiApiException e) {
478 } else if (req.getParameter("addEmail") != null) {
479 User u = User.getByEmail(req.getParameter("addEmailEmail"));
481 EmailAddress ea = new EmailAddress(u, req.getParameter("addEmailNew"), Locale.ENGLISH);
482 verify(ea.getAddress(), ea);
483 } catch (IllegalArgumentException e) {
485 resp.getWriter().println("An internal error occured.");
486 } catch (GigiApiException e) {
487 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
489 } else if (req.getParameter("addCert") != null) {
490 User u = User.getByEmail(req.getParameter("addCertEmail"));
492 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
493 kpg.initialize(4096);
494 KeyPair kp = kpg.generateKeyPair();
495 SPKAC s = new SPKAC((X509Key) kp.getPublic(), "challenge");
496 Signature sign = Signature.getInstance("SHA512withRSA");
497 sign.initSign(kp.getPrivate());
499 byte[] res = s.getEncoded(sign);
501 CertificateRequest cr = new CertificateRequest(new AuthorizationContext(u, u, sessionAc.isStronglyAuthenticated()), Base64.getEncoder().encodeToString(res), "challenge");
502 cr.update(CertificateRequest.DEFAULT_CN, Digest.SHA512.toString(), "client", null, "", "email:" + u.getEmail());
503 Certificate draft = cr.draft();
504 draft.issue(null, "2y", u).waitFor(10000);
505 if (draft.getStatus() == CertificateStatus.ISSUED) {
506 resp.getWriter().println("added certificate");
508 resp.getWriter().println("signer failed");
510 } catch (GeneralSecurityException e1) {
511 e1.printStackTrace();
512 resp.getWriter().println("error");
513 } catch (GigiApiException e) {
514 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
517 } else if (req.getParameter("addExDom") != null) {
518 String dom = req.getParameter("exemptDom");
520 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
521 resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
522 } else if (req.getParameter("delExDom") != null) {
523 String dom = req.getParameter("exemptDom");
524 pingExempt.remove(dom);
525 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
526 resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
527 } else if (req.getParameter("makeAgent") != null) {
528 User u = User.getByEmail(req.getParameter("agentEmail"));
530 resp.getWriter().println("User not found, or found user is not allowed to verify.");
532 if (u.getVerificationPoints() < 100) {
533 addVerificationPoints(100, u);
535 if ( !u.hasPassedCATS()) {
536 passCATS(u, CATSType.AGENT_CHALLENGE);
538 if ( !Contract.hasSignedContract(u, Contract.ContractType.RA_AGENT_CONTRACT)) {
540 new Contract(u, Contract.ContractType.RA_AGENT_CONTRACT);
541 } catch (GigiApiException e) {
545 resp.getWriter().println("User has all requirements to be an RA Agent");
548 resp.getWriter().println("<br/><a href='" + PATH + "'>Go back</a>");
551 private int addVerificationPoints(int vp, User byEmail) throws Error {
555 if (vp > 100) { // only allow max 100 Verification points
564 Notary.verify(getAgent(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
569 } catch (GigiApiException e) {
575 private void fetchMails(HttpServletRequest req, HttpServletResponse resp, String mail) throws IOException {
576 final LinkedList<String> mails = emails.get(mail);
577 HashMap<String, Object> vars = new HashMap<>();
578 vars.put("mail", mail);
580 vars.put("mails", new IterableDataset() {
582 Iterator<String> s = mails.iterator();
585 public boolean next(Language l, Map<String, Object> vars) {
589 vars.put("body", s.next().replaceAll("(https?://\\S+)", "<a href=\"$1\">$1</a>"));
594 t.output(resp.getWriter(), getLanguage(req), vars);
596 resp.getWriter().println("No mails");
601 private static final Template form = new Template(Manager.class.getResource("Manager.templ"));
604 public boolean needsLogin() {
609 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
610 String pi = req.getPathInfo().substring(PATH.length());
611 if (pi.length() > 1 && pi.startsWith("/fetch-")) {
612 String mail = pi.substring(pi.indexOf('-', 2) + 1);
613 fetchMails(req, resp, mail);
616 HashMap<String, Object> vars = new HashMap<>();
617 vars.put("cats_types", new IterableDataset() {
619 CATSType[] type = CATSType.values();
624 public boolean next(Language l, Map<String, Object> vars) {
625 if (i >= type.length) {
628 CATSType t = type[i++];
629 vars.put("id", i - 1);
630 vars.put("name", t.getDisplayName());
635 vars.put("testValidMonths", TimeConditions.getInstance().getTestMonths());
636 vars.put("reverificationDays", TimeConditions.getInstance().getVerificationLimitDays());
637 vars.put("verificationFreshMonths", TimeConditions.getInstance().getVerificationMonths());
638 vars.put("verificationMaxAgeMonths", TimeConditions.getInstance().getVerificationMaxAgeMonths());
639 vars.put("emailPingMonths", TimeConditions.getInstance().getEmailPingMonths());
641 form.output(resp.getWriter(), getLanguage(req), vars);
644 private static void setVerificationDateToPast(Name name) {
645 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
646 Calendar c = Calendar.getInstance();
647 c.setTimeInMillis(System.currentTimeMillis());
648 c.add(Calendar.MONTH, -TimeConditions.getInstance().getVerificationMonths());
649 String date = sdf.format(new Date(c.getTimeInMillis()));
650 GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `notary` SET `date`=? WHERE `to`=? AND `date`>?");
651 ps.setString(1, date);
652 ps.setInt(2, name.getId());
653 ps.setString(3, date);