1 package org.cacert.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.util.Base64;
11 import java.util.Calendar;
12 import java.util.Date;
13 import java.util.GregorianCalendar;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.LinkedList;
17 import java.util.List;
18 import java.util.Locale;
20 import java.util.Properties;
21 import java.util.Random;
22 import java.util.TreeSet;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpServletResponse;
29 import org.cacert.gigi.Gigi;
30 import org.cacert.gigi.GigiApiException;
31 import org.cacert.gigi.crypto.SPKAC;
32 import org.cacert.gigi.database.GigiPreparedStatement;
33 import org.cacert.gigi.dbObjects.Assurance.AssuranceType;
34 import org.cacert.gigi.dbObjects.CATS;
35 import org.cacert.gigi.dbObjects.CATS.CATSType;
36 import org.cacert.gigi.dbObjects.Certificate;
37 import org.cacert.gigi.dbObjects.Certificate.CertificateStatus;
38 import org.cacert.gigi.dbObjects.CertificateOwner;
39 import org.cacert.gigi.dbObjects.Country;
40 import org.cacert.gigi.dbObjects.Digest;
41 import org.cacert.gigi.dbObjects.Domain;
42 import org.cacert.gigi.dbObjects.DomainPingType;
43 import org.cacert.gigi.dbObjects.EmailAddress;
44 import org.cacert.gigi.dbObjects.Group;
45 import org.cacert.gigi.dbObjects.NamePart;
46 import org.cacert.gigi.dbObjects.NamePart.NamePartType;
47 import org.cacert.gigi.dbObjects.User;
48 import org.cacert.gigi.email.DelegateMailProvider;
49 import org.cacert.gigi.localisation.Language;
50 import org.cacert.gigi.output.template.IterableDataset;
51 import org.cacert.gigi.output.template.Template;
52 import org.cacert.gigi.pages.account.certs.CertificateRequest;
53 import org.cacert.gigi.ping.DomainPinger;
54 import org.cacert.gigi.ping.PingerDaemon;
55 import org.cacert.gigi.util.AuthorizationContext;
56 import org.cacert.gigi.util.DayDate;
57 import org.cacert.gigi.util.Notary;
58 import org.cacert.gigi.util.TimeConditions;
60 import sun.security.x509.X509Key;
62 public class Manager extends Page {
64 public static Country getRandomCountry() {
65 List<Country> cc = Country.getCountries();
66 int rnd = new Random().nextInt(cc.size());
70 public static final String PATH = "/manager";
72 private static HashMap<DomainPingType, DomainPinger> dps;
75 super("Test Manager");
78 Field gigiInstance = Gigi.class.getDeclaredField("instance");
79 gigiInstance.setAccessible(true);
80 Gigi g = (Gigi) gigiInstance.get(null);
82 Field gigiPinger = Gigi.class.getDeclaredField("pinger");
83 gigiPinger.setAccessible(true);
84 PingerDaemon pd = (PingerDaemon) gigiPinger.get(g);
86 Field f = PingerDaemon.class.getDeclaredField("pingers");
87 f.setAccessible(true);
88 dps = (HashMap<DomainPingType, DomainPinger>) f.get(pd);
89 HashMap<DomainPingType, DomainPinger> pingers = new HashMap<>();
90 for (DomainPingType dpt : DomainPingType.values()) {
91 pingers.put(dpt, new PingerFetcher(dpt));
94 } catch (ReflectiveOperationException e) {
99 public User getSupporter() {
100 if (supporter != null) {
104 User u = createAssurer( -1);
105 if ( !u.isInGroup(Group.SUPPORTER)) {
106 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
107 ps.setInt(1, u.getId());
108 ps.setString(2, Group.SUPPORTER.getDatabaseName());
109 ps.setInt(3, u.getId());
115 } catch (ReflectiveOperationException | GigiApiException e) {
121 public User getAssurer(int i) {
122 if (assurers[i] != null) {
126 User u = createAssurer(i);
129 } catch (ReflectiveOperationException | GigiApiException e) {
135 private User createAssurer(int i) throws GigiApiException, IllegalAccessException {
136 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?, `country`=?")) {
137 String mail = "test-assurer" + i + "@example.com";
138 User u = User.getByEmail(mail);
140 System.out.println("Creating RA-Agent");
142 u = User.getByEmail(mail);
143 passCATS(u, CATSType.ASSURER_CHALLENGE);
144 ps.setInt(1, u.getId());
145 ps.setInt(2, u.getPreferredName().getId());
147 ps.setString(4, "Manager init code");
148 ps.setString(5, "1990-01-01");
149 ps.setString(6, getRandomCountry().getCode());
156 private void passCATS(User u, CATSType t) {
157 CATS.enterResult(u, t, new Date(System.currentTimeMillis()), "en_EN", "1");
160 private static Manager instance;
162 private static final Template t = new Template(Manager.class.getResource("ManagerMails.templ"));
164 HashMap<String, LinkedList<String>> emails = new HashMap<>();
166 private static TreeSet<String> pingExempt = new TreeSet<>();
168 public static Manager getInstance() {
169 if (instance == null) {
170 instance = new Manager();
175 public static class MailFetcher extends DelegateMailProvider {
179 public MailFetcher(Properties props) {
180 super(props, props.getProperty("emailProvider.manager.target"));
181 String str = props.getProperty("emailProvider.manager.filter");
183 toForward = new Pattern[0];
185 String[] parts = str.split(" ");
186 toForward = new Pattern[parts.length];
187 for (int i = 0; i < parts.length; i++) {
188 toForward[i] = Pattern.compile(parts[i]);
194 public String checkEmailServer(int forUid, String address) throws IOException {
199 public synchronized void sendMail(String to, String subject, String message, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
200 HashMap<String, LinkedList<String>> mails = Manager.getInstance().emails;
201 LinkedList<String> hismails = mails.get(to);
202 if (hismails == null) {
203 mails.put(to, hismails = new LinkedList<>());
205 hismails.addFirst(subject + "\n" + message);
206 for (int i = 0; i < toForward.length; i++) {
207 if (toForward[i].matcher(to).matches()) {
208 super.sendMail(to, subject, message, replyto, toname, fromname, errorsto, extra);
216 public class PingerFetcher extends DomainPinger {
218 private DomainPingType dpt;
220 public PingerFetcher(DomainPingType dpt) {
225 public void ping(Domain domain, String configuration, CertificateOwner target, int confId) {
226 System.out.println("Test: " + domain);
227 if (pingExempt.contains(domain.getSuffix())) {
228 enterPingResult(confId, DomainPinger.PING_SUCCEDED, "Succeeded by TestManager pass-by", null);
230 dps.get(dpt).ping(domain, configuration, target, confId);
236 public void batchCreateUsers(String mailPrefix, String domain, int amount, PrintWriter out) {
240 out.print("100 at most, please.");
243 for (int i = 0; i < amount; i++) {
244 String email = mailPrefix + i + "@" + domain;
247 } catch (ReflectiveOperationException e) {
248 out.println("failed");
250 } catch (GigiApiException e) {
251 out.println("failed: " + e.getMessage());
256 private void createUser(String email) throws GigiApiException, IllegalAccessException {
257 Calendar gc = GregorianCalendar.getInstance();
258 gc.setTimeInMillis(0);
261 Country country = getRandomCountry();
263 User u = new User(email, "xvXV12°§", new DayDate(gc.getTime().getTime()), Locale.ENGLISH, country, //
264 new NamePart(NamePartType.FIRST_NAME, "Först"), new NamePart(NamePartType.FIRST_NAME, "Müddle"), //
265 new NamePart(NamePartType.LAST_NAME, "Läst"), new NamePart(NamePartType.SUFFIX, "Süffix"));
266 EmailAddress ea = u.getEmails()[0];
270 private void verify(String email, EmailAddress ea) throws GigiApiException {
271 LinkedList<String> i = emails.get(email);
272 while (i.size() > 0 && !ea.isVerified()) {
273 String lst = i.getLast();
274 Pattern p = Pattern.compile("hash=([a-zA-Z0-9]+)");
275 Matcher m = p.matcher(lst);
277 ea.verify(m.group(1));
284 User[] assurers = new User[25];
289 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
290 if (req.getParameter("create") != null) {
291 batchCreateUsers(req.getParameter("prefix"), req.getParameter("suffix"), Integer.parseInt(req.getParameter("amount")), resp.getWriter());
292 resp.getWriter().println("User batch created.");
293 } else if (req.getParameter("addpriv") != null || req.getParameter("delpriv") != null) {
294 User u = User.getByEmail(req.getParameter("email"));
296 resp.getWriter().println("User not found.");
299 if (req.getParameter("addpriv") != null) {
301 u.grantGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
302 } catch (GigiApiException e) {
305 resp.getWriter().println("Privilege granted");
307 u.revokeGroup(u, Group.getByString(req.getParameter("priv")));
308 resp.getWriter().println("Privilege revoked");
310 } else if (req.getParameter("fetch") != null) {
311 String mail = req.getParameter("femail");
312 fetchMails(req, resp, mail);
313 } else if (req.getParameter("cats") != null) {
314 String mail = req.getParameter("catsEmail");
315 String testId = req.getParameter("catsType");
316 User byEmail = User.getByEmail(mail);
317 if (byEmail == null) {
318 resp.getWriter().println("User not found.");
321 if (testId == null) {
322 resp.getWriter().println("No test given.");
325 CATSType test = CATSType.values()[Integer.parseInt(testId)];
326 passCATS(byEmail, test);
327 resp.getWriter().println("Test '" + test.getDisplayName() + "' was added to user account.");
328 } else if (req.getParameter("assure") != null) {
329 String mail = req.getParameter("assureEmail");
330 String verificationPoints = req.getParameter("verificationPoints");
331 User byEmail = User.getByEmail(mail);
333 if (byEmail == null) {
334 resp.getWriter().println("User not found.");
343 vp = Integer.parseInt(verificationPoints);
344 } catch (NumberFormatException e) {
345 throw new GigiApiException("No valid Verification Points entered.");
348 if (vp > 100) { // only allow max 100 Verification points
357 Notary.assure(getAssurer(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", "2014-11-06", AssuranceType.FACE_TO_FACE, getRandomCountry());
362 } catch (GigiApiException e) {
366 resp.getWriter().println("User has been assured " + agentNumber + " times.");
368 } else if (req.getParameter("letassure") != null) {
369 String mail = req.getParameter("letassureEmail");
370 User byEmail = User.getByEmail(mail);
372 for (int i = 0; i < 25; i++) {
373 User a = getAssurer(i);
374 Notary.assure(byEmail, a, a.getNames()[0], a.getDoB(), 10, "Testmanager exp up code", "2014-11-06", AssuranceType.FACE_TO_FACE, getRandomCountry());
376 } catch (GigiApiException e) {
379 } else if (req.getParameter("addEmail") != null) {
380 User u = User.getByEmail(req.getParameter("addEmailEmail"));
382 EmailAddress ea = new EmailAddress(u, req.getParameter("addEmailNew"), Locale.ENGLISH);
383 verify(ea.getAddress(), ea);
384 } catch (IllegalArgumentException e) {
386 resp.getWriter().println("An internal error occured.");
387 } catch (GigiApiException e) {
388 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH));
390 } else if (req.getParameter("addCert") != null) {
391 User u = User.getByEmail(req.getParameter("addCertEmail"));
393 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
394 kpg.initialize(4096);
395 KeyPair kp = kpg.generateKeyPair();
396 SPKAC s = new SPKAC((X509Key) kp.getPublic(), "challange");
397 Signature sign = Signature.getInstance("SHA512withRSA");
398 sign.initSign(kp.getPrivate());
400 byte[] res = s.getEncoded(sign);
402 CertificateRequest cr = new CertificateRequest(new AuthorizationContext(u, u), Base64.getEncoder().encodeToString(res), "challange");
403 cr.update(CertificateRequest.DEFAULT_CN, Digest.SHA512.toString(), "client", null, "", "email:" + u.getEmail());
404 Certificate draft = cr.draft();
405 draft.issue(null, "2y", u).waitFor(10000);
406 if (draft.getStatus() == CertificateStatus.ISSUED) {
407 resp.getWriter().println("added certificate");
409 resp.getWriter().println("signer failed");
411 } catch (GeneralSecurityException e1) {
412 e1.printStackTrace();
413 resp.getWriter().println("error");
414 } catch (GigiApiException e) {
415 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH));
418 } else if (req.getParameter("addExDom") != null) {
419 String dom = req.getParameter("exemtDom");
421 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
422 resp.getWriter().println(pingExempt);
423 } else if (req.getParameter("delExDom") != null) {
424 String dom = req.getParameter("exemtDom");
425 pingExempt.remove(dom);
426 resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
427 resp.getWriter().println(pingExempt);
431 private void fetchMails(HttpServletRequest req, HttpServletResponse resp, String mail) throws IOException {
432 final LinkedList<String> mails = emails.get(mail);
433 HashMap<String, Object> vars = new HashMap<>();
434 vars.put("mail", mail);
436 vars.put("mails", new IterableDataset() {
438 Iterator<String> s = mails.iterator();
441 public boolean next(Language l, Map<String, Object> vars) {
445 vars.put("body", s.next().replaceAll("(https?://\\S+)", "<a href=\"$1\">$1</a>"));
450 t.output(resp.getWriter(), getLanguage(req), vars);
452 resp.getWriter().println("No mails");
457 private static final Template form = new Template(Manager.class.getResource("Manager.templ"));
460 public boolean needsLogin() {
465 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
466 String pi = req.getPathInfo().substring(PATH.length());
467 if (pi.length() > 1 && pi.startsWith("/fetch-")) {
468 String mail = pi.substring(pi.indexOf('-', 2) + 1);
469 fetchMails(req, resp, mail);
472 HashMap<String, Object> vars = new HashMap<>();
473 vars.put("cats_types", new IterableDataset() {
475 CATSType[] type = CATSType.values();
480 public boolean next(Language l, Map<String, Object> vars) {
481 if (i >= type.length) {
484 CATSType t = type[i++];
485 vars.put("id", i - 1);
486 vars.put("name", t.getDisplayName());
491 vars.put("testValidMonths", TimeConditions.getInstance().getTestMonths());
492 vars.put("reverificationDays", TimeConditions.getInstance().getVerificationLimitDays());
493 vars.put("verificationFreshMonths", TimeConditions.getInstance().getVerificationMonths());
494 vars.put("verificationMaxAgeMonths", TimeConditions.getInstance().getVerificationMaxAgeMonths());
496 form.output(resp.getWriter(), getLanguage(req), vars);