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.dbObjects.CATS;
36 import club.wpia.gigi.dbObjects.CATS.CATSType;
37 import club.wpia.gigi.dbObjects.Certificate;
38 import club.wpia.gigi.dbObjects.Certificate.CertificateStatus;
39 import club.wpia.gigi.dbObjects.CertificateOwner;
40 import club.wpia.gigi.dbObjects.Contract;
41 import club.wpia.gigi.dbObjects.Contract.ContractType;
42 import club.wpia.gigi.dbObjects.Country;
43 import club.wpia.gigi.dbObjects.Digest;
44 import club.wpia.gigi.dbObjects.Domain;
45 import club.wpia.gigi.dbObjects.DomainPingConfiguration;
46 import club.wpia.gigi.dbObjects.DomainPingExecution;
47 import club.wpia.gigi.dbObjects.DomainPingType;
48 import club.wpia.gigi.dbObjects.EmailAddress;
49 import club.wpia.gigi.dbObjects.Group;
50 import club.wpia.gigi.dbObjects.NamePart;
51 import club.wpia.gigi.dbObjects.NamePart.NamePartType;
52 import club.wpia.gigi.dbObjects.User;
53 import club.wpia.gigi.dbObjects.Verification.VerificationType;
54 import club.wpia.gigi.email.DelegateMailProvider;
55 import club.wpia.gigi.email.EmailProvider;
56 import club.wpia.gigi.localisation.Language;
57 import club.wpia.gigi.output.template.IterableDataset;
58 import club.wpia.gigi.output.template.Template;
59 import club.wpia.gigi.pages.account.certs.CertificateRequest;
60 import club.wpia.gigi.ping.DomainPinger;
61 import club.wpia.gigi.ping.PingerDaemon;
62 import club.wpia.gigi.util.AuthorizationContext;
63 import club.wpia.gigi.util.DayDate;
64 import club.wpia.gigi.util.DomainAssessment;
65 import club.wpia.gigi.util.HTMLEncoder;
66 import club.wpia.gigi.util.Notary;
67 import club.wpia.gigi.util.TimeConditions;
68 import sun.security.x509.X509Key;
70 public class Manager extends Page {
72 public static String validVerificationDateString() {
73 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
74 Calendar c = Calendar.getInstance();
75 c.setTimeInMillis(System.currentTimeMillis());
76 c.add(Calendar.MONTH, -Notary.LIMIT_MAX_MONTHS_VERIFICATION + 1);
77 return sdf.format(new Date(c.getTimeInMillis()));
80 public static Country getRandomCountry() {
81 List<Country> cc = Country.getCountries();
82 int rnd = new Random().nextInt(cc.size());
86 public static final String PATH = "/manager";
88 private static HashMap<DomainPingType, DomainPinger> dps;
91 super("Test Manager");
94 Field gigiInstance = Gigi.class.getDeclaredField("instance");
95 gigiInstance.setAccessible(true);
96 Gigi g = (Gigi) gigiInstance.get(null);
98 Field gigiPinger = Gigi.class.getDeclaredField("pinger");
99 gigiPinger.setAccessible(true);
100 PingerDaemon pd = (PingerDaemon) gigiPinger.get(g);
102 Field f = PingerDaemon.class.getDeclaredField("pingers");
103 f.setAccessible(true);
104 dps = (HashMap<DomainPingType, DomainPinger>) f.get(pd);
105 HashMap<DomainPingType, DomainPinger> pingers = new HashMap<>();
106 for (DomainPingType dpt : DomainPingType.values()) {
107 pingers.put(dpt, new PingerFetcher(dpt));
110 } catch (ReflectiveOperationException e) {
115 public User getSupporter() {
116 if (supporter != null) {
120 User u = createAgent( -1);
121 if ( !u.isInGroup(Group.SUPPORTER)) {
122 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
123 ps.setInt(1, u.getId());
124 ps.setString(2, Group.SUPPORTER.getDBName());
125 ps.setInt(3, u.getId());
131 } catch (ReflectiveOperationException | GigiApiException e) {
137 public User getAgent(int i) {
138 if (agents[i] != null) {
142 User u = createAgent(i);
145 } catch (ReflectiveOperationException | GigiApiException e) {
151 private User createAgent(int i) throws GigiApiException, IllegalAccessException {
152 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?, `country`=?")) {
153 String mail = "test-agent" + i + "@example.com";
154 User u = User.getByEmail(mail);
156 System.out.println("Creating RA-Agent");
158 u = User.getByEmail(mail);
159 passCATS(u, CATSType.AGENT_CHALLENGE);
160 ps.setInt(1, u.getId());
161 ps.setInt(2, u.getPreferredName().getId());
163 ps.setString(4, "Manager init code");
164 ps.setString(5, "1990-01-01");
165 ps.setString(6, getRandomCountry().getCode());
168 new Contract(u, ContractType.RA_AGENT_CONTRACT);
173 private void passCATS(User u, CATSType t) {
174 CATS.enterResult(u, t, new Date(System.currentTimeMillis()), "en_EN", "1");
177 private void expireCATS(User u, CATSType t) {
178 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `cats_passed` SET `pass_date`=? WHERE `user_id`=? AND `variant_id`=? AND `pass_date`>?")) {
179 ps.setTimestamp(1, new Timestamp(System.currentTimeMillis() - DayDate.MILLI_DAY * 367));
180 ps.setInt(2, u.getId());
181 ps.setInt(3, t.getId());
182 ps.setTimestamp(4, new Timestamp(System.currentTimeMillis() - DayDate.MILLI_DAY * 366));
188 private static Manager instance;
190 private static final Template t = new Template(Manager.class.getResource("ManagerMails.templ"));
192 HashMap<String, LinkedList<String>> emails = new HashMap<>();
194 private static TreeSet<String> pingExempt = new TreeSet<>();
196 public static Manager getInstance() {
197 if (instance == null) {
198 instance = new Manager();
203 public static class MailFetcher extends DelegateMailProvider {
207 public MailFetcher(Properties props) {
208 super(props, props.getProperty("emailProvider.manager.target"));
209 String str = props.getProperty("emailProvider.manager.filter");
211 toForward = new Pattern[0];
213 String[] parts = str.split(" ");
214 toForward = new Pattern[parts.length];
215 for (int i = 0; i < parts.length; i++) {
216 toForward[i] = Pattern.compile(parts[i]);
222 public String checkEmailServer(int forUid, String address) throws IOException {
227 public synchronized void sendMail(String to, String subject, String message, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
228 HashMap<String, LinkedList<String>> mails = Manager.getInstance().emails;
229 LinkedList<String> hismails = mails.get(to);
230 if (hismails == null) {
231 mails.put(to, hismails = new LinkedList<>());
233 hismails.addFirst(subject + "\n" + message);
234 for (int i = 0; i < toForward.length; i++) {
235 if (toForward[i].matcher(to).matches()) {
236 super.sendMail(to, subject, message, replyto, toname, fromname, errorsto, extra);
244 public class PingerFetcher extends DomainPinger {
246 private DomainPingType dpt;
248 public PingerFetcher(DomainPingType dpt) {
253 public DomainPingExecution ping(Domain domain, String configuration, CertificateOwner target, DomainPingConfiguration conf) {
254 System.err.println("TestManager: " + domain.getSuffix());
255 if (pingExempt.contains(domain.getSuffix())) {
256 return enterPingResult(conf, DomainPinger.PING_SUCCEDED, "Succeeded by TestManager pass-by", null);
258 DomainPinger pinger = dps.get(dpt);
259 System.err.println("Forward to old pinger: " + pinger);
260 return pinger.ping(domain, configuration, target, conf);
266 public void batchCreateUsers(String mailPrefix, String domain, int amount, PrintWriter out) {
270 out.print("100 at most, please.");
273 for (int i = 0; i < amount; i++) {
274 String email = mailPrefix + i + "@" + domain;
277 } catch (ReflectiveOperationException e) {
278 out.println("failed");
280 } catch (GigiApiException e) {
281 out.println("failed: " + e.getMessage());
286 private void createUser(String email) throws GigiApiException, IllegalAccessException {
287 Calendar gc = GregorianCalendar.getInstance();
288 gc.setTimeInMillis(0);
291 Country country = getRandomCountry();
293 User u = new User(email, "xvXV12°§", new DayDate(gc.getTime().getTime()), Locale.ENGLISH, country, //
294 new NamePart(NamePartType.FIRST_NAME, "Först"), new NamePart(NamePartType.FIRST_NAME, "Müddle"), //
295 new NamePart(NamePartType.LAST_NAME, "Läst"), new NamePart(NamePartType.SUFFIX, "Süffix"));
296 EmailAddress ea = u.getEmails()[0];
300 private void verify(String email, EmailAddress ea) throws GigiApiException {
301 LinkedList<String> i = emails.get(email);
302 while (i.size() > 0 && !ea.isVerified()) {
303 String lst = i.getLast();
304 Pattern p = Pattern.compile("hash=([a-zA-Z0-9]+)");
305 Matcher m = p.matcher(lst);
307 ea.verify(m.group(1));
314 User[] agents = new User[25];
319 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
320 AuthorizationContext sessionAc = (AuthorizationContext) req.getSession().getAttribute(Gigi.AUTH_CONTEXT);
321 if (req.getParameter("create") != null) {
322 String prefix = req.getParameter("prefix");
323 String domain = req.getParameter("suffix");
325 if (null == prefix) {
326 throw new GigiApiException("No prefix given.");
328 if (null == domain) {
329 throw new GigiApiException("No domain given.");
332 DomainAssessment.checkCertifiableDomain(domain, false, true);
334 if ( !EmailProvider.isValidMailAddress(prefix + "@" + domain)) {
335 throw new GigiApiException("Invalid email address template.");
338 batchCreateUsers(prefix, domain, Integer.parseInt(req.getParameter("amount")), resp.getWriter());
339 resp.getWriter().println("User batch created.");
340 } catch (GigiApiException e) {
343 } else if (req.getParameter("addpriv") != null || req.getParameter("delpriv") != null) {
344 User userByEmail = User.getByEmail(req.getParameter("email"));
345 if (userByEmail == null) {
346 resp.getWriter().println("User not found.");
350 if (req.getParameter("addpriv") != null) {
351 userByEmail.grantGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
352 resp.getWriter().println("Privilege granted");
354 userByEmail.revokeGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
355 resp.getWriter().println("Privilege revoked");
357 } catch (GigiApiException e) {
360 } else if (req.getParameter("fetch") != null) {
361 String mail = req.getParameter("femail");
362 fetchMails(req, resp, mail);
363 } else if (req.getParameter("cats") != null) {
364 String mail = req.getParameter("catsEmail");
365 String catsTypeId = req.getParameter("catsType");
366 User byEmail = User.getByEmail(mail);
367 if (byEmail == null) {
368 resp.getWriter().println("User not found.");
371 if (catsTypeId == null) {
372 resp.getWriter().println("No test given.");
375 CATSType test = null;
377 test = CATSType.values()[Integer.parseInt(catsTypeId)];
378 } catch (NumberFormatException e) {
379 resp.getWriter().println("No valid integer given.");
382 passCATS(byEmail, test);
383 resp.getWriter().println("Test '" + test.getDisplayName() + "' was added to user account.");
384 } else if (req.getParameter("catsexpire") != null) {
385 String mail = req.getParameter("catsEmail");
386 String catsTypeId = req.getParameter("catsType");
387 User userByEmail = User.getByEmail(mail);
388 if (userByEmail == null) {
389 resp.getWriter().println("User not found.");
392 if (catsTypeId == null) {
393 resp.getWriter().println("No test given.");
396 CATSType test = null;
398 test = CATSType.values()[Integer.parseInt(catsTypeId)];
399 } catch (NumberFormatException e) {
400 resp.getWriter().println("No valid integer given.");
403 expireCATS(userByEmail, test);
404 resp.getWriter().println("Test '" + test.getDisplayName() + "' is set expired for user account.");
405 } else if (req.getParameter("verify") != null) {
406 String mail = req.getParameter("verifyEmail");
407 String verificationPoints = req.getParameter("verificationPoints");
408 User userByEmail = User.getByEmail(mail);
410 if (userByEmail == null) {
411 resp.getWriter().println("User not found.");
416 int verifications = 0;
421 vp = Integer.parseInt(verificationPoints);
422 } catch (NumberFormatException e) {
423 resp.getWriter().println("The value for Verification Points must be an integer.</br>");
427 int agentNumber = addVerificationPoints(vp, userByEmail);
434 if (Notary.checkVerificationIsPossible(getAgent(agentNumber), userByEmail.getPreferredName())) {
436 Notary.verify(getAgent(agentNumber), userByEmail, userByEmail.getPreferredName(), userByEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
442 if (agentNumber >= agents.length) {
443 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.";
448 } catch (GigiApiException e) {
452 resp.getWriter().println("User has been verified " + verifications + " times." + info);
454 } else if (req.getParameter("letverify") != null) {
455 String mail = req.getParameter("letverifyEmail");
456 User userByEmail = User.getByEmail(mail);
457 if (userByEmail == null || !userByEmail.canVerify()) {
458 resp.getWriter().println("User not found, or found user is not allowed to verify.");
461 for (int i = 0; i < 25; i++) {
462 User a = getAgent(i);
463 Notary.verify(userByEmail, a, a.getNames()[0], a.getDoB(), 10, "Testmanager exp up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
465 resp.getWriter().println("Successfully added experience points.");
466 } catch (GigiApiException e) {
470 } else if (req.getParameter("addEmail") != null) {
471 User userByEmail = User.getByEmail(req.getParameter("addEmailEmail"));
473 EmailAddress ea = new EmailAddress(userByEmail, req.getParameter("addEmailNew"), Locale.ENGLISH);
474 verify(ea.getAddress(), ea);
475 } catch (IllegalArgumentException e) {
477 resp.getWriter().println("An internal error occured.");
478 } catch (GigiApiException e) {
479 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
481 } else if (req.getParameter("addCert") != null) {
482 User userByEmail = User.getByEmail(req.getParameter("addCertEmail"));
484 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
485 kpg.initialize(4096);
486 KeyPair kp = kpg.generateKeyPair();
487 SPKAC s = new SPKAC((X509Key) kp.getPublic(), "challenge");
488 Signature sign = Signature.getInstance("SHA512withRSA");
489 sign.initSign(kp.getPrivate());
491 byte[] res = s.getEncoded(sign);
493 CertificateRequest cr = new CertificateRequest(new AuthorizationContext(userByEmail, userByEmail, sessionAc.isStronglyAuthenticated()), Base64.getEncoder().encodeToString(res), "challenge");
494 cr.update(CertificateRequest.DEFAULT_CN, Digest.SHA512.toString(), "client", null, "", "email:" + userByEmail.getEmail());
495 Certificate draft = cr.draft();
496 draft.issue(null, "2y", userByEmail).waitFor(10000);
497 if (draft.getStatus() == CertificateStatus.ISSUED) {
498 resp.getWriter().println("added certificate");
500 resp.getWriter().println("signer failed");
502 } catch (GeneralSecurityException e1) {
503 e1.printStackTrace();
504 resp.getWriter().println("error");
505 } catch (GigiApiException e) {
506 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
509 } else if (req.getParameter("addExDom") != null) {
510 String dom = req.getParameter("exemptDom");
512 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
513 resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
514 } else if (req.getParameter("delExDom") != null) {
515 String dom = req.getParameter("exemptDom");
516 pingExempt.remove(dom);
517 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
518 resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
519 } else if (req.getParameter("makeAgent") != null) {
520 User userByEmail = User.getByEmail(req.getParameter("agentEmail"));
521 if (userByEmail == null) {
522 resp.getWriter().println("User not found, or found user is not allowed to verify.");
524 if (userByEmail.getVerificationPoints() < 100) {
525 addVerificationPoints(100, userByEmail);
527 if ( !userByEmail.hasPassedCATS()) {
528 passCATS(userByEmail, CATSType.AGENT_CHALLENGE);
530 if ( !Contract.hasSignedContract(userByEmail, Contract.ContractType.RA_AGENT_CONTRACT)) {
532 new Contract(userByEmail, Contract.ContractType.RA_AGENT_CONTRACT);
533 } catch (GigiApiException e) {
537 resp.getWriter().println("User has all requirements to be an RA Agent");
540 resp.getWriter().println("<br/><a href='" + PATH + "'>Go back</a>");
543 private int addVerificationPoints(int vp, User byEmail) throws Error {
547 if (vp > 100) { // only allow max 100 Verification points
556 Notary.verify(getAgent(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
561 } catch (GigiApiException e) {
567 private void fetchMails(HttpServletRequest req, HttpServletResponse resp, String mail) throws IOException {
568 final LinkedList<String> mails = emails.get(mail);
569 HashMap<String, Object> vars = new HashMap<>();
570 vars.put("mail", mail);
572 vars.put("mails", new IterableDataset() {
574 Iterator<String> s = mails.iterator();
577 public boolean next(Language l, Map<String, Object> vars) {
581 vars.put("body", s.next().replaceAll("(https?://\\S+)", "<a href=\"$1\">$1</a>"));
586 t.output(resp.getWriter(), getLanguage(req), vars);
588 resp.getWriter().println("No mails");
593 private static final Template form = new Template(Manager.class.getResource("Manager.templ"));
596 public boolean needsLogin() {
601 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
602 String pi = req.getPathInfo().substring(PATH.length());
603 if (pi.length() > 1 && pi.startsWith("/fetch-")) {
604 String mail = pi.substring(pi.indexOf('-', 2) + 1);
605 fetchMails(req, resp, mail);
608 HashMap<String, Object> vars = new HashMap<>();
609 vars.put("cats_types", new IterableDataset() {
611 CATSType[] type = CATSType.values();
616 public boolean next(Language l, Map<String, Object> vars) {
617 if (i >= type.length) {
620 CATSType t = type[i++];
621 vars.put("id", i - 1);
622 vars.put("name", t.getDisplayName());
627 vars.put("testValidMonths", TimeConditions.getInstance().getTestMonths());
628 vars.put("reverificationDays", TimeConditions.getInstance().getVerificationLimitDays());
629 vars.put("verificationFreshMonths", TimeConditions.getInstance().getVerificationMonths());
630 vars.put("verificationMaxAgeMonths", TimeConditions.getInstance().getVerificationMaxAgeMonths());
631 vars.put("emailPingMonths", TimeConditions.getInstance().getEmailPingMonths());
633 form.output(resp.getWriter(), getLanguage(req), vars);