42c38896a90f2cbf96208b96c66eeb4342523d42
[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
181         
182         public static final String GW_URL = "gw_url";
183         public static final String CM_URL = "cm_url";
184         public static final String CM_TRUSTED_CAS = "cm_trusted_cas";
185
186         public static final String PATHFILTER_URLPATTERN = "pathfilter_urlpattern";
187         public static final String PATHFILTER_STACK = "pathfilter_stack";
188         public static final String PATHFILTER_NS = "pathfilter_ns";
189         public static final String PATHFILTER_NOT_AUTHORIZED_MSG = "pathfilter_not_authorized_msg";
190
191         // This one should go unpublic
192         public static final String AAF_DEFAULT_REALM = "aaf_default_realm";
193         private static String defaultRealm="none";
194
195         public static final String AAF_DOMAIN_SUPPORT = "aaf_domain_support";
196         public static final String AAF_DOMAIN_SUPPORT_DEF = ".com:.org";
197
198         // OAUTH2
199         public static final String AAF_OAUTH2_TOKEN_URL = "aaf_oauth2_token_url";
200         public static final String AAF_OAUTH2_INTROSPECT_URL = "aaf_oauth2_introspect_url";
201         public static final String AAF_ALT_OAUTH2_TOKEN_URL = "aaf_alt_oauth2_token_url";
202         public static final String AAF_ALT_OAUTH2_INTROSPECT_URL = "aaf_alt_oauth2_introspect_url";
203         public static final String AAF_ALT_OAUTH2_DOMAIN = "aaf_alt_oauth2_domain"; 
204         public static final String AAF_ALT_CLIENT_ID = "aaf_alt_oauth2_client_id";
205         public static final String AAF_ALT_CLIENT_SECRET = "aaf_alt_oauth2_client_secret";
206         public static final String AAF_OAUTH2_HELLO_URL = "aaf_oauth2_hello_url";
207
208         
209         
210         public static void setDefaultRealm(Access access) throws CadiException {
211                 try {
212                         defaultRealm = logProp(access,Config.AAF_DEFAULT_REALM,
213                                 logProp(access,Config.BASIC_REALM,
214                                         logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName())
215                                         )
216                                 );
217                 } catch (UnknownHostException e) {
218                         //defaultRealm="none";
219                 }
220         }
221
222         public static HttpTaf configHttpTaf(Connector con, SecurityInfoC<HttpURLConnection> si, TrustChecker tc, CredVal up, Lur lur, Object ... additionalTafLurs) throws CadiException, LocatorException {
223                 Access access = si.access;
224                 /////////////////////////////////////////////////////
225                 // Setup AAFCon for any following
226                 /////////////////////////////////////////////////////
227                 Class<?> aafConClass = loadClass(access,CADI_AAF_CON_DEF);
228                 Object aafcon = null;
229                 if(con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) {
230                         aafcon = con;
231                 } else if(lur != null) {
232                         Field f = null;
233                         try {
234                                 f = lur.getClass().getField("aaf");
235                                 aafcon = f.get(lur);
236                         } catch (Exception nsfe) {
237                         }
238                 }
239         
240                 
241                 boolean hasDirectAAF = hasDirect("DirectAAFLur",additionalTafLurs);
242                 // IMPORTANT!  Don't attempt to load AAF Connector if there is no AAF URL
243                 String aafURL = access.getProperty(AAF_URL,null);
244                 if(!hasDirectAAF && aafcon==null && aafURL!=null) {
245                         aafcon = loadAAFConnector(si, aafURL);  
246                 }
247                 
248                 HttpTaf taf;
249                 // Setup Host, in case Network reports an unusable Hostname (i.e. VTiers, VPNs, etc)
250                 String hostname = logProp(access, HOSTNAME,null);
251                 if(hostname==null) {
252                         try {
253                                 hostname = InetAddress.getLocalHost().getHostName();
254                         } catch (UnknownHostException e1) {
255                                 throw new CadiException("Unable to determine Hostname",e1);
256                         }
257                 }
258                 
259                 access.log(Level.INIT, "Hostname set to",hostname);
260                 // Get appropriate TAFs
261                 ArrayList<HttpTaf> htlist = new ArrayList<>();
262
263                 /////////////////////////////////////////////////////
264                 // Add a Denial of Service TAF
265                 // Note: how IPs and IDs are added are up to service type.
266                 // They call "DenialOfServiceTaf.denyIP(String) or denyID(String)
267                 /////////////////////////////////////////////////////
268                 htlist.add(new DenialOfServiceTaf(access));
269
270                 /////////////////////////////////////////////////////
271                 // Configure Client Cert TAF
272                 /////////////////////////////////////////////////////
273                 X509Taf x509TAF = null;
274                 String truststore = logProp(access, CADI_TRUSTSTORE,null);
275                 if(truststore!=null) {
276                         String truststore_pwd = access.getProperty(CADI_TRUSTSTORE_PASSWORD,null);
277                         if(truststore_pwd!=null) {
278                                 if(truststore_pwd.startsWith(Symm.ENC)) {
279                                         try {
280                                                 truststore_pwd = access.decrypt(truststore_pwd,false);
281                                         } catch (IOException e) {
282                                                 throw new CadiException(CADI_TRUSTSTORE_PASSWORD + " cannot be decrypted",e);
283                                         }
284                                 }
285                                 try {
286                                         htlist.add(x509TAF=new X509Taf(access,lur));
287                                         access.log(Level.INIT,"Certificate Authorization enabled");
288                                 } catch (SecurityException e) {
289                                         access.log(Level.INIT,"AAFListedCertIdentity cannot be instantiated. Certificate Authorization is now disabled",e);
290                                 } catch (IllegalArgumentException e) {
291                                         access.log(Level.INIT,"AAFListedCertIdentity cannot be instantiated. Certificate Authorization is now disabled",e);
292                                 } catch (CertificateException e) {
293                                         access.log(Level.INIT,"Certificate Authorization failed, it is disabled",e);
294                                 } catch (NoSuchAlgorithmException e) {
295                                         access.log(Level.INIT,"Certificate Authorization failed, wrong Security Algorithm",e);
296                                 }
297                         }
298                 } else {
299                         access.log(Level.INIT,"Certificate Authorization not enabled");
300                 }
301                 
302                 /////////////////////////////////////////////////////
303                 // Configure Basic Auth (local content)
304                 /////////////////////////////////////////////////////
305                 boolean hasOAuthDirectTAF = hasDirect("DirectOAuthTAF", additionalTafLurs);
306                 String basic_realm = logProp(access, BASIC_REALM,null);
307                 String aafCleanup = logProp(access, AAF_USER_EXPIRES,AAF_USER_EXPIRES_DEF); // Default is 10 mins
308                 long userExp = Long.parseLong(aafCleanup);
309                 boolean basic_warn = "TRUE".equals(access.getProperty(BASIC_WARN,"FALSE"));
310
311                 if(!hasDirectAAF) {
312                         HttpTaf aaftaf=null;
313                         if(!hasOAuthDirectTAF) {
314                                 if(basic_realm!=null) {
315                                         @SuppressWarnings("unchecked")
316                                         Class<HttpTaf> obasicCls = (Class<HttpTaf>)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF);
317                                         if(obasicCls!=null) {
318                                                 try {
319                                                         String tokenurl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL, null);
320                                                         String introspecturl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL, null);
321                                                         if(tokenurl==null || introspecturl==null) {
322                                                                 access.log(Level.INIT,"Both tokenurl and introspecturl are required. Oauth Authorization is disabled.");
323                                                         }
324                                                         Constructor<HttpTaf> obasicConst = obasicCls.getConstructor(PropAccess.class,String.class, String.class, String.class);
325                                                         htlist.add(obasicConst.newInstance(access,basic_realm,tokenurl,introspecturl));
326                                                         access.log(Level.INIT,"Oauth supported Basic Authorization is enabled");
327                                                 } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
328                                                 }
329                                         } else if(up!=null) {
330                                                 access.log(Level.INIT,"Basic Authorization is enabled using realm",basic_realm);
331                                                 // Allow warning about insecure channel to be turned off
332                                                 if(!basic_warn)access.log(Level.INIT,"WARNING! The basic_warn 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, basic_realm, userExp, basic_warn);
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 basic_realm=<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,basic_warn,lur);
369                                                                         } else {
370                                                                                 cstr = aafTafClass.getConstructor(Connector.class,boolean.class);
371                                                                                 if(cstr!=null) {
372                                                                                         aaftaf = (HttpTaf)cstr.newInstance(aafcon,basic_warn);
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 oauth_token_url = 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                                 }
403                                 if(additionalTafLurs!=null && additionalTafLurs.length>0 && (oadtClss!=null && additionalTafLurs[0].getClass().isAssignableFrom(oadtClss))) {
404                                         htlist.add((HttpTaf)additionalTafLurs[0]);
405                                         String array[] = new String[additionalTafLurs.length-1];
406                                         if(array.length>0) {
407                                                 System.arraycopy(htlist, 1, array, 0, array.length);
408                                         }
409                                         additionalTafLurs = array;
410                                         access.log(Level.INIT,"OAuth2 Direct is enabled");
411                                 } else if(oauth_token_url!=null) {
412                                         String oauth_introspect_url = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL,null);
413                                         @SuppressWarnings("unchecked")
414                                         Class<HttpTaf> oaTCls = (Class<HttpTaf>)loadClass(access,OAUTH_HTTP_TAF);
415                                         if(oaTCls!=null) {
416                                                 Class<?> oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR);
417                                                 if(oaTTmgrCls!=null) {
418                                                         try {
419                                                                 Method oaTTmgrGI = oaTTmgrCls.getMethod("getInstance",PropAccess.class,String.class,String.class);
420                                                                 Object oaTTmgr = oaTTmgrGI.invoke(null /*this is static method*/,access,oauth_token_url,oauth_introspect_url);
421                                                                 Constructor<HttpTaf> oaTConst = oaTCls.getConstructor(Access.class,oaTTmgrCls);
422                                                                 htlist.add(oaTConst.newInstance(access,oaTTmgr));
423                                                                 access.log(Level.INIT,"OAuth2 TAF is enabled");
424                                                         } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
425                                                                 access.log(Level.INIT,"OAuth2HttpTaf cannot be instantiated. OAuth2 is disabled",e);
426                                                         }
427                                                 }
428                                         }
429                                 } else {
430                                         access.log(Level.INIT,"OAuth TAF is not configured");
431                                 }
432                         }
433         
434                         /////////////////////////////////////////////////////
435                         // Adding BasicAuth (AAF) last, after other primary Cookie Based
436                         // Needs to be before Cert... see below
437                         /////////////////////////////////////////////////////
438                         if(aaftaf!=null) {
439                                 htlist.add(aaftaf);
440                         }
441                 }       
442
443                 /////////////////////////////////////////////////////
444                 // Any Additional Lurs passed in Constructor
445                 /////////////////////////////////////////////////////
446                 if(additionalTafLurs!=null) {
447                         for(Object additional : additionalTafLurs) {
448                                 if(additional instanceof BasicHttpTaf) {
449                                         BasicHttpTaf ht = (BasicHttpTaf)additional;
450                                         for(Object cv : additionalTafLurs) {
451                                                 if(cv instanceof CredValDomain) {
452                                                         ht.add((CredValDomain)cv);
453                                                         access.printf(Level.INIT,"%s Authentication is enabled",cv);
454                                                 }
455                                         }
456                                         htlist.add(ht);
457                                 } else if(additional instanceof HttpTaf) {
458                                         HttpTaf ht = (HttpTaf)additional;
459                                         htlist.add(ht);
460                                         access.printf(Level.INIT,"%s Authentication is enabled",additional.getClass().getSimpleName());
461                                 } else if(hasOAuthDirectTAF) {
462                                         Class<?> daupCls;
463                                         try {
464                                                 daupCls = Class.forName("org.onap.aaf.auth.direct.DirectAAFUserPass");
465                                         } catch (ClassNotFoundException e) {
466                                                 daupCls = null;
467                                         }
468                                         if(daupCls != null && additional.getClass().isAssignableFrom(daupCls)) {
469                                                 htlist.add(new BasicHttpTaf(access, (CredVal)additional , basic_realm, userExp, basic_warn));
470                                                 access.printf(Level.INIT,"Direct BasicAuth Authentication is enabled",additional.getClass().getSimpleName());
471                                         }
472                                 }
473                         }
474                 }
475                 
476                 // Add BasicAuth, if any, to x509Taf
477                 if(x509TAF!=null) {
478                         for( HttpTaf ht : htlist) {
479                                 if(ht instanceof BasicHttpTaf) {
480                                         x509TAF.add((BasicHttpTaf)ht);
481                                 }
482                         }
483                 }
484                 /////////////////////////////////////////////////////
485                 // Create EpiTaf from configured TAFs
486                 /////////////////////////////////////////////////////
487                 if(htlist.size()==1) {
488                         // just return the one
489                         taf = htlist.get(0);
490                 } else {
491                         HttpTaf[] htarray = new HttpTaf[htlist.size()];
492                         htlist.toArray(htarray);
493                         Locator<URI> locator = loadLocator(si, logProp(access, AAF_LOCATE_URL, null));
494                         
495                         taf = new HttpEpiTaf(access,locator, tc, htarray); // ok to pass locator == null
496                         String level = logProp(access, CADI_LOGLEVEL, null);
497                         if(level!=null) {
498                                 access.setLogLevel(Level.valueOf(level));
499                         }
500                 }
501                 
502                 return taf;
503         }
504         
505         public static String logProp(Access access,String tag, String def) {
506                 String rv = access.getProperty(tag, def);
507                 if(rv == null) {
508                         access.log(Level.INIT,tag,"is not explicitly set");
509                 } else {
510                         access.log(Level.INIT,tag,"is set to",rv);
511                 }
512                 return rv;
513         }
514         
515         public static Lur configLur(SecurityInfoC<HttpURLConnection> si, Connector con, Object ... additionalTafLurs) throws CadiException {
516                 Access access = si.access;
517                 List<Lur> lurs = new ArrayList<>();
518                 
519                 /////////////////////////////////////////////////////
520                 // Configure a Local Property Based RBAC/LUR
521                 /////////////////////////////////////////////////////
522                 try {
523                         String users = access.getProperty(USERS,null);
524                         String groups = access.getProperty(GROUPS,null);
525
526                         if(groups!=null || users!=null) {
527                                 LocalLur ll;
528                                 lurs.add(ll = new LocalLur(access, users, groups)); // note b64==null is ok.. just means no encryption.
529                                 
530                                 String writeto = access.getProperty(WRITE_TO,null);
531                                 if(writeto!=null) {
532                                         String msg = UsersDump.updateUsers(writeto, ll);
533                                         if(msg!=null) access.log(Level.INIT,"ERROR! Error Updating ",writeto,"with roles and users:",msg);
534                                 }
535                         }
536                 } catch (IOException e) {
537                         throw new CadiException(e);
538                 }
539
540                 /////////////////////////////////////////////////////
541                 // Configure the OAuth Lur (if any)
542                 /////////////////////////////////////////////////////
543                 String token_url = logProp(access,AAF_OAUTH2_TOKEN_URL, null);
544                 String introspect_url = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null);
545                 if(token_url!=null && introspect_url !=null) {
546                         try {
547                                 Class<?> olurCls = loadClass(access, CADI_OLUR_CLASS_DEF);
548                                 if(olurCls!=null) {
549                                         Constructor<?> olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class);
550                                         Lur olur = (Lur)olurCnst.newInstance(access,token_url,introspect_url);
551                                         lurs.add(olur);
552                                         access.log(Level.INIT, "OAuth2 LUR enabled");
553                                 } else {
554                                         access.log(Level.INIT,"AAF/OAuth LUR plugin is not available.");
555                                 }
556                         } catch (NoSuchMethodException| SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
557                                 String msg = e.getMessage();
558                                 if(msg==null && e.getCause()!=null) {
559                                         msg = e.getCause().getMessage();
560                                 }
561                                 access.log(Level.INIT,"AAF/OAuth LUR is not instantiated.",msg);
562                         } 
563                 } else {
564                         access.log(Level.INIT, "OAuth2 Lur disabled");
565                 }
566
567                 if(con!=null) { // try to reutilize connector
568                         lurs.add(con.newLur());
569                 } else { 
570                         /////////////////////////////////////////////////////
571                         // Configure the AAF Lur (if any)
572                         /////////////////////////////////////////////////////
573                         String aafURL = logProp(access,AAF_URL,null); // Trigger Property
574                         String aaf_env = access.getProperty(AAF_ENV,null);
575                         if(aaf_env == null && aafURL!=null && access instanceof PropAccess) { // set AAF_ENV from AAF_URL
576                                 int ec = aafURL.indexOf("envContext=");
577                                 if(ec>0) {
578                                         ec += 11; // length of envContext=
579                                         int slash = aafURL.indexOf('/', ec);
580                                         if(slash>0) {
581                                                 aaf_env = aafURL.substring(ec, slash);
582                                                 ((PropAccess)access).setProperty(AAF_ENV, aaf_env);
583                                                 access.printf(Level.INIT, "Setting aaf_env to %s from aaf_url value",aaf_env);
584                                         }
585                                 }
586                         }
587
588                         // Don't configure AAF if it is using DirectAccess
589                         if(!hasDirect("DirectAAFLur",additionalTafLurs)) {
590                                 if(aafURL==null) {
591                                         access.log(Level.INIT,"No AAF LUR properties, AAF will not be loaded");
592                                 } else {// There's an AAF_URL... try to configure an AAF
593                                         String aafLurClassStr = logProp(access,AAF_LUR_CLASS,AAF_V2_0_AAF_LUR_PERM);
594                                         ////////////AAF Lur 2.0 /////////////
595                                         if(aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { 
596                                                 try {
597                                                         Object aafcon = loadAAFConnector(si, aafURL);
598                                                         if(aafcon==null) {
599                                                                 access.log(Level.INIT,"AAF LUR class,",aafLurClassStr,"cannot be constructed without valid AAFCon object.");
600                                                         } else {
601                                                                 Class<?> aafAbsAAFCon = loadClass(access, AAF_V2_0_AAFCON);
602                                                                 if(aafAbsAAFCon!=null) {
603                                                                         Method mNewLur = aafAbsAAFCon.getMethod("newLur");
604                                                                         Object aaflur = mNewLur.invoke(aafcon);
605                                 
606                                                                         if(aaflur==null) {
607                                                                                 access.log(Level.INIT,"ERROR! AAF LUR Failed construction.  NOT Configured");
608                                                                         } else {
609                                                                                 access.log(Level.INIT,"AAF LUR Configured to ",aafURL);
610                                                                                 lurs.add((Lur)aaflur);
611                                                                                 String debugIDs = logProp(access,Config.AAF_DEBUG_IDS, null);
612                                                                                 if(debugIDs !=null && aaflur instanceof CachingLur) {
613                                                                                         ((CachingLur<?>)aaflur).setDebug(debugIDs);
614                                                                                 }
615                                                                         }
616                                                                 }
617                                                         }
618                                                 } catch (Exception e) {
619                                                         access.log(e,"AAF LUR class,",aafLurClassStr,"could not be constructed with given Constructors.");
620                                                 }
621                                         } 
622                                 }
623                         }
624                 }
625
626                 /////////////////////////////////////////////////////
627                 // Any Additional passed in Constructor
628                 /////////////////////////////////////////////////////
629                 if(additionalTafLurs!=null) {
630                         for(Object additional : additionalTafLurs) {
631                                 if(additional instanceof Lur) {
632                                         lurs.add((Lur)additional);
633                                         access.log(Level.INIT, additional);
634                                 }
635                         }
636                 }
637
638                 /////////////////////////////////////////////////////
639                 // Return a Lur based on how many there are... 
640                 /////////////////////////////////////////////////////
641                 switch(lurs.size()) {
642                         case 0: 
643                                 access.log(Level.INIT,"WARNING! No CADI LURs configured");
644                                 // Return a NULL Lur that does nothing.
645                                 return new NullLur();
646                         case 1:
647                                 return lurs.get(0); // Only one, just return it, save processing
648                         default:
649                                 // Multiple Lurs, use EpiLUR to handle
650                                 Lur[] la = new Lur[lurs.size()];
651                                 lurs.toArray(la);
652                                 return new EpiLur(la);
653                 }
654         }
655         
656         private static boolean hasDirect(String simpleClassName, Object[] additionalTafLurs) {
657                 if(additionalTafLurs!=null) {
658                         for(Object tf : additionalTafLurs) {
659                                 if(tf.getClass().getSimpleName().equals(simpleClassName)) {
660                                         return true;
661                                 }
662                         }
663                 }
664                 return false;
665         }
666
667         private static final String AAF_V2_0_AAF_CON_HTTP = "org.onap.aaf.cadi.aaf.v2_0.AAFConHttp";
668
669         public static Object loadAAFConnector(SecurityInfoC<HttpURLConnection> si, String aafURL) {
670                 Access access = si.access;
671                 Object aafcon = null;
672                 Class<?> aafConClass = null;
673
674                 try {
675                         if (aafURL!=null) {
676                                 String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, AAF_V2_0_AAF_CON_HTTP);
677                                 if (AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) {
678                                         aafConClass = loadClass(access, AAF_V2_0_AAF_CON_HTTP);
679                                         if (aafConClass != null) {
680                                                 for (Constructor<?> c : aafConClass.getConstructors()) {
681                                                         List<Object> lo = new ArrayList<>();
682                                                         for (Class<?> pc : c.getParameterTypes()) {
683                                                                 if (pc.equals(Access.class)) {
684                                                                         lo.add(access);
685                                                                 } else if (pc.equals(Locator.class)) {
686                                                                         lo.add(loadLocator(si, aafURL));
687                                                                 } else {
688                                                                         continue;
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                                                         // it's ok, don't use
709                                                 }
710                                         }
711                                 }
712                         }
713                 } catch (Exception e) {
714                         access.log(e, "AAF Connector could not be constructed with given Constructors.");
715                 }
716
717                 return aafcon;
718         }
719
720         public static Class<?> loadClass(Access access, String className) {
721                 Class<?> cls=null;
722                 try {
723                         cls = access.classLoader().loadClass(className);
724                 } catch (ClassNotFoundException cnfe) {
725                         try {
726                                 cls = access.getClass().getClassLoader().loadClass(className);
727                         } catch (ClassNotFoundException cnfe2) {
728                                 // just return null
729                         }
730                 }
731                 return cls;
732         }
733
734
735         @SuppressWarnings("unchecked")
736         public static Locator<URI> loadLocator(SecurityInfoC<HttpURLConnection> si, final String _url) throws LocatorException {
737                 Access access = si.access;
738                 Locator<URI> locator = null;
739                 if(_url==null) {
740                         access.log(Level.INIT,"No URL passed to 'loadLocator'. Disabled");
741                 } else {
742                         String url = _url, replacement;
743                         int idxAAF_LOCATE_URL;
744                         if((idxAAF_LOCATE_URL=_url.indexOf(AAF_LOCATE_URL_TAG))>0 && ((replacement=access.getProperty(AAF_LOCATE_URL, null))!=null)) {
745                                 StringBuilder sb = new StringBuilder(replacement);
746                                 if(!replacement.endsWith("/locate")) {
747                                         sb.append("/locate");
748                                 } 
749                                 sb.append(_url,idxAAF_LOCATE_URL+AAF_LOCATE_URL_TAG.length(),_url.length());
750                                 url = sb.toString();
751                         }
752         
753                         try {
754                                 Class<?> lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF);
755                                 if(lcls==null) {
756                                         throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator");
757                                 }
758                                 // First check for preloaded
759                                 try {
760                                         Method meth = lcls.getMethod("create",String.class);
761                                         locator = (Locator<URI>)meth.invoke(null,url);
762                                 } catch (Exception e) {
763                                         locator = null;
764                                 }
765                                 if(locator==null) {
766                                         URI locatorURI = new URI(url);
767                                         Constructor<?> cnst = lcls.getConstructor(new Class[] {SecurityInfoC.class,URI.class});
768                                         locator = (Locator<URI>)cnst.newInstance(new Object[] {si,locatorURI});
769                                         int port = locatorURI.getPort();
770                                         String portS = port<0?"":(":"+locatorURI.getPort());
771                                         
772                                         access.log(Level.INFO, "AAFLocator enabled using " + locatorURI.getScheme() +"://"+locatorURI.getHost() + portS);
773                                 } else {
774                                         access.log(Level.INFO, "AAFLocator enabled using preloaded " + locator.getClass().getSimpleName());
775                                 }
776                         } catch (InvocationTargetException e) {
777                                 if(e.getTargetException() instanceof LocatorException) {
778                                         throw (LocatorException)e.getTargetException();
779                                 }
780                                 access.log(Level.INIT,e.getTargetException().getMessage(),"AAFLocator for",url,"could not be created.",e);
781                         } catch (Exception e) {
782                                 access.log(Level.INIT,"AAFLocator for",url,"could not be created.",e);
783                         }
784                 }
785                 return locator;
786         }
787
788         // Set by CSP, or is hostname.
789         public static String getDefaultRealm() {
790                 return defaultRealm;
791         }
792
793 }
794