Collection syntax change because of Sonar
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / sso / AAFSSO.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.sso;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.PrintStream;
30 import java.lang.reflect.InvocationTargetException;
31 import java.lang.reflect.Method;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.Map.Entry;
35 import java.util.Properties;
36
37 import org.onap.aaf.cadi.Access.Level;
38 import org.onap.aaf.cadi.CadiException;
39 import org.onap.aaf.cadi.PropAccess;
40 import org.onap.aaf.cadi.Symm;
41 import org.onap.aaf.cadi.config.Config;
42 import org.onap.aaf.cadi.util.MyConsole;
43 import org.onap.aaf.cadi.util.SubStandardConsole;
44 import org.onap.aaf.cadi.util.TheConsole;
45
46 public class AAFSSO {
47         public static final MyConsole  cons = TheConsole.implemented() ? new TheConsole() : new SubStandardConsole();
48 //      private static final int EIGHT_HOURS = 8 * 60 * 60 * 1000;
49
50         private Properties diskprops;
51         private boolean touchDiskprops;
52         private File dot_aaf = null;
53         private File sso = null; // instantiated, if ever, with diskprops
54
55         boolean removeSSO = false;
56         boolean loginOnly = false;
57         boolean doExit = true;
58         private PropAccess access;
59         private StringBuilder err;
60         private String user;
61         private String encrypted_pass;
62         private boolean use_X509;
63
64         private PrintStream os;
65
66         private Method close;
67         private final PrintStream stdOutOrig;
68         private final PrintStream stdErrOrig;
69         private boolean ok;
70
71         public AAFSSO(String[] args) throws IOException, CadiException {
72                 this(args,new Properties());
73         }
74         
75         public AAFSSO(String[] args, ProcessArgs pa) throws IOException, CadiException {
76                 this(args,pa.process(args, new Properties()));
77         }
78
79         public AAFSSO(String[] args, Properties dp) throws IOException, CadiException {
80                 stdOutOrig = System.out;
81                 stdErrOrig = System.err;
82                 ok = true;
83                 List<String> nargs = parseArgs(args);
84                 diskprops = dp;
85                 touchDiskprops = false;
86
87                 dot_aaf = new File(System.getProperty("user.home") + "/.aaf");
88                 if (!dot_aaf.exists()) {
89                         dot_aaf.mkdirs();
90                 }
91                 File f = new File(dot_aaf, "sso.out");
92                 os = new PrintStream(new FileOutputStream(f, true));
93                 //System.setOut(os);
94                 System.setErr(os);
95
96                 sso = new File(dot_aaf, "sso.props");
97                 if(sso.exists()) {
98                         InputStream propStream = new FileInputStream(sso);
99                         try {
100                                 diskprops.load(propStream);
101                         } finally {
102                                 propStream.close();
103                         }
104                 }
105                 
106                 File dot_aaf_kf = new File(dot_aaf, "keyfile");
107
108                 if (removeSSO) {
109                         if (dot_aaf_kf.exists()) {
110                                 dot_aaf_kf.setWritable(true, true);
111                                 dot_aaf_kf.delete();
112                         }
113                         if (sso.exists()) {
114                                 Properties temp = new Properties();
115                                 // Keep only these
116                                 for(Entry<Object, Object> es : diskprops.entrySet()) {
117                                         if(Config.CADI_LATITUDE.equals(es.getKey()) ||
118                                            Config.CADI_LONGITUDE.equals(es.getKey()) ||
119                                            Config.AAF_DEFAULT_REALM.equals(es.getKey())) {
120                                                  temp.setProperty(es.getKey().toString(), es.getValue().toString());
121                                         }
122                                 }
123                                 diskprops = temp;
124                                 touchDiskprops = true;
125                         }
126                         String[] naargs = new String[nargs.size()];
127                         nargs.toArray(naargs);
128                         access = new PropAccess(os, naargs);
129                         ok = false;
130                         setLogDefault();
131                         System.out.println("AAF SSO information removed");
132                 } else {
133                         //      Config.setDefaultRealm(access);
134         
135                         if (!dot_aaf_kf.exists()) {
136                                 FileOutputStream fos = new FileOutputStream(dot_aaf_kf);
137                                 try {
138                                         fos.write(Symm.keygen());
139                                         setReadonly(dot_aaf_kf);
140                                 } finally {
141                                         fos.close();
142                                 }
143                         }
144
145                         for(Entry<Object, Object> es : diskprops.entrySet()) {
146                                 nargs.add(es.getKey().toString() + '=' + es.getValue().toString());
147                         }
148                         String[] naargs = new String[nargs.size()];
149                         nargs.toArray(naargs);
150                         access = new PropAccess(os, naargs);
151                         
152                         if(loginOnly) {
153                                 for(String tag : new String[] {Config.AAF_APPID, Config.AAF_APPPASS, 
154                                                 Config.CADI_ALIAS, Config.CADI_KEYSTORE,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) {
155                                         access.getProperties().remove(tag);
156                                         diskprops.remove(tag);
157                                 }
158                                 touchDiskprops=true;
159 // TODO Do we want to require reset of Passwords at least every Eight Hours.
160 //                      } else if (sso.lastModified() > (System.currentTimeMillis() - EIGHT_HOURS)) {
161 //                              for(String tag : new String[] {Config.AAF_APPPASS,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) {
162 //                                      access.getProperties().remove(tag);
163 //                                      diskprops.remove(tag);
164 //                              }
165 //                              touchDiskprops=true;
166                         }
167         
168                         String keyfile = access.getProperty(Config.CADI_KEYFILE); // in case its CertificateMan props
169                         if (keyfile == null) {
170                                 access.setProperty(Config.CADI_KEYFILE, dot_aaf_kf.getAbsolutePath());
171                                 addProp(Config.CADI_KEYFILE,dot_aaf_kf.getAbsolutePath());
172                         }
173         
174         
175                         String alias, appID;
176                         alias = access.getProperty(Config.CADI_ALIAS);
177                         if(alias==null) {
178                                 appID = access.getProperty(Config.AAF_APPID);
179                                 user=appID;
180                         } else {
181                                 user=alias;
182                                 appID=null;
183                         }
184                         
185                         if(appID!=null && access.getProperty(Config.AAF_APPPASS)==null) {
186                                 char[] password = cons.readPassword("Password for %s: ", appID);
187                                 String app_pass = access.encrypt(new String(password));
188                                 access.setProperty(Config.AAF_APPPASS,app_pass);
189                                 diskprops.setProperty(Config.AAF_APPPASS, app_pass);
190                         }
191                         
192                         String keystore=access.getProperty(Config.CADI_KEYSTORE);
193                         String keystore_pass=access.getProperty(Config.CADI_KEYSTORE_PASSWORD);
194                         
195                         if(user==null || (alias!=null && (keystore==null || keystore_pass==null))) {
196                                 String select = null;
197                                 String name;
198                                 for (File tsf : dot_aaf.listFiles()) {
199                                         name = tsf.getName();
200                                         if (!name.contains("trust") && (name.endsWith(".jks") || name.endsWith(".p12"))) {
201                                                 setLogDefault();
202                                                 select = cons.readLine("Use %s for Identity? (y/n): ",tsf.getName());
203                                                 if("y".equalsIgnoreCase(select)) {
204                                                         keystore = tsf.getCanonicalPath();
205                                                         access.setProperty(Config.CADI_KEYSTORE, keystore);
206                                                         addProp(Config.CADI_KEYSTORE, keystore);
207                                                         char[] password = cons.readPassword("Keystore Password: ");
208                                                         encrypted_pass= access.encrypt(new String(password));
209                                                         access.setProperty(Config.CADI_KEYSTORE_PASSWORD, encrypted_pass);
210                                                         addProp(Config.CADI_KEYSTORE_PASSWORD, encrypted_pass);
211                                                         
212                                                         // TODO READ Aliases out of Keystore?
213                                                         user = alias = cons.readLine("Keystore alias: ");
214                                                         access.setProperty(Config.CADI_ALIAS, user);
215                                                         addProp(Config.CADI_ALIAS, user);
216                                                         break;
217                                                 }
218                                         }
219                                 }
220                                 if(alias==null) {
221                                         user = appID = cons.readLine(Config.AAF_APPID + ": ");
222                                         access.setProperty(Config.AAF_APPID, appID);
223                                         addProp(Config.AAF_APPID, appID);
224                                         char[] password = cons.readPassword(Config.AAF_APPPASS + ": ");
225                                         encrypted_pass= access.encrypt(new String(password));
226                                         access.setProperty(Config.AAF_APPPASS, encrypted_pass);
227                                         addProp(Config.AAF_APPPASS, encrypted_pass);
228                                 }
229                         } else {
230                                 encrypted_pass = access.getProperty(Config.CADI_KEYSTORE_PASSWORD);
231                                 if(encrypted_pass == null) {
232                                         keystore_pass = null;
233                                         encrypted_pass = access.getProperty(Config.AAF_APPPASS);
234                                 } else {
235                                         keystore_pass = encrypted_pass;
236                                 }
237                         }
238                         
239         
240                         if (alias!=null) {
241                                 use_X509 = true;
242                         } else {
243                                 use_X509 = false;
244                                 Symm decryptor = Symm.obtain(dot_aaf_kf);
245                                 if (user == null) {
246                                         if (sso.exists()) {
247                                                 String cm_url = access.getProperty(Config.CM_URL); // SSO might overwrite...
248                                                 FileInputStream fos = new FileInputStream(sso);
249                                                 try {
250                                                         access.load(fos);
251                                                         user = access.getProperty(Config.AAF_APPID);
252                                                         encrypted_pass = access.getProperty(Config.AAF_APPPASS);
253                                                         // decrypt with .aaf, and re-encrypt with regular Keyfile
254                                                         access.setProperty(Config.AAF_APPPASS,
255                                                                         access.encrypt(decryptor.depass(encrypted_pass)));
256                                                         if (cm_url != null) { //Command line CM_URL Overwrites ssofile.
257                                                                 access.setProperty(Config.CM_URL, cm_url);
258                                                         }
259                                                 } finally {
260                                                         fos.close();
261                                                 }
262                                         } else {
263                                                 diskprops = new Properties();
264                                                 String realm = Config.getDefaultRealm();
265                                                 // Turn on Console Sysout
266                                                 System.setOut(System.out);
267                                                 user = cons.readLine("aaf_id(%s@%s): ", System.getProperty("user.name"), realm);
268                                                 if (user == null) {
269                                                         user = System.getProperty("user.name") + '@' + realm;
270                                                 } else if (user.length() == 0) { //
271                                                         user = System.getProperty("user.name") + '@' + realm;
272                                                 } else if ((user.indexOf('@') < 0) && (realm != null)) {
273                                                         user = user + '@' + realm;
274                                                 }
275                                                 access.setProperty(Config.AAF_APPID, user);
276                                                 diskprops.setProperty(Config.AAF_APPID, user);
277                                                 encrypted_pass = new String(cons.readPassword("aaf_password: "));
278                                                 System.setOut(os);
279                                                 encrypted_pass = Symm.ENC + decryptor.enpass(encrypted_pass);
280                                                 access.setProperty(Config.AAF_APPPASS, encrypted_pass);
281                                                 diskprops.setProperty(Config.AAF_APPPASS, encrypted_pass);
282                                                 diskprops.setProperty(Config.CADI_KEYFILE, access.getProperty(Config.CADI_KEYFILE));
283                                         }
284                                 }
285                         }
286                         if (user == null) {
287                                 err = new StringBuilder("Add -D" + Config.AAF_APPID + "=<id> ");
288                         }
289         
290                         if (encrypted_pass == null && alias == null) {
291                                 if (err == null) {
292                                         err = new StringBuilder();
293                                 } else {
294                                         err.append("and ");
295                                 }
296                                 err.append("-D" + Config.AAF_APPPASS + "=<passwd> ");
297                         }
298                         
299                         String locateUrl = access.getProperty(Config.AAF_LOCATE_URL);
300                         if(locateUrl==null) {
301                                 locateUrl=AAFSSO.cons.readLine("AAF Locator URL=https://");
302                                 if(locateUrl==null || locateUrl.length()==0) {
303                                         err = new StringBuilder(Config.AAF_LOCATE_URL);
304                                         err.append(" is required.");
305                                         ok = false;
306                                         return;
307                                 } else {
308                                         locateUrl="https://"+locateUrl;
309                                 }
310                                 access.setProperty(Config.AAF_LOCATE_URL, locateUrl);
311                                 addProp(Config.AAF_LOCATE_URL, locateUrl);
312                         }
313                         
314                         String aafUrl = "https://AAF_LOCATE_URL/AAF_NS.service:2.0";
315                         access.setProperty(Config.AAF_URL, aafUrl);
316                         access.setProperty(Config.CM_URL, "https://AAF_LOCATE_URL/AAF_NS.cm:2.0");
317                         String cadiLatitude = access.getProperty(Config.CADI_LATITUDE);
318                         if(cadiLatitude==null) {
319                                 System.out.println("# If you do not know your Global Coordinates, we suggest bing.com/maps");
320                                 cadiLatitude=AAFSSO.cons.readLine("cadi_latitude[0.000]=");
321                                 if(cadiLatitude==null || cadiLatitude.isEmpty()) {
322                                         cadiLatitude="0.000";
323                                 }
324                                 access.setProperty(Config.CADI_LATITUDE, cadiLatitude);
325                                 addProp(Config.CADI_LATITUDE, cadiLatitude);
326                                 
327                         }
328                         String cadiLongitude = access.getProperty(Config.CADI_LONGITUDE);
329                         if(cadiLongitude==null) {
330                                 cadiLongitude=AAFSSO.cons.readLine("cadi_longitude[0.000]=");
331                                 if(cadiLongitude==null || cadiLongitude.isEmpty()) {
332                                         cadiLongitude="0.000";
333                                 }
334                                 access.setProperty(Config.CADI_LONGITUDE, cadiLongitude);
335                                 addProp(Config.CADI_LONGITUDE, cadiLongitude);
336                         }
337         
338                         String cadi_truststore = access.getProperty(Config.CADI_TRUSTSTORE);
339                         if(cadi_truststore==null) {
340                                 String name; 
341                                 String select;
342                                 for (File tsf : dot_aaf.listFiles()) {
343                                         name = tsf.getName();
344                                         if (name.contains("trust") && 
345                                                         (name.endsWith(".jks") || name.endsWith(".p12"))) {
346                                                 select = cons.readLine("Use %s for TrustStore? (y/n):",tsf.getName());
347                                                 if("y".equalsIgnoreCase(select)) {
348                                                         cadi_truststore=tsf.getCanonicalPath();
349                                                         access.setProperty(Config.CADI_TRUSTSTORE, cadi_truststore);
350                                                         addProp(Config.CADI_TRUSTSTORE, cadi_truststore);
351                                                         break;
352                                                 }
353                                         }
354                                 }
355                         }
356                         if(cadi_truststore!=null) {
357                                 if(cadi_truststore.indexOf(File.separatorChar)<0) {
358                                         cadi_truststore=dot_aaf.getPath()+File.separator+cadi_truststore;
359                                 }
360                                 String cadi_truststore_password = access.getProperty(Config.CADI_TRUSTSTORE_PASSWORD);
361                                 if(cadi_truststore_password==null) {
362                                         cadi_truststore_password=AAFSSO.cons.readLine("cadi_truststore_password[%s]=","changeit");
363                                         cadi_truststore_password = access.encrypt(cadi_truststore_password);
364                                         access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password);
365                                         addProp(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password);
366                                 }
367                         }
368                         ok = err==null;
369                 }
370                 writeFiles();
371         }
372
373         public void setLogDefault() {
374                 this.setLogDefault(PropAccess.DEFAULT);
375                 System.setOut(stdOutOrig);
376         }
377
378         public void setStdErrDefault() {
379                 access.setLogLevel(PropAccess.DEFAULT);
380                 System.setErr(stdErrOrig);
381         }
382
383         public void setLogDefault(Level level) {
384                 if(access!=null) {
385                         access.setLogLevel(level);
386                 }
387                 System.setOut(stdOutOrig);
388         }
389
390         public boolean loginOnly() {
391                 return loginOnly;
392         }
393
394         public void addProp(String key, String value) {
395                 if(key==null || value==null) {
396                         return;
397                 }
398                 touchDiskprops=true;
399                 diskprops.setProperty(key, value);
400         }
401
402         public void writeFiles() throws IOException {
403                 if(touchDiskprops) {
404                         // Store Creds, if they work
405                         if (diskprops != null) {
406                                 if (!dot_aaf.exists()) {
407                                         dot_aaf.mkdirs();
408                                 }
409                                 FileOutputStream fos = new FileOutputStream(sso);
410                                 try {
411                                         diskprops.store(fos, "AAF Single Signon");
412                                 } finally {
413                                         fos.close();
414                                         setReadonly(sso);
415                                 }
416                         }
417                         if (sso != null) {
418                                 setReadonly(sso);
419                                 sso.setWritable(true, true);
420                         }
421                 }
422         }
423
424         public PropAccess access() {
425                 return access;
426         }
427
428         public StringBuilder err() {
429                 return err;
430         }
431
432         public String user() {
433                 return user;
434         }
435
436         public String enc_pass() {
437                 return encrypted_pass;
438         }
439
440         public boolean useX509() {
441                 return use_X509;
442         }
443
444         public void close() {
445                 if (close != null) {
446                         try {
447                                 close.invoke(null);
448                         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
449                                 // nothing to do here.
450                         }
451                         close = null;
452                 }
453         }
454
455         private List<String> parseArgs(String[] args)
456         {
457                 List<String> larg = new ArrayList<>(args.length);
458
459                 // Cover for bash's need to escape *.. (\\*)
460                 // also, remove SSO if required
461                 for (int i = 0; i < args.length; ++i) {
462                         if ("\\*".equals(args[i])) {
463                                 args[i] = "*";
464                         }
465
466                         if ("-logout".equalsIgnoreCase(args[i])) {
467                                 removeSSO = true;
468                         } else if ("-login".equalsIgnoreCase(args[i])) {
469                                 loginOnly = true;
470                         } else if ("-noexit".equalsIgnoreCase(args[i])) {
471                                 doExit = false;
472                         } else {
473                                 larg.add(args[i]);
474                         }
475                 }
476                 return larg;
477         }
478         
479         private void setReadonly(File file) {
480                 file.setExecutable(false, false);
481                 file.setWritable(false, false);
482                 file.setReadable(false, false);
483                 file.setReadable(true, true);
484         }
485
486         public boolean ok() {
487                 return ok;
488         }
489         
490         public static interface ProcessArgs {
491                 public Properties process(final String[] args, final Properties props);
492         }
493 }