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