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