Implement public private locator
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / config / Config.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi.config;
23
24 import java.io.IOException;
25 import java.lang.reflect.Constructor;
26 import java.lang.reflect.Field;
27 import java.lang.reflect.InvocationTargetException;
28 import java.lang.reflect.Method;
29 import java.net.HttpURLConnection;
30 import java.net.InetAddress;
31 import java.net.URI;
32 import java.net.UnknownHostException;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.cert.CertificateException;
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.List;
38
39 import javax.servlet.Registration;
40
41 import org.onap.aaf.cadi.AbsUserCache;
42 import org.onap.aaf.cadi.Access;
43 import org.onap.aaf.cadi.Access.Level;
44 import org.onap.aaf.cadi.CachingLur;
45 import org.onap.aaf.cadi.CadiException;
46 import org.onap.aaf.cadi.Connector;
47 import org.onap.aaf.cadi.CredVal;
48 import org.onap.aaf.cadi.CredValDomain;
49 import org.onap.aaf.cadi.Locator;
50 import org.onap.aaf.cadi.LocatorException;
51 import org.onap.aaf.cadi.Lur;
52 import org.onap.aaf.cadi.PropAccess;
53 import org.onap.aaf.cadi.Symm;
54 import org.onap.aaf.cadi.TrustChecker;
55 import org.onap.aaf.cadi.lur.EpiLur;
56 import org.onap.aaf.cadi.lur.LocalLur;
57 import org.onap.aaf.cadi.lur.NullLur;
58 import org.onap.aaf.cadi.taf.HttpEpiTaf;
59 import org.onap.aaf.cadi.taf.HttpTaf;
60 import org.onap.aaf.cadi.taf.basic.BasicHttpTaf;
61 import org.onap.aaf.cadi.taf.cert.X509Taf;
62 import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf;
63 import org.onap.aaf.cadi.util.FixURIinfo;
64 import org.onap.aaf.cadi.util.Split;
65
66 /**
67  * Create a Consistent Configuration mechanism, even when configuration styles are as vastly different as
68  * Properties vs JavaBeans vs FilterConfigs...
69  * 
70  * @author Jonathan
71  *
72  */
73 public class Config {
74
75     private static final String AAF_V2_0 = "org.onap.aaf.cadi.aaf.v2_0";
76     private static final String AAF_V2_0_AAFCON = AAF_V2_0+".AAFCon";
77     private static final String AAF_V2_0_AAF_LUR_PERM = AAF_V2_0+".AAFLurPerm";
78     private static final String OAUTH = "org.onap.auth.oauth";
79     private static final String OAUTH_TOKEN_MGR = OAUTH+".TokenMgr";
80     private static final String OAUTH_HTTP_TAF = OAUTH+".OAuth2HttpTaf";
81     private static final String OAUTH_DIRECT_TAF = OAUTH+".OAuthDirectTAF";
82     public static final String UTF_8 = "UTF-8";
83
84     // Property Names associated with configurations.
85     // As of 1.0.2, these have had the dots removed so as to be compatible with JavaBean style
86     // configurations as well as property list style.
87     public static final String HOSTNAME = "hostname";
88     public static final String CADI_PROP_FILES = "cadi_prop_files"; // Additional Properties files (separate with ;)
89     public static final String CADI_LOGLEVEL = "cadi_loglevel";
90     public static final String CADI_LOGDIR = "cadi_log_dir";
91     public static final String CADI_ETCDIR = "cadi_etc_dir";
92     public static final String CADI_LOGNAME = "cadi_logname";
93     public static final String CADI_KEYFILE = "cadi_keyfile";
94     public static final String CADI_KEYSTORE = "cadi_keystore";
95     public static final String CADI_KEYSTORE_PASSWORD = "cadi_keystore_password";
96     public static final String CADI_ALIAS = "cadi_alias";
97     public static final String CADI_LOGINPAGE_URL = "cadi_loginpage_url";
98     public static final String CADI_LATITUDE = "cadi_latitude";
99     public static final String CADI_LONGITUDE = "cadi_longitude";
100
101
102     public static final String CADI_KEY_PASSWORD = "cadi_key_password";
103     public static final String CADI_TRUSTSTORE = "cadi_truststore";
104     public static final String CADI_TRUSTSTORE_PASSWORD = "cadi_truststore_password";
105     public static final String CADI_X509_ISSUERS = "cadi_x509_issuers";
106     public static final String CADI_TRUST_MASKS="cadi_trust_masks";
107     public static final String CADI_TRUST_PERM="cadi_trust_perm"; //  IDs with this perm can utilize the "AS " user concept
108     public static final String CADI_PROTOCOLS = "cadi_protocols";
109     public static final String CADI_NOAUTHN = "cadi_noauthn";
110     public static final String CADI_LOC_LIST = "cadi_loc_list";
111     
112     // Special Behaviors
113     public static final String CADI_BATH_CONVERT = "cadi_bath_convert";
114     public static final String CADI_API_ENFORCEMENT = "cadi_api_enforcement";
115     public static final String CADI_ADD_TAFS = "cadi_add_tafs";
116     public static final String CADI_ADD_LURS = "cadi_add_lurs";
117     
118     public static final String CADI_USER_CHAIN_TAG = "cadi_user_chain";
119     public static final String CADI_USER_CHAIN = "USER_CHAIN";
120     
121     public static final String CADI_OAUTH2_URL="cadi_oauth2_url";
122     public static final String CADI_TOKEN_DIR = "cadi_token_dir";
123
124     public static final String HTTPS_PROTOCOLS = "https.protocols";
125     public static final String HTTPS_CIPHER_SUITES = "https.cipherSuites";
126     public static final String HTTPS_CLIENT_PROTOCOLS="jdk.tls.client.protocols";
127     public static final String HTTPS_CIPHER_SUITES_DEFAULT="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,"
128             + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,"
129             + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,"
130             + "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA,TLS_ECDH_ECDSA_WITH_RC4_128_SHA,"
131             + "TLS_ECDH_RSA_WITH_RC4_128_SHA,TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,"
132             + "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
133              
134
135     public static final String LOCALHOST_ALLOW = "localhost_allow";
136     public static final String LOCALHOST_DENY = "localhost_deny";
137     
138     public static final String BASIC_REALM = "basic_realm";  // what is sent to the client 
139     public static final String BASIC_WARN = "basic_warn";  // Warning of insecure channel 
140     public static final String USERS = "local_users";
141     public static final String GROUPS = "local_groups";
142     public static final String WRITE_TO = "local_writeto"; // dump RBAC to local file in Tomcat Style (some apps use)
143     
144     public static final String OAUTH_CLIENT_ID="client_id";
145     public static final String OAUTH_CLIENT_SECRET="client_secret";
146     
147     public static final String AAF_ENV = "aaf_env";
148     public static final String AAF_ROOT_NS = "aaf_root_ns";
149     public static final String AAF_ROOT_NS_DEF = "org.osaaf.aaf";
150     public static final String AAF_ROOT_COMPANY = "aaf_root_company";
151     public static final String AAF_LOCATE_URL = "aaf_locate_url"; //URL for AAF locator
152     public static final String AAF_LOCATE_URL_TAG = "AAF_LOCATE_URL"; // Name of Above for use in Config Variables.
153     public static final String AAF_DEFAULT_API_VERSION = "2.1";
154     public static final String AAF_API_VERSION = "aaf_api_version";
155     public static final String AAF_URL = "aaf_url"; //URL for AAF... Use to trigger AAF configuration
156     public static final String AAF_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.service:" + AAF_DEFAULT_API_VERSION;
157     public static final String GUI_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.gui:" + AAF_DEFAULT_API_VERSION;
158     public static final String CM_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.cm:" + AAF_DEFAULT_API_VERSION;
159     public static final String FS_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.fs:" + AAF_DEFAULT_API_VERSION;
160     public static final String HELLO_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.hello:" + AAF_DEFAULT_API_VERSION;
161     public static final String OAUTH2_TOKEN_URL = "https://AAF_LOCATE_URL/AAF_NS.token:" + AAF_DEFAULT_API_VERSION;
162     public static final String OAUTH2_INTROSPECT_URL = "https://AAF_LOCATE_URL/AAF_NS.introspect:" + AAF_DEFAULT_API_VERSION;
163
164     public static final String AAF_LOCATOR_CLASS = "aaf_locator_class";
165     // AAF Locator Entries are ADDITIONAL entries, which also gives the Property ability
166     // to set these entries manually
167     // example: adding a K8S name like "oom"
168     // this will allow Registrations to pick up 
169     // locator_ns.oom for onap's "OOM" based k8s entries, etc.
170     public static final String AAF_LOCATOR_CONTAINER="aaf_locator_container";
171     // An ID for another Container, to be used to avoid picking up the wrong internal info 
172     // for another container.
173     public static final String AAF_LOCATOR_CONTAINER_ID = "aaf_locator_container_id";
174     public static final String AAF_LOCATOR_CONTAINER_NS = "aaf_locator_container_ns";
175     public static final String AAF_LOCATOR_VERSION = "aaf_locator_version";
176     public static final String AAF_LOCATOR_PROTOCOL = "aaf_locator_protocol";
177     public static final String AAF_LOCATOR_SUBPROTOCOL = "aaf_locator_subprotocol";
178     public static final String AAF_LOCATOR_NS = "aaf_locator_ns";
179     public static final String AAF_LOCATOR_ENTRIES = "aaf_locator_entries";
180     public static final String AAF_LOCATOR_FQDN = "aaf_locator_fqdn";
181     public static final String AAF_LOCATOR_NAME = "aaf_locator_name";
182     public static final String AAF_LOCATOR_PUBLIC_PORT = "aaf_locator_public_port";
183     public static final String AAF_LOCATOR_PUBLIC_HOSTNAME = "aaf_locator_public_hostname";
184
185     public static final String AAF_APPID = "aaf_id";
186     public static final String AAF_APPPASS = "aaf_password";
187     public static final String AAF_LUR_CLASS = "aaf_lur_class";
188     public static final String AAF_TAF_CLASS = "aaf_taf_class";
189     public static final String AAF_CONNECTOR_CLASS = "aaf_connector_class";
190     public static final String AAF_CONN_TIMEOUT = "aaf_conn_timeout";
191     public static final String AAF_CONN_TIMEOUT_DEF = "3000";
192     public static final String AAF_CONN_IDLE_TIMEOUT = "aaf_conn_idle_timeout"; // only for Direct Jetty Access.
193     public static final String AAF_CONN_IDLE_TIMEOUT_DEF = "10000"; // only for Direct Jetty Access.
194      
195     // Default Classes: These are for Class loading to avoid direct compile links
196     public static final String AAF_TAF_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFTaf";
197     public static final String AAF_LOCATOR_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFLocator";
198     public static final String CADI_OLUR_CLASS_DEF = "org.onap.aaf.cadi.olur.OLur";
199     public static final String CADI_OBASIC_HTTP_TAF_DEF = "org.onap.aaf.cadi.obasic.OBasicHttpTaf";
200     public static final String CADI_AAF_CON_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFCon";
201
202     public static final String AAF_CALL_TIMEOUT = "aaf_timeout";
203     public static final String AAF_CALL_TIMEOUT_DEF = "5000";
204     public static final String AAF_USER_EXPIRES = "aaf_user_expires";
205     public static final String AAF_USER_EXPIRES_DEF = "600000"; // Default is 10 mins
206     public static final String AAF_CLEAN_INTERVAL = "aaf_clean_interval";
207     public static final String AAF_CLEAN_INTERVAL_DEF = "30000"; // Default is 30 seconds
208     public static final String AAF_REFRESH_TRIGGER_COUNT = "aaf_refresh_trigger_count";
209     public static final String AAF_REFRESH_TRIGGER_COUNT_DEF = "3"; // Default is 10 mins
210     
211     public static final String AAF_HIGH_COUNT = "aaf_high_count";
212     public static final String AAF_HIGH_COUNT_DEF = "1000"; // Default is 1000 entries
213     public static final String AAF_PERM_MAP = "aaf_perm_map";
214 //    public static final String AAF_COMPONENT = "aaf_component";
215     public static final String AAF_CERT_IDS = "aaf_cert_ids";
216     public static final String AAF_DEBUG_IDS = "aaf_debug_ids"; // comma delimited
217     public static final String AAF_DATA_DIR = "aaf_data_dir"; // AAF processes and Components only.
218     public static final String AAF_RELEASE = "aaf_release";
219
220     public static final String GW_URL = "gw_url";
221     public static final String CM_URL = "cm_url";
222     public static final String CM_TRUSTED_CAS = "cm_trusted_cas";
223
224     public static final String PATHFILTER_URLPATTERN = "pathfilter_urlpattern";
225     public static final String PATHFILTER_STACK = "pathfilter_stack";
226     public static final String PATHFILTER_NS = "pathfilter_ns";
227     public static final String PATHFILTER_NOT_AUTHORIZED_MSG = "pathfilter_not_authorized_msg";
228
229     // This one should go unpublic
230     public static final String AAF_DEFAULT_REALM = "aaf_default_realm";
231     private static String defaultRealm="none";
232
233     public static final String AAF_DOMAIN_SUPPORT = "aaf_domain_support";
234     public static final String AAF_DOMAIN_SUPPORT_DEF = ".com:.org";
235
236     // OAUTH2
237     public static final String AAF_OAUTH2_TOKEN_URL = "aaf_oauth2_token_url";
238     public static final String AAF_OAUTH2_INTROSPECT_URL = "aaf_oauth2_introspect_url";
239     public static final String AAF_ALT_OAUTH2_TOKEN_URL = "aaf_alt_oauth2_token_url";
240     public static final String AAF_ALT_OAUTH2_INTROSPECT_URL = "aaf_alt_oauth2_introspect_url";
241     public static final String AAF_ALT_OAUTH2_DOMAIN = "aaf_alt_oauth2_domain"; 
242     public static final String AAF_ALT_CLIENT_ID = "aaf_alt_oauth2_client_id";
243     public static final String AAF_ALT_CLIENT_SECRET = "aaf_alt_oauth2_client_secret";
244     public static final String AAF_OAUTH2_HELLO_URL = "aaf_oauth2_hello_url";
245
246     private static final String AAF_V2_0_AAF_CON_HTTP = "org.onap.aaf.cadi.aaf.v2_0.AAFConHttp";
247
248
249     public static void setDefaultRealm(Access access) {
250         try {
251             defaultRealm = logProp(access,Config.AAF_DEFAULT_REALM,
252                 logProp(access,Config.BASIC_REALM,
253                     logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName())
254                     )
255                 );
256         } catch (UnknownHostException e) {
257             access.log(Level.INIT, "Unable to determine Hostname",e);
258         }
259     }
260
261     public static HttpTaf configHttpTaf(Connector con, SecurityInfoC<HttpURLConnection> si, TrustChecker tc, CredVal up, Lur lur, Object ... additionalTafLurs) throws CadiException, LocatorException {
262         Access access = si.access;
263         /////////////////////////////////////////////////////
264         // Setup AAFCon for any following
265         /////////////////////////////////////////////////////
266         Class<?> aafConClass = loadClass(access,CADI_AAF_CON_DEF);
267         Object aafcon = null;
268         if (con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) {
269             aafcon = con;
270         } else if (lur != null) {
271             Field f;
272             try {
273                 f = lur.getClass().getField("aaf");
274                 aafcon = f.get(lur);
275             } catch (Exception e) {
276                 access.log(Level.INIT, e);
277             }
278         }
279
280         boolean hasDirectAAF = hasDirect("DirectAAFLur",additionalTafLurs);
281         // IMPORTANT!  Don't attempt to load AAF Connector if there is no AAF URL
282         String aafURL = access.getProperty(AAF_URL,null);
283         if (!hasDirectAAF && aafcon==null && aafURL!=null) {
284             aafcon = loadAAFConnector(si, aafURL);    
285         }
286         
287         HttpTaf taf;
288         // Setup Host, in case Network reports an unusable Hostname (i.e. VTiers, VPNs, etc)
289         String hostname = logProp(access, HOSTNAME,null);
290         if (hostname==null) {
291             try {
292                 hostname = InetAddress.getLocalHost().getHostName();
293             } catch (UnknownHostException e1) {
294                 throw new CadiException("Unable to determine Hostname",e1);
295             }
296         }
297         
298         access.log(Level.INIT, "Hostname set to",hostname);
299         // Get appropriate TAFs
300         ArrayList<Priori<HttpTaf>> htlist = new ArrayList<>();
301
302         /////////////////////////////////////////////////////
303         // Add a Denial of Service TAF
304         // Note: how IPs and IDs are added are up to service type.
305         // They call "DenialOfServiceTaf.denyIP(String) or denyID(String)
306         /////////////////////////////////////////////////////
307         htlist.add(new Priori<HttpTaf>(new DenialOfServiceTaf(access),0));
308
309         /////////////////////////////////////////////////////
310         // Configure Client Cert TAF
311         /////////////////////////////////////////////////////
312         X509Taf x509TAF = null;
313         String truststore = logProp(access, CADI_TRUSTSTORE,null);
314         if (truststore!=null) {
315             String truststorePwd = access.getProperty(CADI_TRUSTSTORE_PASSWORD,null);
316             if (truststorePwd!=null) {
317                 if (truststorePwd.startsWith(Symm.ENC)) {
318                     try {
319                         access.decrypt(truststorePwd,false);
320                     } catch (IOException e) {
321                         throw new CadiException(CADI_TRUSTSTORE_PASSWORD + " cannot be decrypted",e);
322                     }
323                 }
324                 try {
325                     x509TAF=new X509Taf(access,lur);
326                     htlist.add(new Priori<HttpTaf>(x509TAF,10));
327                     access.log(Level.INIT,"Certificate Authorization enabled");
328                 } catch (SecurityException | IllegalArgumentException e) {
329                     access.log(Level.INIT,"AAFListedCertIdentity cannot be instantiated. Certificate Authorization is now disabled",e);
330                 } catch (CertificateException e) {
331                     access.log(Level.INIT,"Certificate Authorization failed, it is disabled",e);
332                 } catch (NoSuchAlgorithmException e) {
333                     access.log(Level.INIT,"Certificate Authorization failed, wrong Security Algorithm",e);
334                 }
335             }
336         } else {
337             access.log(Level.INIT,"Certificate Authorization not enabled");
338         }
339         
340         /////////////////////////////////////////////////////
341         // Configure Basic Auth (local content)
342         /////////////////////////////////////////////////////
343         boolean hasOAuthDirectTAF = hasDirect("DirectOAuthTAF", additionalTafLurs);
344         String basicRealm = logProp(access, BASIC_REALM,null);
345         String aafCleanup = logProp(access, AAF_USER_EXPIRES,AAF_USER_EXPIRES_DEF); // Default is 10 mins
346         long userExp = Long.parseLong(aafCleanup);
347         boolean basicWarn = "TRUE".equals(access.getProperty(BASIC_WARN,"FALSE"));
348
349         if (!hasDirectAAF) {
350             HttpTaf aaftaf=null;
351             if (!hasOAuthDirectTAF) {
352                 if (basicRealm!=null) {
353                     @SuppressWarnings("unchecked")
354                     Class<HttpTaf> obasicCls = (Class<HttpTaf>)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF);
355                     if (obasicCls!=null) {
356                         try {
357                             String tokenurl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL, null);
358                             String introspecturl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL, null);
359                             if (tokenurl==null || introspecturl==null) {
360                                 access.log(Level.INIT,"Both tokenurl and introspecturl are required. Oauth Authorization is disabled.");
361                             }
362                             Constructor<HttpTaf> obasicConst = obasicCls.getConstructor(PropAccess.class,String.class, String.class, String.class);
363                             htlist.add(new Priori<HttpTaf>(obasicConst.newInstance(access,basicRealm,tokenurl,introspecturl),20));
364                             access.log(Level.INIT,"Oauth supported Basic Authorization is enabled");
365                         } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
366                             access.log(Level.INIT, e);
367                         }
368                     } else if (up!=null) {
369                         access.log(Level.INIT,"Basic Authorization is enabled using realm",basicRealm);
370                         // Allow warning about insecure channel to be turned off
371                         if (!basicWarn) {
372                             access.log(Level.INIT, "WARNING! The basicWarn property has been set to false.",
373                                 " There will be no additional warning if Basic Auth is used on an insecure channel");
374                         }
375                         BasicHttpTaf bht = new BasicHttpTaf(access, up, basicRealm, userExp, basicWarn);
376                         for (Object o : additionalTafLurs) {
377                             if (o instanceof CredValDomain) {
378                                 bht.add((CredValDomain)o);
379                             }
380                         }
381                         if (x509TAF!=null) {
382                             x509TAF.add(bht);
383                         }
384                         htlist.add(new Priori<HttpTaf>(bht,20));
385                         access.log(Level.INIT,"Basic Authorization is enabled");
386                     }
387                 } else {
388                     access.log(Level.INIT,"Local Basic Authorization is disabled.  Enable by setting basicRealm=<appropriate realm, i.e. my.att.com>");
389                 }
390             
391                 /////////////////////////////////////////////////////
392                 // Configure AAF Driven Basic Auth
393                 /////////////////////////////////////////////////////
394                 if (aafcon==null) {
395                     access.log(Level.INIT,"AAF Connection (AAFcon) is null.  Cannot create an AAF TAF");
396                 } else if (aafURL==null) {
397                     access.log(Level.INIT,"No AAF URL in properties, Cannot create an AAF TAF");
398                 } else {// There's an AAF_URL... try to configure an AAF 
399                     String aafTafClassName = logProp(access, AAF_TAF_CLASS,AAF_TAF_CLASS_DEF);
400                     // Only 2.0 available at this time
401                     if (AAF_TAF_CLASS_DEF.equals(aafTafClassName)) { 
402                         try {
403                             Class<?> aafTafClass = loadClass(access,aafTafClassName);
404                             if (aafTafClass!=null) {
405                                 Constructor<?> cstr = aafTafClass.getConstructor(Connector.class,boolean.class,AbsUserCache.class);
406                                 if (cstr!=null) {
407                                     if (lur instanceof AbsUserCache) {
408                                         aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn,lur);
409                                     } else {
410                                         cstr = aafTafClass.getConstructor(Connector.class,boolean.class);
411                                         if (cstr!=null) {
412                                             aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn);
413                                         }
414                                     }
415                                     if (aaftaf==null) {
416                                         access.log(Level.INIT,"ERROR! AAF TAF Failed construction.  NOT Configured");
417                                     } else {
418                                         access.log(Level.INIT,"AAF TAF Configured to ",aafURL);
419                                         // Note: will add later, after all others configured
420                                     }
421                                 }
422                             } else {
423                                 access.log(Level.INIT, "There is no AAF TAF class available: %s. AAF TAF not configured.",aafTafClassName);
424                             }
425                         } catch (Exception e) {
426                             access.log(Level.INIT,"ERROR! AAF TAF Failed construction.  NOT Configured",e);
427                         }
428                     }
429                 }
430             }
431             
432             /////////////////////////////////////////////////////
433             // Configure OAuth TAF
434             /////////////////////////////////////////////////////
435             if (!hasOAuthDirectTAF) {
436                 String oauthTokenUrl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL,null);
437                 Class<?> oadtClss;
438                 try {
439                     oadtClss = Class.forName(OAUTH_DIRECT_TAF);
440                 } catch (ClassNotFoundException e1) {
441                     oadtClss = null;
442                     access.log(Level.DEBUG, e1);
443                 }
444                 if (additionalTafLurs!=null && additionalTafLurs.length>0 && (oadtClss!=null && additionalTafLurs[0].getClass().isAssignableFrom(oadtClss))) {
445                     htlist.add(new Priori<HttpTaf>((HttpTaf)additionalTafLurs[0],30));
446                     String[] array= new String[additionalTafLurs.length-1];
447                     if (array.length>0) {
448                         System.arraycopy(htlist, 1, array, 0, array.length);
449                     }
450                     additionalTafLurs = array;
451                     access.log(Level.INIT,"OAuth2 Direct is enabled");
452                 } else if (oauthTokenUrl!=null) {
453                     String oauthIntrospectUrl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL,null);
454                     @SuppressWarnings("unchecked")
455                     Class<HttpTaf> oaTCls = (Class<HttpTaf>)loadClass(access,OAUTH_HTTP_TAF);
456                     if (oaTCls!=null) {
457                         Class<?> oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR);
458                         if (oaTTmgrCls!=null) {
459                             try {
460                                 Method oaTTmgrGI = oaTTmgrCls.getMethod("getInstance",PropAccess.class,String.class,String.class);
461                                 Object oaTTmgr = oaTTmgrGI.invoke(null /*this is static method*/,access,oauthTokenUrl,oauthIntrospectUrl);
462                                 Constructor<HttpTaf> oaTConst = oaTCls.getConstructor(Access.class,oaTTmgrCls);
463                                 htlist.add(new Priori<HttpTaf>(oaTConst.newInstance(access,oaTTmgr),30));
464                                 access.log(Level.INIT,"OAuth2 TAF is enabled");
465                             } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
466                                 access.log(Level.INIT,"OAuth2HttpTaf cannot be instantiated. OAuth2 is disabled",e);
467                             }
468                         }
469                     }
470                 } else {
471                     access.log(Level.INIT,"OAuth TAF is not configured");
472                 }
473             }
474     
475             /////////////////////////////////////////////////////
476             // Adding BasicAuth (AAF) last, after other primary Cookie Based
477             // Needs to be before Cert... see below
478             /////////////////////////////////////////////////////
479             if (aaftaf!=null) {
480                 htlist.add(new Priori<HttpTaf>(aaftaf,40));
481             }
482         }    
483
484         /////////////////////////////////////////////////////
485         // Any Additional Tafs passed in Constructor
486         /////////////////////////////////////////////////////
487         if (additionalTafLurs!=null) {
488                 int i=0;
489             for (Object additional : additionalTafLurs) {
490                 if (additional instanceof BasicHttpTaf) {
491                     BasicHttpTaf ht = (BasicHttpTaf)additional;
492                     for (Object cv : additionalTafLurs) {
493                         if (cv instanceof CredValDomain) {
494                             ht.add((CredValDomain)cv);
495                             access.printf(Level.INIT,"%s Authentication is enabled",cv);
496                         }
497                     }
498                     htlist.add(new Priori<HttpTaf>(ht,50+i++));
499                 } else if (additional instanceof HttpTaf) {
500                     HttpTaf ht = (HttpTaf)additional;
501                     htlist.add(new Priori<HttpTaf>(ht,50+i++));
502                     access.printf(Level.INIT,"%s Authentication is enabled",additional.getClass().getSimpleName());
503                 } else if (hasOAuthDirectTAF) {
504                     Class<?> daupCls;
505                     try {
506                         daupCls = Class.forName("org.onap.aaf.auth.direct.DirectAAFUserPass");
507                     } catch (ClassNotFoundException e) {
508                         daupCls = null;
509                         access.log(Level.INIT, e);
510                     }
511                     if (daupCls != null && additional.getClass().isAssignableFrom(daupCls)) {
512                         htlist.add(new Priori<HttpTaf>(new BasicHttpTaf(access, (CredVal)additional , basicRealm, userExp, basicWarn),50+i++));
513                         access.printf(Level.INIT,"Direct BasicAuth Authentication is enabled",additional.getClass().getSimpleName());
514                     }
515                 }
516             }
517         }
518         
519         // Add BasicAuth, if any, to x509Taf
520         if (x509TAF!=null) {
521             for ( Priori<HttpTaf> ht : htlist) {
522                 if (ht.t instanceof BasicHttpTaf) {
523                     x509TAF.add((BasicHttpTaf)ht.t);
524                 }
525             }
526         }
527         
528         /////////////////////////////////////////////////////
529         // Additional TAFs by Plugin
530         /////////////////////////////////////////////////////
531         Priori.add(access, CADI_ADD_TAFS, htlist);
532         
533         /////////////////////////////////////////////////////
534         // Create EpiTaf from configured TAFs
535         /////////////////////////////////////////////////////
536         if (htlist.size()==1) {
537             // just return the one
538             taf = htlist.get(0).t;
539         } else {
540                 Collections.sort(htlist);
541             HttpTaf[] htarray = new HttpTaf[htlist.size()];
542             int i=-1;
543             StringBuilder sb = new StringBuilder("Tafs processed in this order:\n");
544             for(Priori<HttpTaf> pht : htlist) {
545                 htarray[++i] = pht.t;
546                 sb.append("    ");
547                 sb.append(pht.t.getClass().getName());
548                 sb.append('(');
549                 sb.append(pht.priority);
550                 sb.append(")\n");
551             }
552             access.log(Level.INIT, sb);
553
554             Locator<URI> locator = loadLocator(si, logProp(access, AAF_LOCATE_URL, null));
555             
556             taf = new HttpEpiTaf(access,locator, tc, htarray); // ok to pass locator == null
557             String level = logProp(access, CADI_LOGLEVEL, null);
558             if (level!=null) {
559                 access.setLogLevel(Level.valueOf(level));
560             }
561         }
562         
563         return taf;
564     }
565     
566     public static String logProp(Access access,String tag, String def) {
567         String rv = access.getProperty(tag, def);
568         if (rv == null) {
569             access.log(Level.INIT,tag,"is not explicitly set");
570         } else {
571             access.log(Level.INIT,tag,"is set to",rv);
572         }
573         return rv;
574     }
575     
576     public static Lur configLur(SecurityInfoC<HttpURLConnection> si, Connector con, Object ... additionalTafLurs) throws CadiException {
577         Access access = si.access;
578         List<Priori<Lur>> lurs = new ArrayList<>();
579         
580         /////////////////////////////////////////////////////
581         // Configure a Local Property Based RBAC/LUR
582         /////////////////////////////////////////////////////
583         try {
584             String users = access.getProperty(USERS,null);
585             String groups = access.getProperty(GROUPS,null);
586
587             if (groups!=null || users!=null) {
588                 LocalLur ll = new LocalLur(access, users, groups);  // note b64==null is ok.. just means no encryption.
589                 lurs.add(new Priori<Lur>(ll,10));
590                 
591                 String writeto = access.getProperty(WRITE_TO,null);
592                 if (writeto!=null) {
593                     String msg = UsersDump.updateUsers(writeto, ll);
594                     if (msg!=null) {
595                         access.log(Level.INIT,"ERROR! Error Updating ",writeto,"with roles and users:",msg);
596                     }
597                 }
598             }
599         } catch (IOException e) {
600             throw new CadiException(e);
601         }
602
603         /////////////////////////////////////////////////////
604         // Configure the OAuth Lur (if any)
605         /////////////////////////////////////////////////////
606         String tokenUrl = logProp(access,AAF_OAUTH2_TOKEN_URL, null);
607         String introspectUrl = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null);
608         if (tokenUrl!=null && introspectUrl !=null) {
609             try {
610                 Class<?> olurCls = loadClass(access, CADI_OLUR_CLASS_DEF);
611                 if (olurCls!=null) {
612                     Constructor<?> olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class);
613                     Lur olur = (Lur)olurCnst.newInstance(access,tokenUrl,introspectUrl);
614                     lurs.add(new Priori<Lur>(olur,20));
615                     access.log(Level.INIT, "OAuth2 LUR enabled");
616                 } else {
617                     access.log(Level.INIT,"AAF/OAuth LUR plugin is not available.");
618                 }
619             } catch (NoSuchMethodException| SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
620                 String msg = e.getMessage();
621                 if (msg==null && e.getCause()!=null) {
622                     msg = e.getCause().getMessage();
623                 }
624                 access.log(Level.INIT,"AAF/OAuth LUR is not instantiated.",msg,e);
625             } 
626         } else {
627             access.log(Level.INIT, "OAuth2 Lur disabled");
628         }
629
630         if (con!=null) { // try to reutilize connector
631             lurs.add(new Priori<Lur>(con.newLur(),30));
632         } else { 
633             /////////////////////////////////////////////////////
634             // Configure the AAF Lur (if any)
635             /////////////////////////////////////////////////////
636             String aafURL = logProp(access,AAF_URL,null); // Trigger Property
637             String aafEnv = access.getProperty(AAF_ENV,null);
638             if (aafEnv == null && aafURL!=null && access instanceof PropAccess) { // set AAF_ENV from AAF_URL
639                 int ec = aafURL.indexOf("envContext=");
640                 if (ec>0) {
641                     ec += 11; // length of envContext=
642                     int slash = aafURL.indexOf('/', ec);
643                     if (slash>0) {
644                         aafEnv = aafURL.substring(ec, slash);
645                         ((PropAccess)access).setProperty(AAF_ENV, aafEnv);
646                         access.printf(Level.INIT, "Setting aafEnv to %s from aaf_url value",aafEnv);
647                     }
648                 }
649             }
650
651             // Don't configure AAF if it is using DirectAccess
652             if (!hasDirect("DirectAAFLur",additionalTafLurs)) {
653                 if (aafURL==null) {
654                     access.log(Level.INIT,"No AAF LUR properties, AAF will not be loaded");
655                 } else {// There's an AAF_URL... try to configure an AAF
656                     String aafLurClassStr = logProp(access,AAF_LUR_CLASS,AAF_V2_0_AAF_LUR_PERM);
657                     ////////////AAF Lur 2.0 /////////////
658                     if (aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { 
659                         try {
660                             Object aafcon = loadAAFConnector(si, aafURL);
661                             if (aafcon==null) {
662                                 access.log(Level.INIT,"AAF LUR class,",aafLurClassStr,"cannot be constructed without valid AAFCon object.");
663                             } else {
664                                 Class<?> aafAbsAAFCon = loadClass(access, AAF_V2_0_AAFCON);
665                                 if (aafAbsAAFCon!=null) {
666                                     Method mNewLur = aafAbsAAFCon.getMethod("newLur");
667                                     Object aaflur = mNewLur.invoke(aafcon);
668                 
669                                     if (aaflur==null) {
670                                         access.log(Level.INIT,"ERROR! AAF LUR Failed construction.  NOT Configured");
671                                     } else {
672                                         access.log(Level.INIT,"AAF LUR Configured to ",aafURL);
673                                         lurs.add(new Priori<Lur>((Lur)aaflur,40));
674                                         String debugIDs = logProp(access,Config.AAF_DEBUG_IDS, null);
675                                         if (debugIDs !=null && aaflur instanceof CachingLur) {
676                                             ((CachingLur<?>)aaflur).setDebug(debugIDs);
677                                         }
678                                     }
679                                 }
680                             }
681                         } catch (Exception e) {
682                             access.log(e,"AAF LUR class,",aafLurClassStr,"could not be constructed with given Constructors.");
683                         }
684                     } 
685                 }
686             }
687         }
688
689         /////////////////////////////////////////////////////
690         // Any Additional passed in Constructor
691         /////////////////////////////////////////////////////
692         if (additionalTafLurs!=null) {
693                 int i=0;
694             for (Object additional : additionalTafLurs) {
695                 if (additional instanceof Lur) {
696                     lurs.add(new Priori<Lur>((Lur)additional,50+i++));
697                     access.log(Level.INIT, additional);
698                 }
699             }
700         }
701
702         /////////////////////////////////////////////////////
703         // Additional LURs by Plugin
704         /////////////////////////////////////////////////////
705         Priori.add(access, CADI_ADD_LURS, lurs);       
706
707         /////////////////////////////////////////////////////
708         // Return a Lur based on how many there are... 
709         /////////////////////////////////////////////////////
710         switch(lurs.size()) {
711             case 0: 
712                 access.log(Level.INIT,"WARNING! No CADI LURs configured");
713                 // Return a NULL Lur that does nothing.
714                 return new NullLur();
715             case 1:
716                 return lurs.get(0).t; // Only one, just return it, save processing
717             default:
718                 // Multiple Lurs, use EpiLUR to handle
719                 Collections.sort(lurs);
720                 Lur[] la = new Lur[lurs.size()];
721                 int i=-1;
722                 StringBuilder sb = new StringBuilder("Lurs processed in this order:\n");
723                 for(Priori<Lur> pht : lurs) {
724                         la[++i] = pht.t;
725                         sb.append("    ");
726                         sb.append(pht.t.getClass().getName());
727                         sb.append('(');
728                         sb.append(pht.priority);
729                         sb.append(")\n");
730                 }
731                 access.log(Level.INIT, sb);
732                 return new EpiLur(la);
733         }
734     }
735     
736     private static boolean hasDirect(String simpleClassName, Object[] additionalTafLurs) {
737         if (additionalTafLurs!=null) {
738             for (Object tf : additionalTafLurs) {
739                 if (tf.getClass().getSimpleName().equals(simpleClassName)) {
740                     return true;
741                 }
742             }
743         }
744         return false;
745     }
746
747     public static Object loadAAFConnector(SecurityInfoC<HttpURLConnection> si, String aafURL) {
748         Access access = si.access;
749         Object aafcon = null;
750         Class<?> aafConClass = null;
751
752         try {
753             if (aafURL!=null) {
754                 String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, AAF_V2_0_AAF_CON_HTTP);
755                 if (AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) {
756                     aafConClass = loadClass(access, AAF_V2_0_AAF_CON_HTTP);
757                     if (aafConClass != null) {
758                         for (Constructor<?> c : aafConClass.getConstructors()) {
759                             List<Object> lo = new ArrayList<>();
760                             for (Class<?> pc : c.getParameterTypes()) {
761                                 if (pc.equals(Access.class)) {
762                                     lo.add(access);
763                                 } else if (pc.equals(Locator.class)) {
764                                     lo.add(loadLocator(si, aafURL));
765                                 }
766                             }
767                             if (c.getParameterTypes().length != lo.size()) {
768                                 continue; // back to another Constructor
769                             } else {
770                                 aafcon = c.newInstance(lo.toArray());
771                             }
772                             break;
773                         }
774                     }
775                 }
776                 if (aafcon != null) {
777                     String mechid = logProp(access, Config.AAF_APPID, null);
778                     String pass = access.getProperty(Config.AAF_APPPASS, null);
779                     if (mechid != null && pass != null) {
780                         try {
781                             Method basicAuth = aafConClass.getMethod("basicAuth", String.class, String.class);
782                             basicAuth.invoke(aafcon, mechid, pass);
783                         } catch (NoSuchMethodException nsme) {
784                             access.log(Level.NONE, nsme);
785                             // it's ok, don't use
786                         }
787                     }
788                 }
789             }
790         } catch (Exception e) {
791             access.log(e, "AAF Connector could not be constructed with given Constructors.");
792         }
793
794         return aafcon;
795     }
796
797     public static Class<?> loadClass(Access access, String className) {
798         Class<?> cls=null;
799         try {
800             cls = access.classLoader().loadClass(className);
801         } catch (ClassNotFoundException cnfe) {
802             access.log(Level.NONE, cnfe);
803             try {
804                 cls = access.getClass().getClassLoader().loadClass(className);
805             } catch (ClassNotFoundException cnfe2) {
806                 access.log(Level.NONE, cnfe2);
807                 // just return null
808             }
809         }
810         return cls;
811     }
812
813     @SuppressWarnings("unchecked")
814     public static Locator<URI> loadLocator(SecurityInfoC<HttpURLConnection> si, final String _url) throws LocatorException {
815         Access access = si.access;
816         Locator<URI> locator = null;
817         if (_url==null) {
818             access.log(Level.INIT,"No URL passed to 'loadLocator'. Disabled");
819         } else {
820 //            String url = _url.replace("/AAF_NS.", "/%C%CID%AAF_NS.");
821 //            String root_ns = access.getProperty(Config.AAF_ROOT_NS, null);
822                 String url;
823             RegistrationPropHolder rph;
824             try {
825                          rph = new RegistrationPropHolder(access, 0);
826                          url = rph.replacements(_url, null, null);
827                 } catch (UnknownHostException | CadiException e1) {
828                         throw new LocatorException(e1);
829                 }
830             
831 //            if(url.indexOf('%')>=0) {
832 //                  String str = access.getProperty(Config.AAF_LOCATOR_CONTAINER_ID, null);
833 //                  if(str==null) {
834 //                      url = url.replace("%CID","");
835 //                  } else {
836 //                      url = url.replace("%CID",str+'.');
837 //                  }
838 //                  str = access.getProperty(Config.AAF_LOCATOR_CONTAINER, null);
839 //                  if(str==null) {
840 //                      url = url.replace("%C","");
841 //                  } else {
842 //                      url = url.replace("%C",str+'.');
843 //                  }
844 //      
845 //                  if (root_ns==null) {
846 //                      url = url.replace("%AAF_NS","");
847 //                  } else {
848 //                      url = url.replace("%AAF_NS",root_ns);
849 //                  }
850 //            }
851             String replacement;
852             int idxAAFLocateUrl;
853             if ((idxAAFLocateUrl=url.indexOf(AAF_LOCATE_URL_TAG))>0 && ((replacement=access.getProperty(AAF_LOCATE_URL, null))!=null)) {
854                 StringBuilder sb = new StringBuilder(replacement);
855                 if (!replacement.endsWith("/locate")) {
856                     sb.append("/locate");
857                 } 
858                 sb.append(url,idxAAFLocateUrl+AAF_LOCATE_URL_TAG.length(),url.length());
859                 url = sb.toString();
860             }
861             
862             try {
863                 Class<?> lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF);
864                 if (lcls==null) {
865                     throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator");
866                 }
867                 // First check for preloaded
868                 try {
869                     Method meth = lcls.getMethod("create",String.class);
870                     locator = (Locator<URI>)meth.invoke(null,url);
871                 } catch (Exception e) {
872                     access.log(Level.DEBUG, "(Not fatal) Cannot load by create(String)", e);
873                 }
874                 if (locator==null) {
875                     URI locatorURI = new URI(url);
876                     FixURIinfo fui = new FixURIinfo(locatorURI);
877                     Constructor<?> cnst = lcls.getConstructor(SecurityInfoC.class,URI.class);
878                     locator = (Locator<URI>)cnst.newInstance(new Object[] {si,locatorURI});
879                     int port = fui.getPort();
880                     String portS = port<0?"":(":"+port);
881                     
882                     access.log(Level.INFO, "AAFLocator enabled using " + locatorURI.getScheme() +"://"+fui.getHost() + portS);
883                 } else {
884                     access.log(Level.INFO, "AAFLocator enabled using preloaded " + locator.getClass().getSimpleName());
885                 }
886             } catch (InvocationTargetException e) {
887                 if (e.getTargetException() instanceof LocatorException) {
888                     throw (LocatorException)e.getTargetException();
889                 }
890                 access.log(Level.INIT,e.getTargetException().getMessage(),"AAFLocator for",url,"could not be created.",e);
891             } catch (Exception e) {
892                 access.log(Level.INIT,"AAFLocator for",url,"could not be created.",e);
893             }
894         }
895         return locator;
896     }
897
898     // Set by CSP, or is hostname.
899     public static String getDefaultRealm() {
900         return defaultRealm;
901     }
902
903     private static class Priori<T> implements Comparable<Priori<T>> {
904         public final T t;
905         public final int priority;
906         
907         public Priori(final T t, final int priority) {
908                 this.t = t;
909                 this.priority = priority;
910         }
911
912                 @Override
913                 public int compareTo(Priori<T> o) {
914                         if(priority==o.priority) {
915                                 return 0;
916                         } else if(priority<o.priority) {
917                                 return -1;
918                         } else {
919                                 return 1;
920                         }
921                 }
922             public static<T> void add(Access access, final String tag, List<Priori<T>> list) {
923                     String plugins = access.getProperty(tag, null);
924                     if(plugins!=null) {
925                         for(String tafs : Split.splitTrim(';', plugins)) {
926                                 String[] pluginArray = Split.splitTrim(',', tafs);
927                                 String clssn = null;
928                                 int priority = 60;
929                                 switch(pluginArray.length) {
930                                         case 0:
931                                                 break;
932                                         case 1:
933                                                 clssn = tafs;
934                                                 break;
935                                         default:
936                                                 clssn = pluginArray[0];
937                                                 try {
938                                                         priority = Integer.parseInt(pluginArray[1]);
939                                                 } catch (NumberFormatException nfe) {
940                                                         access.printf(Level.ERROR, "%s format is <classname>,priority[;...]\n",CADI_ADD_TAFS);
941                                                 }
942                                 }
943                                 
944                                 if(clssn!=null) {
945                                         Class<?> cls = loadClass(access, clssn);
946                                         if(cls!=null) {
947                                                 try {
948                                                                 @SuppressWarnings("unchecked")
949                                                                 Constructor<T> cnst = (Constructor<T>)cls.getConstructor(Access.class);
950                                                 try {
951                                                                         list.add(new Priori<T>(cnst.newInstance(access),priority));
952                                                                 } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
953                                                                         access.printf(Level.ERROR, "%s cannot be constructed with Access.\n",clssn);
954                                                                 }
955                                                         } catch (NoSuchMethodException | SecurityException e) {
956                                                                 access.printf(Level.ERROR, "%s needs a Constructor taking Access as sole param.\n",clssn);
957                                                         }
958                                         }
959                                 }
960                         }
961                     }
962                 }
963    }
964 }
965