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 javax.mail.Address;
35 import javax.mail.Message;
36 import javax.mail.MessagingException;
37 import javax.mail.Session;
38 import javax.mail.Transport;
39 import javax.mail.internet.InternetAddress;
40 import javax.mail.internet.MimeMessage;
42 import org.onap.aaf.auth.env.AuthzTrans;
43 import org.onap.aaf.auth.org.EmailWarnings;
44 import org.onap.aaf.auth.org.Executor;
45 import org.onap.aaf.auth.org.Organization;
46 import org.onap.aaf.auth.org.OrganizationException;
47 import org.onap.aaf.cadi.util.FQI;
48 import org.onap.aaf.misc.env.Env;
50 public class DefaultOrg implements Organization {
51 private static final String AAF_DATA_DIR = "aaf_data_dir";
52 private static final String PROPERTY_IS_REQUIRED = " property is Required";
55 final String atDomain;
58 private final String NAME,mailHost,mailFrom;
59 private final Set<String> supportedRealms;
62 public DefaultOrg(Env env, String realm) throws OrganizationException {
65 supportedRealms=new HashSet<>();
66 supportedRealms.add(realm);
67 domain=FQI.reverseDomain(realm);
68 atDomain = '@'+domain;
70 NAME=env.getProperty(realm + ".name","Default Organization");
71 mailHost = env.getProperty(s=(realm + ".mailHost"), null);
73 throw new OrganizationException(s + PROPERTY_IS_REQUIRED);
75 mailFrom = env.getProperty(s=(realm + ".mailFrom"), null);
77 throw new OrganizationException(s + PROPERTY_IS_REQUIRED);
80 System.getProperties().setProperty("mail.smtp.host",mailHost);
81 System.getProperties().setProperty("mail.user", mailFrom);
82 // Get the default Session object.
83 session = Session.getDefaultInstance(System.getProperties());
87 String temp=env.getProperty(defFile = (getClass().getName()+".file"));
88 File fIdentities=null;
90 temp = env.getProperty(AAF_DATA_DIR);
92 env.warn().log(defFile, " is not defined. Using default: ",temp+"/identities.dat");
93 File dir = new File(temp);
94 fIdentities=new File(dir,"identities.dat");
96 if(!fIdentities.exists()) {
97 env.warn().log("No",fIdentities.getCanonicalPath(),"exists. Creating.");
101 fIdentities.createNewFile();
105 fIdentities = new File(temp);
106 if(!fIdentities.exists()) {
107 String dataDir = env.getProperty(AAF_DATA_DIR);
109 fIdentities = new File(dataDir,temp);
114 if(fIdentities!=null && fIdentities.exists()) {
115 identities = new Identities(fIdentities);
117 if(fIdentities==null) {
118 throw new OrganizationException("No Identities");
120 throw new OrganizationException(fIdentities.getCanonicalPath() + " does not exist.");
123 } catch (IOException e) {
124 throw new OrganizationException(e);
128 // Implement your own Delegation System
129 static final List<String> NULL_DELEGATES = new ArrayList<>();
131 public Identities identities;
132 private boolean dryRun;
133 private Session session;
134 public enum Types {Employee, Contractor, Application, NotActive};
135 private final static Set<String> typeSet;
138 typeSet = new HashSet<>();
139 for(Types t : Types.values()) {
140 typeSet.add(t.name());
144 private static final EmailWarnings emailWarnings = new DefaultOrgWarnings();
147 public String getName() {
152 public String getRealm() {
157 public String getDomain() {
162 public DefaultOrgIdentity getIdentity(AuthzTrans trans, String id) throws OrganizationException {
163 int at = id.indexOf('@');
164 return new DefaultOrgIdentity(trans,at<0?id:id.substring(0, at),this);
167 // Note: Return a null if found; return a String Message explaining why not found.
169 public String isValidID(final AuthzTrans trans, final String id) {
171 DefaultOrgIdentity u = getIdentity(trans,id);
172 return (u==null||!u.isFound())?id + "is not an Identity in " + getName():null;
173 } catch (OrganizationException e) {
174 return getName() + " could not lookup " + id + ": " + e.getLocalizedMessage();
177 // Possible ID Pattern
178 // private static final Pattern ID_PATTERN=Pattern.compile("([\\w.-]+@[\\w.-]+).{4-13}");
179 // Another one: ID_PATTERN = "(a-z[a-z0-9]{5-8}@.*).{4-13}";
182 public boolean isValidCred(final AuthzTrans trans, final String id) {
184 int at = id.indexOf('@');
187 // Use this to prevent passwords to any but THIS domain.
188 // if(!id.regionMatches(at+1, domain, 0, id.length()-at-1)) {
191 sid = id.substring(0,at);
195 // We'll validate that it exists, rather than check patterns.
197 return isValidID(trans, sid)==null;
198 // Check Pattern (if checking existing is too long)
199 // if(id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) {
205 private static final String SPEC_CHARS = "!@#$%^*-+?/,:;.";
206 private static final Pattern PASS_PATTERN=Pattern.compile("(((?=.*[a-z,A-Z])(((?=.*\\d))|(?=.*[" + SPEC_CHARS +"]))).{6,20})");
209 * (?=.*[a-z,A-Z]) # must contain one character
211 * (?=.*\d) # must contain one digit from 0-9
213 * (?=.*[@#$%]) # must contain one special symbols in the list SPEC_CHARS
215 * . # match anything with previous condition checking
216 * {6,20} # length at least 6 characters and maximum of 20
219 * Another example, more stringent pattern
220 private static final Pattern PASS_PATTERN=Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[" + SPEC_CHARS +"]).{6,20})");
221 * Attribution: from mkyong.com
223 * (?=.*\d) # must contain one digit from 0-9
224 * (?=.*[a-z]) # must contain one lowercase characters
225 * (?=.*[A-Z]) # must contain one uppercase characters
226 * (?=.*[@#$%]) # must contain one special symbols in the list SPEC_CHARS
227 * . # match anything with previous condition checking
228 * {6,20} # length at least 6 characters and maximum of 20
232 public String isValidPassword(final AuthzTrans trans, final String user, final String password, final String... prev) {
233 for(String p : prev) {
234 if(password.contains(p)) { // A more sophisticated algorithm might be better.
235 return "Password too similar to previous passwords";
238 // If you have an Organization user/Password scheme, replace the following
239 if(PASS_PATTERN.matcher(password).matches()) {
242 return "Password does not match " + NAME + " Password Standards";
245 private static final String[] rules = new String[] {
246 "Passwords must contain letters",
247 "Passwords must contain one of the following:",
249 " One special symbols in the list \""+ SPEC_CHARS + '"',
250 "Passwords must be between 6 and 20 chars in length",
254 public String[] getPasswordRules() {
259 public Set<String> getIdentityTypes() {
264 public Response notify(AuthzTrans trans, Notify type, String url, String[] identities, String[] ccs, String summary, Boolean urgent) {
265 String system = trans.getProperty("CASS_ENV", "");
267 ArrayList<String> toList = new ArrayList<>();
269 if (identities != null) {
270 for (String user : identities) {
272 identity = getIdentity(trans, user);
273 if (identity == null) {
275 "Failure to obtain User " + user + " for "
278 toList.add(identity.email());
280 } catch (Exception e) {
283 "Failure to obtain User " + user + " for "
289 if (toList.isEmpty()) {
290 trans.error().log("No Users listed to email");
291 return Response.ERR_NotificationFailure;
294 ArrayList<String> ccList = new ArrayList<>();
296 // If we're sending an urgent email, CC the user's supervisor
299 trans.info().log("urgent msg for: " + identities[0]);
301 List<Identity> supervisors = getApprovers(trans, identities[0]);
302 for (Identity us : supervisors) {
303 trans.info().log("supervisor: " + us.email());
304 ccList.add(us.email());
306 } catch (Exception e) {
308 "Failed to find supervisor for " + identities[0]);
313 for (String user : ccs) {
315 identity = getIdentity(trans, user);
316 ccList.add(identity.email());
317 } catch (Exception e) {
320 "Failure to obtain User " + user + " for "
326 if (summary == null) {
333 sendEmail(trans, toList, ccList,
334 "AAF Approval Notification "
335 + (system.length() == 0 ? "" : "(ENV: "
339 + "System for Fine-Grained Authorizations. You are being asked to Approve"
340 + (system.length() == 0 ? "" : " in the "
341 + system + " environment")
342 + " before AAF Actions can be taken.\n\n"
343 + "Please follow this link: \n\n\t" + url
344 + "\n\n" + summary, urgent);
345 } catch (Exception e) {
347 trans.error().log(e, "Failure to send Email");
348 return Response.ERR_NotificationFailure;
351 case PasswordExpiration:
356 "AAF Password Expiration Warning "
357 + (system.length() == 0 ? "" : "(ENV: "
361 + " System for Authorizations.\n\nOne or more passwords will expire soon or have expired"
362 + (system.length() == 0 ? "" : " in the "
363 + system + " environment")
364 + ".\n\nPasswords expired for more than 30 days without action are subject to deletion.\n\n"
365 + "Please follow each link to add a New Password with Expiration Date. Either are valid until expiration. "
366 + "Use this time to change the passwords on your system. If issues, reply to this email.\n\n"
368 } catch (Exception e) {
369 trans.error().log(e, "Failure to send Email");
370 return Response.ERR_NotificationFailure;
380 "AAF Role Expiration Warning "
381 + (system.length() == 0 ? "" : "(ENV: "
385 + " System for Authorizations. One or more roles will expire soon"
386 + (system.length() == 0 ? "" : " in the "
387 + system + " environment")
388 + ".\n\nRoles expired for more than 30 days are subject to deletion."
389 + "Please follow this link the GUI Command line, and either 'extend' or 'del' the user in the role.\n"
390 + "If issues, reply to this email.\n\n\t" + url
391 + "\n\n" + summary, urgent);
392 } catch (Exception e) {
393 trans.error().log(e, "Failure to send Email");
394 return Response.ERR_NotificationFailure;
398 return Response.ERR_NotImplemented;
404 public int sendEmail(AuthzTrans trans, List<String> toList, List<String> ccList, String subject, String body,
405 Boolean urgent) throws OrganizationException {
409 List<String> to = new ArrayList<>();
410 for(String em : toList) {
411 if(em.indexOf('@')<0) {
412 to.add(new DefaultOrgIdentity(trans, em, this).email());
418 List<String> cc = new ArrayList<>();
420 if(!ccList.isEmpty()) {
422 for(String em : ccList) {
423 if(em.indexOf('@')<0) {
424 cc.add(new DefaultOrgIdentity(trans, em, this).email());
431 // for now, I want all emails so we can see what goes out. Remove later
432 if (!ccList.contains(mailFrom)) {
433 ccList.add(mailFrom);
438 // Create a default MimeMessage object.
439 MimeMessage message = new MimeMessage(session);
441 // Set From: header field of the header.
442 message.setFrom(new InternetAddress(mailFrom));
445 // Set To: header field of the header. This is a required field
446 // and calling module should make sure that it is not null or
448 message.addRecipients(Message.RecipientType.TO,getAddresses(to));
450 // Set CC: header field of the header.
451 if ((ccList != null) && (ccList.size() > 0)) {
452 message.addRecipients(Message.RecipientType.CC,getAddresses(cc));
455 // Set Subject: header field
456 message.setSubject(subject);
459 message.addHeader("X-Priority", "1");
462 // Now set the actual message
463 message.setText(body);
466 // override recipients
467 message.addRecipients(Message.RecipientType.TO,
468 InternetAddress.parse(mailFrom));
470 // Set Subject: header field
471 message.setSubject("[TESTMODE] " + subject);
474 message.addHeader("X-Priority", "1");
477 ArrayList<String> newBody = new ArrayList<>();
479 Address temp[] = getAddresses(to);
480 String headerString = "TO:\t" + InternetAddress.toString(temp) + "\n";
482 temp = getAddresses(cc);
483 headerString += "CC:\t" + InternetAddress.toString(temp) + "\n";
485 newBody.add(headerString);
487 newBody.add("Text: \n");
490 String outString = "";
491 for (String s : newBody) {
492 outString += s + "\n";
495 message.setText(outString);
498 Transport.send(message);
501 } catch (MessagingException mex) {
502 System.out.println("Error messaging: "+ mex.getMessage());
503 System.out.println("Error messaging: "+ mex.toString());
504 throw new OrganizationException("Exception send email message "
512 * Default Policy is to set to 6 Months for Notification Types.
513 * add others/change as required
516 public Date whenToValidate(Notify type, Date lastValidated) {
519 case PasswordExpiration:
522 GregorianCalendar gc = new GregorianCalendar();
523 gc.setTime(lastValidated);
524 gc.add(GregorianCalendar.MONTH, 6); // 6 month policy
530 public GregorianCalendar expiration(GregorianCalendar gc, Expiration exp, String... extra) {
531 GregorianCalendar now = new GregorianCalendar();
532 GregorianCalendar rv = gc==null?now:(GregorianCalendar)gc.clone();
535 // Extending Password give 5 extra days, max 8 days from now
536 rv.add(GregorianCalendar.DATE, 5);
537 now.add(GregorianCalendar.DATE, 8);
543 // Future requests last 15 days.
544 now.add(GregorianCalendar.DATE, 15);
548 // Passwords expire in 90 days
549 now.add(GregorianCalendar.DATE, 90);
553 // Temporary Passwords last for 12 hours.
554 now.add(GregorianCalendar.DATE, 90);
558 // Delegations expire max in 2 months, renewable to 3
559 rv.add(GregorianCalendar.MONTH, 2);
560 now.add(GregorianCalendar.MONTH, 3);
566 // Roles expire in 6 months
567 now.add(GregorianCalendar.MONTH, 6);
571 // Unless other wise set, 6 months is default
572 now.add(GregorianCalendar.MONTH, 6);
580 public EmailWarnings emailWarningPolicy() {
581 return emailWarnings;
585 * Assume the Supervisor is the Approver.
588 public List<Identity> getApprovers(AuthzTrans trans, String user) throws OrganizationException {
589 Identity orgIdentity = getIdentity(trans, user);
590 List<Identity> orgIdentitys = new ArrayList<>();
591 if(orgIdentity!=null) {
592 Identity supervisor = orgIdentity.responsibleTo();
593 if(supervisor!=null) {
594 orgIdentitys.add(supervisor);
601 public String getApproverType() {
606 public int startOfDay() {
607 // TODO Auto-generated method stub
612 public boolean canHaveMultipleCreds(String id) {
613 // External entities are likely mono-password... if you change it, it is a global change.
614 // This is great for people, but horrible for Applications.
616 // AAF's Password can have multiple Passwords, each with their own Expiration Date.
617 // For Default Org, we'll assume true for all, but when you add your external
618 // Identity stores, you need to return "false" if they cannot support multiple Passwords like AAF
623 public String validate(AuthzTrans trans, Policy policy, Executor executor, String... vars) throws OrganizationException {
628 DefaultOrgIdentity thisID = getIdentity(trans,vars[0]);
629 if("a".equals(thisID.identity.status)) { // MechID
630 DefaultOrgIdentity requestor = getIdentity(trans, trans.user());
631 if(requestor!=null) {
632 Identity mechid = getIdentity(trans, vars[0]);
634 Identity sponsor = mechid.responsibleTo();
635 if(sponsor!=null && requestor.fullID().equals(sponsor.fullID())) {
638 return trans.user() + " is not the Sponsor of MechID " + vars[0];
646 case CREATE_MECHID_BY_PERM_ONLY:
647 return getName() + " only allows sponsors to create MechIDs";
650 return policy.name() + " is unsupported at " + getName();
655 public boolean isTestEnv() {
660 public void setTestMode(boolean dryRun) {
661 this.dryRun = dryRun;
665 * Convert the delimiter String into Internet addresses with the default
670 private Address[] getAddresses(List<String> strAddress) throws OrganizationException {
671 return this.getAddresses(strAddress,";");
674 * Convert the delimiter String into Internet addresses with the
675 * delimiter of provided
676 * @param strAddresses
680 private Address[] getAddresses(List<String> strAddresses, String delimiter) throws OrganizationException {
681 Address[] addressArray = new Address[strAddresses.size()];
683 for (String addr : strAddresses)
686 addressArray[count] = new InternetAddress(addr);
689 throw new OrganizationException("Failed to parse the email address "+ addr +": "+e.getMessage());
695 private String extractRealm(final String r) {
697 if((at=r.indexOf('@'))>=0) {
698 return FQI.reverseDomain(r.substring(at+1));
703 public boolean supportsRealm(final String r) {
704 if(r.endsWith(realm)) {
707 String erealm = extractRealm(r);
708 for(String sr : supportedRealms) {
709 if(erealm.startsWith(sr)) {
718 public synchronized void addSupportedRealm(final String r) {
719 supportedRealms.add(extractRealm(r));