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