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