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