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 if ( !Contract.hasSignedContract(u, ContractType.RA_AGENT_CONTRACT)) {
171 new Contract(u, ContractType.RA_AGENT_CONTRACT);
177 private void passCATS(User u, CATSType t) {
178 CATS.enterResult(u, t, new Date(System.currentTimeMillis()), "en_EN", "1");
181 private void expireCATS(User u, CATSType t) {
182 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `cats_passed` WHERE `user_id`=? AND `variant_id`=? AND `pass_date`>?")) {
183 ps.setInt(1, u.getId());
184 ps.setInt(2, t.getId());
185 ps.setTimestamp(3, new Timestamp(System.currentTimeMillis() - DayDate.MILLI_DAY * 366));
187 GigiResultSet rs = ps.executeQuery();
189 GigiPreparedStatement ps1 = new GigiPreparedStatement("UPDATE `cats_passed` SET `pass_date`=? WHERE `id`=?");
190 ps1.setTimestamp(1, new Timestamp(System.currentTimeMillis() - DayDate.MILLI_DAY * 367));
191 ps1.setInt(2, rs.getInt(1));
199 private static Manager instance;
201 private static final Template t = new Template(Manager.class.getResource("ManagerMails.templ"));
203 HashMap<String, LinkedList<String>> emails = new HashMap<>();
205 private static TreeSet<String> pingExempt = new TreeSet<>();
207 public static Manager getInstance() {
208 if (instance == null) {
209 instance = new Manager();
214 public static class MailFetcher extends DelegateMailProvider {
218 public MailFetcher(Properties props) {
219 super(props, props.getProperty("emailProvider.manager.target"));
220 String str = props.getProperty("emailProvider.manager.filter");
222 toForward = new Pattern[0];
224 String[] parts = str.split(" ");
225 toForward = new Pattern[parts.length];
226 for (int i = 0; i < parts.length; i++) {
227 toForward[i] = Pattern.compile(parts[i]);
233 public String checkEmailServer(int forUid, String address) throws IOException {
238 public synchronized void sendMail(String to, String subject, String message, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
239 HashMap<String, LinkedList<String>> mails = Manager.getInstance().emails;
240 LinkedList<String> hismails = mails.get(to);
241 if (hismails == null) {
242 mails.put(to, hismails = new LinkedList<>());
244 hismails.addFirst(subject + "\n" + message);
245 for (int i = 0; i < toForward.length; i++) {
246 if (toForward[i].matcher(to).matches()) {
247 super.sendMail(to, subject, message, replyto, toname, fromname, errorsto, extra);
255 public class PingerFetcher extends DomainPinger {
257 private DomainPingType dpt;
259 public PingerFetcher(DomainPingType dpt) {
264 public DomainPingExecution ping(Domain domain, String configuration, CertificateOwner target, DomainPingConfiguration conf) {
265 System.err.println("TestManager: " + domain.getSuffix());
266 if (pingExempt.contains(domain.getSuffix())) {
267 return enterPingResult(conf, DomainPinger.PING_SUCCEDED, "Succeeded by TestManager pass-by", null);
269 DomainPinger pinger = dps.get(dpt);
270 System.err.println("Forward to old pinger: " + pinger);
271 return pinger.ping(domain, configuration, target, conf);
277 public void batchCreateUsers(String mailPrefix, String domain, int amount, PrintWriter out) {
281 out.print("100 at most, please.");
284 for (int i = 0; i < amount; i++) {
285 String email = mailPrefix + i + "@" + domain;
288 } catch (ReflectiveOperationException e) {
289 out.println("failed");
291 } catch (GigiApiException e) {
292 out.println("failed: " + e.getMessage());
297 private void createUser(String email) throws GigiApiException, IllegalAccessException {
298 Calendar gc = GregorianCalendar.getInstance();
299 gc.setTimeInMillis(0);
302 Country country = getRandomCountry();
304 User u = new User(email, "xvXV12°§", new DayDate(gc.getTime().getTime()), Locale.ENGLISH, country, //
305 new NamePart(NamePartType.FIRST_NAME, "Först"), new NamePart(NamePartType.FIRST_NAME, "Müddle"), //
306 new NamePart(NamePartType.LAST_NAME, "Läst"), new NamePart(NamePartType.SUFFIX, "Süffix"));
307 EmailAddress ea = u.getEmails()[0];
311 private void verify(String email, EmailAddress ea) throws GigiApiException {
312 LinkedList<String> i = emails.get(email);
313 while (i.size() > 0 && !ea.isVerified()) {
314 String lst = i.getLast();
315 Pattern p = Pattern.compile("hash=([a-zA-Z0-9]+)");
316 Matcher m = p.matcher(lst);
318 ea.verify(m.group(1));
325 User[] agents = new User[25];
330 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
331 AuthorizationContext sessionAc = (AuthorizationContext) req.getSession().getAttribute(Gigi.AUTH_CONTEXT);
332 if (req.getParameter("create") != null) {
333 String prefix = req.getParameter("prefix");
334 String domain = req.getParameter("suffix");
336 if (null == prefix) {
337 throw new GigiApiException("No prefix given.");
339 if (null == domain) {
340 throw new GigiApiException("No domain given.");
343 DomainAssessment.checkCertifiableDomain(domain, false, true);
345 if ( !EmailProvider.isValidMailAddress(prefix + "@" + domain)) {
346 throw new GigiApiException("Invalid email address template.");
349 batchCreateUsers(prefix, domain, Integer.parseInt(req.getParameter("amount")), resp.getWriter());
350 resp.getWriter().println("User batch created.");
351 } catch (GigiApiException e) {
354 } else if (req.getParameter("addpriv") != null || req.getParameter("delpriv") != null) {
355 User u = User.getByEmail(req.getParameter("email"));
357 resp.getWriter().println("User not found.");
361 if (req.getParameter("addpriv") != null) {
362 u.grantGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
363 resp.getWriter().println("Privilege granted");
365 u.revokeGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
366 resp.getWriter().println("Privilege revoked");
368 } catch (GigiApiException e) {
371 } else if (req.getParameter("fetch") != null) {
372 String mail = req.getParameter("femail");
373 fetchMails(req, resp, mail);
374 } else if (req.getParameter("cats") != null) {
375 String mail = req.getParameter("catsEmail");
376 String testId = req.getParameter("catsType");
377 User byEmail = User.getByEmail(mail);
378 if (byEmail == null) {
379 resp.getWriter().println("User not found.");
382 if (testId == null) {
383 resp.getWriter().println("No test given.");
386 CATSType test = CATSType.values()[Integer.parseInt(testId)];
387 passCATS(byEmail, test);
388 resp.getWriter().println("Test '" + test.getDisplayName() + "' was added to user account.");
389 } else if (req.getParameter("catsexpire") != null) {
390 String mail = req.getParameter("catsEmail");
391 String testId = req.getParameter("catsType");
392 User byEmail = User.getByEmail(mail);
393 if (byEmail == null) {
394 resp.getWriter().println("User not found.");
397 if (testId == null) {
398 resp.getWriter().println("No test given.");
401 CATSType test = CATSType.values()[Integer.parseInt(testId)];
402 expireCATS(byEmail, test);
403 resp.getWriter().println("Test '" + test.getDisplayName() + "' is set expired for user account.");
404 } else if (req.getParameter("verify") != null) {
405 String mail = req.getParameter("verifyEmail");
406 String verificationPoints = req.getParameter("verificationPoints");
407 User byEmail = User.getByEmail(mail);
409 if (byEmail == null) {
410 resp.getWriter().println("User not found.");
415 int verifications = 0;
420 vp = Integer.parseInt(verificationPoints);
421 } catch (NumberFormatException e) {
422 resp.getWriter().println("The value for Verification Points must be an integer.</br>");
426 int agentNumber = addVerificationPoints(vp, byEmail);
433 if (Notary.checkVerificationIsPossible(getAgent(agentNumber), byEmail.getPreferredName())) {
435 Notary.verify(getAgent(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
441 if (agentNumber >= agents.length) {
442 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.";
447 } catch (GigiApiException e) {
451 resp.getWriter().println("User has been verified " + verifications + " times." + info);
453 } else if (req.getParameter("verifyexpire") != null) {
454 String mail = req.getParameter("verifyEmail");
455 User byEmail = User.getByEmail(mail);
456 if (byEmail == null) {
457 resp.getWriter().println("User not found.");
460 setVerificationDateToPast(byEmail.getPreferredName());
463 resp.getWriter().println("Verification set to time past the limit.");
464 } else if (req.getParameter("letverify") != null) {
465 String mail = req.getParameter("letverifyEmail");
466 User byEmail = User.getByEmail(mail);
467 if (byEmail == null || !byEmail.canVerify()) {
468 resp.getWriter().println("User not found, or found user is not allowed to verify.");
471 for (int i = 0; i < 25; i++) {
472 User a = getAgent(i);
473 Notary.verify(byEmail, a, a.getNames()[0], a.getDoB(), 10, "Testmanager exp up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
475 resp.getWriter().println("Successfully added experience points.");
476 } catch (GigiApiException e) {
480 } else if (req.getParameter("addEmail") != null) {
481 User u = User.getByEmail(req.getParameter("addEmailEmail"));
483 EmailAddress ea = new EmailAddress(u, req.getParameter("addEmailNew"), Locale.ENGLISH);
484 verify(ea.getAddress(), ea);
485 } catch (IllegalArgumentException e) {
487 resp.getWriter().println("An internal error occured.");
488 } catch (GigiApiException e) {
489 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
491 } else if (req.getParameter("addCert") != null) {
492 User u = User.getByEmail(req.getParameter("addCertEmail"));
494 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
495 kpg.initialize(4096);
496 KeyPair kp = kpg.generateKeyPair();
497 SPKAC s = new SPKAC((X509Key) kp.getPublic(), "challenge");
498 Signature sign = Signature.getInstance("SHA512withRSA");
499 sign.initSign(kp.getPrivate());
501 byte[] res = s.getEncoded(sign);
503 CertificateRequest cr = new CertificateRequest(new AuthorizationContext(u, u, sessionAc.isStronglyAuthenticated()), Base64.getEncoder().encodeToString(res), "challenge");
504 cr.update(CertificateRequest.DEFAULT_CN, Digest.SHA512.toString(), "client", null, "", "email:" + u.getEmail());
505 Certificate draft = cr.draft();
506 draft.issue(null, "2y", u).waitFor(10000);
507 if (draft.getStatus() == CertificateStatus.ISSUED) {
508 resp.getWriter().println("added certificate");
510 resp.getWriter().println("signer failed");
512 } catch (GeneralSecurityException e1) {
513 e1.printStackTrace();
514 resp.getWriter().println("error");
515 } catch (GigiApiException e) {
516 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
519 } else if (req.getParameter("addExDom") != null) {
520 String dom = req.getParameter("exemptDom");
522 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
523 resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
524 } else if (req.getParameter("delExDom") != null) {
525 String dom = req.getParameter("exemptDom");
526 pingExempt.remove(dom);
527 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
528 resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
529 } else if (req.getParameter("makeAgent") != null) {
530 User u = User.getByEmail(req.getParameter("agentEmail"));
532 resp.getWriter().println("User not found, or found user is not allowed to verify.");
534 if (u.getVerificationPoints() < 100) {
535 addVerificationPoints(100, u);
537 if ( !u.hasPassedCATS()) {
538 passCATS(u, CATSType.AGENT_CHALLENGE);
540 if ( !Contract.hasSignedContract(u, Contract.ContractType.RA_AGENT_CONTRACT)) {
542 new Contract(u, Contract.ContractType.RA_AGENT_CONTRACT);
543 } catch (GigiApiException e) {
547 resp.getWriter().println("User has all requirements to be an RA Agent");
550 resp.getWriter().println("<br/><a href='" + PATH + "'>Go back</a>");
553 private int addVerificationPoints(int vp, User byEmail) throws Error {
557 if (vp > 100) { // only allow max 100 Verification points
566 Notary.verify(getAgent(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
571 } catch (GigiApiException e) {
577 private void fetchMails(HttpServletRequest req, HttpServletResponse resp, String mail) throws IOException {
578 final LinkedList<String> mails = emails.get(mail);
579 HashMap<String, Object> vars = new HashMap<>();
580 vars.put("mail", mail);
582 vars.put("mails", new IterableDataset() {
584 Iterator<String> s = mails.iterator();
587 public boolean next(Language l, Map<String, Object> vars) {
591 vars.put("body", s.next().replaceAll("(https?://\\S+)", "<a href=\"$1\">$1</a>"));
596 t.output(resp.getWriter(), getLanguage(req), vars);
598 resp.getWriter().println("No mails");
603 private static final Template form = new Template(Manager.class.getResource("Manager.templ"));
606 public boolean needsLogin() {
611 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
612 String pi = req.getPathInfo().substring(PATH.length());
613 if (pi.length() > 1 && pi.startsWith("/fetch-")) {
614 String mail = pi.substring(pi.indexOf('-', 2) + 1);
615 fetchMails(req, resp, mail);
618 HashMap<String, Object> vars = new HashMap<>();
619 vars.put("cats_types", new IterableDataset() {
621 CATSType[] type = CATSType.values();
626 public boolean next(Language l, Map<String, Object> vars) {
627 if (i >= type.length) {
630 CATSType t = type[i++];
631 vars.put("id", i - 1);
632 vars.put("name", t.getDisplayName());
637 vars.put("testValidMonths", TimeConditions.getInstance().getTestMonths());
638 vars.put("reverificationDays", TimeConditions.getInstance().getVerificationLimitDays());
639 vars.put("verificationFreshMonths", TimeConditions.getInstance().getVerificationMonths());
640 vars.put("verificationMaxAgeMonths", TimeConditions.getInstance().getVerificationMaxAgeMonths());
641 vars.put("emailPingMonths", TimeConditions.getInstance().getEmailPingMonths());
643 form.output(resp.getWriter(), getLanguage(req), vars);
646 private static void setVerificationDateToPast(Name name) {
647 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
648 Calendar c = Calendar.getInstance();
649 c.setTimeInMillis(System.currentTimeMillis());
650 c.add(Calendar.MONTH, -TimeConditions.getInstance().getVerificationMonths());
651 String date = sdf.format(new Date(c.getTimeInMillis()));
652 GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `notary` SET `date`=? WHERE `to`=? AND `date`>?");
653 ps.setString(1, date);
654 ps.setInt(2, name.getId());
655 ps.setString(3, date);