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 = CATSType.values()[Integer.parseInt(catsTypeId)];
376 passCATS(byEmail, test);
377 resp.getWriter().println("Test '" + test.getDisplayName() + "' was added to user account.");
378 } else if (req.getParameter("catsexpire") != null) {
379 String mail = req.getParameter("catsEmail");
380 String catsTypeId = req.getParameter("catsType");
381 User userByEmail = User.getByEmail(mail);
382 if (userByEmail == null) {
383 resp.getWriter().println("User not found.");
386 if (catsTypeId == null) {
387 resp.getWriter().println("No test given.");
390 CATSType test = CATSType.values()[Integer.parseInt(catsTypeId)];
391 expireCATS(userByEmail, test);
392 resp.getWriter().println("Test '" + test.getDisplayName() + "' is set expired for user account.");
393 } else if (req.getParameter("verify") != null) {
394 String mail = req.getParameter("verifyEmail");
395 String verificationPoints = req.getParameter("verificationPoints");
396 User userByEmail = User.getByEmail(mail);
398 if (userByEmail == null) {
399 resp.getWriter().println("User not found.");
404 int verifications = 0;
409 vp = Integer.parseInt(verificationPoints);
410 } catch (NumberFormatException e) {
411 resp.getWriter().println("The value for Verification Points must be an integer.</br>");
415 int agentNumber = addVerificationPoints(vp, userByEmail);
422 if (Notary.checkVerificationIsPossible(getAgent(agentNumber), userByEmail.getPreferredName())) {
424 Notary.verify(getAgent(agentNumber), userByEmail, userByEmail.getPreferredName(), userByEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
430 if (agentNumber >= agents.length) {
431 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.";
436 } catch (GigiApiException e) {
440 resp.getWriter().println("User has been verified " + verifications + " times." + info);
442 } else if (req.getParameter("letverify") != null) {
443 String mail = req.getParameter("letverifyEmail");
444 User userByEmail = User.getByEmail(mail);
445 if (userByEmail == null || !userByEmail.canVerify()) {
446 resp.getWriter().println("User not found, or found user is not allowed to verify.");
449 for (int i = 0; i < 25; i++) {
450 User a = getAgent(i);
451 Notary.verify(userByEmail, a, a.getNames()[0], a.getDoB(), 10, "Testmanager exp up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
453 resp.getWriter().println("Successfully added experience points.");
454 } catch (GigiApiException e) {
458 } else if (req.getParameter("addEmail") != null) {
459 User userByEmail = User.getByEmail(req.getParameter("addEmailEmail"));
461 EmailAddress ea = new EmailAddress(userByEmail, req.getParameter("addEmailNew"), Locale.ENGLISH);
462 verify(ea.getAddress(), ea);
463 } catch (IllegalArgumentException e) {
465 resp.getWriter().println("An internal error occured.");
466 } catch (GigiApiException e) {
467 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
469 } else if (req.getParameter("addCert") != null) {
470 User userByEmail = User.getByEmail(req.getParameter("addCertEmail"));
472 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
473 kpg.initialize(4096);
474 KeyPair kp = kpg.generateKeyPair();
475 SPKAC s = new SPKAC((X509Key) kp.getPublic(), "challenge");
476 Signature sign = Signature.getInstance("SHA512withRSA");
477 sign.initSign(kp.getPrivate());
479 byte[] res = s.getEncoded(sign);
481 CertificateRequest cr = new CertificateRequest(new AuthorizationContext(userByEmail, userByEmail, sessionAc.isStronglyAuthenticated()), Base64.getEncoder().encodeToString(res), "challenge");
482 cr.update(CertificateRequest.DEFAULT_CN, Digest.SHA512.toString(), "client", null, "", "email:" + userByEmail.getEmail());
483 Certificate draft = cr.draft();
484 draft.issue(null, "2y", userByEmail).waitFor(10000);
485 if (draft.getStatus() == CertificateStatus.ISSUED) {
486 resp.getWriter().println("added certificate");
488 resp.getWriter().println("signer failed");
490 } catch (GeneralSecurityException e1) {
491 e1.printStackTrace();
492 resp.getWriter().println("error");
493 } catch (GigiApiException e) {
494 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
497 } else if (req.getParameter("addExDom") != null) {
498 String dom = req.getParameter("exemptDom");
500 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
501 resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
502 } else if (req.getParameter("delExDom") != null) {
503 String dom = req.getParameter("exemptDom");
504 pingExempt.remove(dom);
505 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
506 resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
507 } else if (req.getParameter("makeAgent") != null) {
508 User userByEmail = User.getByEmail(req.getParameter("agentEmail"));
509 if (userByEmail == null) {
510 resp.getWriter().println("User not found, or found user is not allowed to verify.");
512 if (userByEmail.getVerificationPoints() < 100) {
513 addVerificationPoints(100, userByEmail);
515 if ( !userByEmail.hasPassedCATS()) {
516 passCATS(userByEmail, CATSType.AGENT_CHALLENGE);
518 if ( !Contract.hasSignedContract(userByEmail, Contract.ContractType.RA_AGENT_CONTRACT)) {
520 new Contract(userByEmail, Contract.ContractType.RA_AGENT_CONTRACT);
521 } catch (GigiApiException e) {
525 resp.getWriter().println("User has all requirements to be an RA Agent");
528 resp.getWriter().println("<br/><a href='" + PATH + "'>Go back</a>");
531 private int addVerificationPoints(int vp, User byEmail) throws Error {
535 if (vp > 100) { // only allow max 100 Verification points
544 Notary.verify(getAgent(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
549 } catch (GigiApiException e) {
555 private void fetchMails(HttpServletRequest req, HttpServletResponse resp, String mail) throws IOException {
556 final LinkedList<String> mails = emails.get(mail);
557 HashMap<String, Object> vars = new HashMap<>();
558 vars.put("mail", mail);
560 vars.put("mails", new IterableDataset() {
562 Iterator<String> s = mails.iterator();
565 public boolean next(Language l, Map<String, Object> vars) {
569 vars.put("body", s.next().replaceAll("(https?://\\S+)", "<a href=\"$1\">$1</a>"));
574 t.output(resp.getWriter(), getLanguage(req), vars);
576 resp.getWriter().println("No mails");
581 private static final Template form = new Template(Manager.class.getResource("Manager.templ"));
584 public boolean needsLogin() {
589 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
590 String pi = req.getPathInfo().substring(PATH.length());
591 if (pi.length() > 1 && pi.startsWith("/fetch-")) {
592 String mail = pi.substring(pi.indexOf('-', 2) + 1);
593 fetchMails(req, resp, mail);
596 HashMap<String, Object> vars = new HashMap<>();
597 vars.put("cats_types", new IterableDataset() {
599 CATSType[] type = CATSType.values();
604 public boolean next(Language l, Map<String, Object> vars) {
605 if (i >= type.length) {
608 CATSType t = type[i++];
609 vars.put("id", i - 1);
610 vars.put("name", t.getDisplayName());
615 vars.put("testValidMonths", TimeConditions.getInstance().getTestMonths());
616 vars.put("reverificationDays", TimeConditions.getInstance().getVerificationLimitDays());
617 vars.put("verificationFreshMonths", TimeConditions.getInstance().getVerificationMonths());
618 vars.put("verificationMaxAgeMonths", TimeConditions.getInstance().getVerificationMaxAgeMonths());
619 vars.put("emailPingMonths", TimeConditions.getInstance().getEmailPingMonths());
621 form.output(resp.getWriter(), getLanguage(req), vars);