1 /*******************************************************************************
2 * ============LICENSE_START====================================================
4 * * ===========================================================================
5 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * * ===========================================================================
7 * * Licensed under the Apache License, Version 2.0 (the "License");
8 * * you may not use this file except in compliance with the License.
9 * * You may obtain a copy of the License at
11 * * http://www.apache.org/licenses/LICENSE-2.0
13 * * Unless required by applicable law or agreed to in writing, software
14 * * distributed under the License is distributed on an "AS IS" BASIS,
15 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * * See the License for the specific language governing permissions and
17 * * limitations under the License.
18 * * ============LICENSE_END====================================================
21 ******************************************************************************/
22 package org.onap.aaf.org;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Date;
28 import java.util.GregorianCalendar;
29 import java.util.HashSet;
30 import java.util.List;
32 import java.util.regex.Pattern;
34 import org.onap.aaf.auth.env.AuthzTrans;
35 import org.onap.aaf.auth.local.AbsData.Reuse;
36 import org.onap.aaf.auth.org.EmailWarnings;
37 import org.onap.aaf.auth.org.Executor;
38 import org.onap.aaf.auth.org.Mailer;
39 import org.onap.aaf.auth.org.Organization;
40 import org.onap.aaf.auth.org.OrganizationException;
41 import org.onap.aaf.cadi.config.Config;
42 import org.onap.aaf.cadi.util.FQI;
43 import org.onap.aaf.misc.env.Env;
45 public class DefaultOrg implements Organization {
46 private static final String AAF_DATA_DIR = "aaf_data_dir";
49 final String atDomain;
52 private final String root_ns;
54 private final String NAME;
55 private final Set<String> supportedRealms;
59 public DefaultOrg(Env env, String realm) throws OrganizationException {
62 supportedRealms=new HashSet<>();
63 supportedRealms.add(realm);
64 domain=FQI.reverseDomain(realm);
65 atDomain = '@'+domain;
66 NAME=env.getProperty(realm + ".name","Default Organization");
67 root_ns = env.getProperty(Config.AAF_ROOT_NS,Config.AAF_ROOT_NS_DEF);
71 String temp=env.getProperty(defFile = (getClass().getName()+".file"));
72 File fIdentities=null;
74 temp = env.getProperty(AAF_DATA_DIR);
76 env.warn().log(defFile, " is not defined. Using default: ",temp+"/identities.dat");
77 File dir = new File(temp);
78 fIdentities=new File(dir,"identities.dat");
80 if (!fIdentities.exists()) {
81 env.warn().log("No",fIdentities.getCanonicalPath(),"exists. Creating.");
85 fIdentities.createNewFile();
90 fIdentities = new File(temp);
91 if (!fIdentities.exists()) {
92 String dataDir = env.getProperty(AAF_DATA_DIR);
94 fIdentities = new File(dataDir,temp);
99 if (fIdentities!=null && fIdentities.exists()) {
100 identities = new Identities(fIdentities);
102 if (fIdentities==null) {
103 throw new OrganizationException("No Identities: set \"" + AAF_DATA_DIR + '"');
105 throw new OrganizationException(fIdentities.getCanonicalPath() + " does not exist.");
110 temp=env.getProperty(getClass().getName()+".file.revoked");
112 temp = env.getProperty(AAF_DATA_DIR);
114 File dir = new File(temp);
115 fRevoked=new File(dir,"revoked.dat");
118 fRevoked = new File(temp);
120 if (fRevoked!=null && fRevoked.exists()) {
121 revoked = new Identities(fRevoked);
126 } catch (IOException e) {
127 throw new OrganizationException(e);
131 // Implement your own Delegation System
132 static final List<String> NULL_DELEGATES = new ArrayList<>();
134 public Identities identities;
135 public Identities revoked;
136 private boolean dryRun;
137 private Mailer mailer;
138 public enum Types {Employee, Contractor, Application, NotActive};
139 private final static Set<String> typeSet;
142 typeSet = new HashSet<>();
143 for (Types t : Types.values()) {
144 typeSet.add(t.name());
148 private static final EmailWarnings emailWarnings = new DefaultOrgWarnings();
151 public String getName() {
156 public String getRealm() {
161 public String getDomain() {
166 public DefaultOrgIdentity getIdentity(AuthzTrans trans, String id) throws OrganizationException {
167 int at = id.indexOf('@');
168 return new DefaultOrgIdentity(trans,at<0?id:id.substring(0, at),this);
172 * If the ID isn't in the revoked file, if it exists, it is revoked.
175 public boolean isRevoked(AuthzTrans trans, String key) {
178 revoked.open(trans, DefaultOrgIdentity.TIMEOUT);
180 Reuse r = revoked.reuse();
181 int at = key.indexOf(domain);
184 search = key.substring(0,at);
188 return revoked.find(search, r)!=null;
190 revoked.close(trans);
192 } catch (IOException e) {
193 trans.error().log(e);
200 * @see org.onap.aaf.auth.org.Organization#getEsclaations(org.onap.aaf.auth.env.AuthzTrans, java.lang.String, int)
203 public List<Identity> getIDs(AuthzTrans trans, String user, int escalate) throws OrganizationException {
204 List<Identity> rv = new ArrayList<>();
205 int end = Math.min(3,Math.abs(escalate));
207 for(int i=0;i<end;++i) {
209 id = getIdentity(trans,user);
211 id = id.responsibleTo();
222 // Note: Return a null if found; return a String Message explaining why not found.
224 public String isValidID(final AuthzTrans trans, final String id) {
226 DefaultOrgIdentity u = getIdentity(trans,id);
227 return (u==null||!u.isFound())?id + "is not an Identity in " + getName():null;
228 } catch (OrganizationException e) {
229 return getName() + " could not lookup " + id + ": " + e.getLocalizedMessage();
232 // Possible ID Pattern
233 // private static final Pattern ID_PATTERN=Pattern.compile("([\\w.-]+@[\\w.-]+).{4-13}");
234 // Another one: ID_PATTERN = "(a-z[a-z0-9]{5-8}@.*).{4-13}";
237 public boolean isValidCred(final AuthzTrans trans, final String id) {
239 int at = id.indexOf('@');
242 // Use this to prevent passwords to any but THIS domain.
243 // if (!id.regionMatches(at+1, domain, 0, id.length()-at-1)) {
246 sid = id.substring(0,at);
250 // We'll validate that it exists, rather than check patterns.
252 return isValidID(trans, sid)==null;
253 // Check Pattern (if checking existing is too long)
254 // if (id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) {
260 private static final String SPEC_CHARS = "!@#$%^*-+?/,:;.";
261 private static final Pattern PASS_PATTERN=Pattern.compile("(((?=.*[a-z,A-Z])(((?=.*\\d))|(?=.*[" + SPEC_CHARS +"]))).{6,20})");
264 * (?=.*[a-z,A-Z]) # must contain one character
266 * (?=.*\d) # must contain one digit from 0-9
268 * (?=.*[@#$%]) # must contain one special symbols in the list SPEC_CHARS
270 * . # match anything with previous condition checking
271 * {6,20} # length at least 6 characters and maximum of 20
274 * Another example, more stringent pattern
275 private static final Pattern PASS_PATTERN=Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[" + SPEC_CHARS +"]).{6,20})");
276 * Attribution: from mkyong.com
278 * (?=.*\d) # must contain one digit from 0-9
279 * (?=.*[a-z]) # must contain one lowercase characters
280 * (?=.*[A-Z]) # must contain one uppercase characters
281 * (?=.*[@#$%]) # must contain one special symbols in the list SPEC_CHARS
282 * . # match anything with previous condition checking
283 * {6,20} # length at least 6 characters and maximum of 20
287 public String isValidPassword(final AuthzTrans trans, final String user, final String password, final String... prev) {
288 for (String p : prev) {
289 if (password.contains(p)) { // A more sophisticated algorithm might be better.
290 return "Password too similar to previous passwords";
293 // If you have an Organization user/Password scheme, replace the following
294 if (PASS_PATTERN.matcher(password).matches()) {
297 return "Password does not match " + NAME + " Password Standards";
300 private static final String[] rules = new String[] {
301 "Passwords must contain letters",
302 "Passwords must contain one of the following:",
304 " One special symbols in the list \""+ SPEC_CHARS + '"',
305 "Passwords must be between 6 and 20 chars in length",
309 public String[] getPasswordRules() {
314 public Set<String> getIdentityTypes() {
319 public Response notify(AuthzTrans trans, Notify type, String url, String[] identities, String[] ccs, String summary, Boolean urgent) {
320 String system = trans.getProperty("CASS_ENV", "");
322 ArrayList<String> toList = new ArrayList<>();
324 if (identities != null) {
325 for (String user : identities) {
327 identity = getIdentity(trans, user);
328 if (identity == null) {
330 "Failure to obtain User " + user + " for "
333 toList.add(identity.email());
335 } catch (Exception e) {
338 "Failure to obtain User " + user + " for "
344 if (toList.isEmpty()) {
345 trans.error().log("No Users listed to email");
346 return Response.ERR_NotificationFailure;
349 ArrayList<String> ccList = new ArrayList<>();
351 // If we're sending an urgent email, CC the user's supervisor
354 trans.info().log("urgent msg for: " + identities[0]);
356 List<Identity> supervisors = getApprovers(trans, identities[0]);
357 for (Identity us : supervisors) {
358 trans.info().log("supervisor: " + us.email());
359 ccList.add(us.email());
361 } catch (Exception e) {
363 "Failed to find supervisor for " + identities[0]);
368 for (String user : ccs) {
370 identity = getIdentity(trans, user);
371 ccList.add(identity.email());
372 } catch (Exception e) {
375 "Failure to obtain User " + user + " for "
381 if (summary == null) {
388 sendEmail(trans, toList, ccList,
389 "AAF Approval Notification "
390 + (system.length() == 0 ? "" : "(ENV: "
394 + "System for Fine-Grained Authorizations. You are being asked to Approve"
395 + (system.length() == 0 ? "" : " in the "
396 + system + " environment")
397 + " before AAF Actions can be taken.\n\n"
398 + "Please follow this link: \n\n\t" + url
399 + "\n\n" + summary, urgent);
400 } catch (Exception e) {
402 trans.error().log(e, "Failure to send Email");
403 return Response.ERR_NotificationFailure;
406 case PasswordExpiration:
411 "AAF Password Expiration Warning "
412 + (system.length() == 0 ? "" : "(ENV: "
416 + " System for Authorizations.\n\nOne or more passwords will expire soon or have expired"
417 + (system.length() == 0 ? "" : " in the "
418 + system + " environment")
419 + ".\n\nPasswords expired for more than 30 days without action are subject to deletion.\n\n"
420 + "Please follow each link to add a New Password with Expiration Date. Either are valid until expiration. "
421 + "Use this time to change the passwords on your system. If issues, reply to this email.\n\n"
423 } catch (Exception e) {
424 trans.error().log(e, "Failure to send Email");
425 return Response.ERR_NotificationFailure;
435 "AAF Role Expiration Warning "
436 + (system.length() == 0 ? "" : "(ENV: "
440 + " System for Authorizations. One or more roles will expire soon"
441 + (system.length() == 0 ? "" : " in the "
442 + system + " environment")
443 + ".\n\nRoles expired for more than 30 days are subject to deletion."
444 + "Please follow this link the GUI Command line, and either 'extend' or 'del' the user in the role.\n"
445 + "If issues, reply to this email.\n\n\t" + url
446 + "\n\n" + summary, urgent);
447 } catch (Exception e) {
448 trans.error().log(e, "Failure to send Email");
449 return Response.ERR_NotificationFailure;
453 return Response.ERR_NotImplemented;
460 * Default Policy is to set to 6 Months for Notification Types.
461 * add others/change as required
464 public Date whenToValidate(Notify type, Date lastValidated) {
467 case PasswordExpiration:
470 GregorianCalendar gc = new GregorianCalendar();
471 gc.setTime(lastValidated);
472 gc.add(GregorianCalendar.MONTH, 6); // 6 month policy
478 public GregorianCalendar expiration(GregorianCalendar gc, Expiration exp, String... extra) {
479 GregorianCalendar now = new GregorianCalendar();
480 GregorianCalendar rv = gc==null?now:(GregorianCalendar)gc.clone();
483 // Extending Password give 5 extra days, max 8 days from now
484 rv.add(GregorianCalendar.DATE, 5);
485 now.add(GregorianCalendar.DATE, 8);
491 // Future requests last 15 days.
492 now.add(GregorianCalendar.DATE, 15);
496 // Passwords expire in 90 days
497 now.add(GregorianCalendar.DATE, 90);
501 // Temporary Passwords last for 12 hours.
502 now.add(GregorianCalendar.DATE, 90);
506 // Delegations expire max in 2 months, renewable to 3
507 rv.add(GregorianCalendar.MONTH, 2);
508 now.add(GregorianCalendar.MONTH, 3);
514 // Roles expire in 6 months
515 now.add(GregorianCalendar.MONTH, 6);
519 // Unless other wise set, 6 months is default
520 now.add(GregorianCalendar.MONTH, 6);
528 public EmailWarnings emailWarningPolicy() {
529 return emailWarnings;
533 * Assume the Supervisor is the Approver.
536 public List<Identity> getApprovers(AuthzTrans trans, String user) throws OrganizationException {
537 Identity orgIdentity = getIdentity(trans, user);
538 List<Identity> orgIdentitys = new ArrayList<>();
539 if (orgIdentity!=null) {
540 Identity supervisor = orgIdentity.responsibleTo();
541 if (supervisor!=null) {
542 orgIdentitys.add(supervisor);
549 public String getApproverType() {
554 public int startOfDay() {
555 // TODO Auto-generated method stub
560 public boolean canHaveMultipleCreds(String id) {
561 // External entities are likely mono-password... if you change it, it is a global change.
562 // This is great for people, but horrible for Applications.
564 // AAF's Password can have multiple Passwords, each with their own Expiration Date.
565 // For Default Org, we'll assume true for all, but when you add your external
566 // Identity stores, you need to return "false" if they cannot support multiple Passwords like AAF
571 public String validate(AuthzTrans trans, Policy policy, Executor executor, String... vars) throws OrganizationException {
577 DefaultOrgIdentity thisID = getIdentity(trans,vars[0]);
578 if ("a".equals(thisID.identity.status)) { // MechID
579 DefaultOrgIdentity requestor = getIdentity(trans, trans.user());
580 if (requestor!=null) {
581 Identity mechid = getIdentity(trans, vars[0]);
583 Identity sponsor = mechid.responsibleTo();
584 if (sponsor!=null && requestor.fullID().equals(sponsor.fullID())) {
587 return trans.user() + " is not the Sponsor of MechID " + vars[0];
595 case CREATE_MECHID_BY_PERM_ONLY:
596 return getName() + " only allows sponsors to create MechIDs";
598 case MAY_EXTEND_CRED_EXPIRES:
599 // If parm, use it, otherwise, trans
600 user = vars.length>1?vars[1]:trans.user();
601 return executor.hasPermission(user, root_ns,"password", root_ns , "extend")
602 ?null:user + " does not have permission to extend passwords at " + getName();
605 return policy.name() + " is unsupported at " + getName();
610 public boolean isTestEnv() {
615 public void setTestMode(boolean dryRun) {
616 this.dryRun = dryRun;
619 private String extractRealm(final String r) {
621 if ((at=r.indexOf('@'))>=0) {
622 return FQI.reverseDomain(r.substring(at+1));
627 public boolean supportsRealm(final String r) {
628 if (r.endsWith(realm)) {
631 String erealm = extractRealm(r);
632 for (String sr : supportedRealms) {
633 if (erealm.startsWith(sr)) {
642 public synchronized void addSupportedRealm(final String r) {
643 supportedRealms.add(extractRealm(r));
647 public int sendEmail(AuthzTrans trans, List<String> toList, List<String> ccList, String subject, String body,
648 Boolean urgent) throws OrganizationException {
650 String mailFrom = mailer.mailFrom();
651 List<String> to = new ArrayList<>();
652 for (String em : toList) {
653 if (em.indexOf('@')<0) {
654 to.add(new DefaultOrgIdentity(trans, em, this).email());
660 List<String> cc = new ArrayList<>();
662 if (!ccList.isEmpty()) {
664 for (String em : ccList) {
665 if (em.indexOf('@')<0) {
666 cc.add(new DefaultOrgIdentity(trans, em, this).email());
673 // for now, I want all emails so we can see what goes out. Remove later
674 if (!ccList.contains(mailFrom)) {
675 ccList.add(mailFrom);
679 return mailer.sendEmail(trans,dryRun?"DefaultOrg":null,to,cc,subject,body,urgent)?0:1;