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