a03b3fdf029f17054c0ae296e8e391dc2ed412a7
[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             access.setProperty(Config.AAF_URL, Defaults.AAF_URL);
312             access.setProperty(Config.CM_URL, Defaults.CM_URL);
313             String cadiLatitude = access.getProperty(Config.CADI_LATITUDE);
314             if (cadiLatitude==null) {
315                 System.out.println("# If you do not know your Global Coordinates, we suggest bing.com/maps");
316                 cadiLatitude=AAFSSO.cons.readLine("cadi_latitude[0.000]=");
317                 if (cadiLatitude==null || cadiLatitude.isEmpty()) {
318                     cadiLatitude="0.000";
319                 }
320                 access.setProperty(Config.CADI_LATITUDE, cadiLatitude);
321                 addProp(Config.CADI_LATITUDE, cadiLatitude);
322                 
323             }
324             String cadiLongitude = access.getProperty(Config.CADI_LONGITUDE);
325             if (cadiLongitude==null) {
326                 cadiLongitude=AAFSSO.cons.readLine("cadi_longitude[0.000]=");
327                 if (cadiLongitude==null || cadiLongitude.isEmpty()) {
328                     cadiLongitude="0.000";
329                 }
330                 access.setProperty(Config.CADI_LONGITUDE, cadiLongitude);
331                 addProp(Config.CADI_LONGITUDE, cadiLongitude);
332             }
333     
334             String cadi_truststore = access.getProperty(Config.CADI_TRUSTSTORE);
335             if (cadi_truststore==null) {
336                 String name; 
337                 String select;
338                 for (File tsf : dot_aaf.listFiles()) {
339                     name = tsf.getName();
340                     if (name.contains("trust") && 
341                             (name.endsWith(".jks") || name.endsWith(".p12"))) {
342                         select = cons.readLine("Use %s for TrustStore? (y/n):",tsf.getName());
343                         if ("y".equalsIgnoreCase(select)) {
344                             cadi_truststore=tsf.getCanonicalPath();
345                             access.setProperty(Config.CADI_TRUSTSTORE, cadi_truststore);
346                             addProp(Config.CADI_TRUSTSTORE, cadi_truststore);
347                             break;
348                         }
349                     }
350                 }
351             }
352             if (cadi_truststore!=null) {
353                 if (cadi_truststore.indexOf(File.separatorChar)<0) {
354                     cadi_truststore=dot_aaf.getPath()+File.separator+cadi_truststore;
355                 }
356                 String cadi_truststore_password = access.getProperty(Config.CADI_TRUSTSTORE_PASSWORD);
357                 if (cadi_truststore_password==null) {
358                     cadi_truststore_password=AAFSSO.cons.readLine("cadi_truststore_password[%s]=","changeit");
359                     cadi_truststore_password = access.encrypt(cadi_truststore_password);
360                     access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password);
361                     addProp(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password);
362                 }
363             }
364             ok = err==null;
365         }
366         writeFiles();
367     }
368
369     public void setLogDefault() {
370         this.setLogDefault(PropAccess.DEFAULT);
371         System.setOut(stdOutOrig);
372     }
373
374     public void setStdErrDefault() {
375         access.setLogLevel(PropAccess.DEFAULT);
376         System.setErr(stdErrOrig);
377     }
378
379     public void setLogDefault(Level level) {
380         if (access!=null) {
381             access.setLogLevel(level);
382         }
383         System.setOut(stdOutOrig);
384     }
385
386     public boolean loginOnly() {
387         return loginOnly;
388     }
389
390     public void addProp(String key, String value) {
391         if (key==null || value==null) {
392             return;
393         }
394         touchDiskprops=true;
395         diskprops.setProperty(key, value);
396     }
397
398     public void writeFiles() throws IOException {
399         if (touchDiskprops) {
400             // Store Creds, if they work
401             if (diskprops != null) {
402                 if (!dot_aaf.exists()) {
403                     dot_aaf.mkdirs();
404                 }
405                 FileOutputStream fos = new FileOutputStream(sso);
406                 try {
407                     diskprops.store(fos, "AAF Single Signon");
408                 } finally {
409                     fos.close();
410                     setReadonly(sso);
411                 }
412             }
413             if (sso != null) {
414                 setReadonly(sso);
415                 sso.setWritable(true, true);
416             }
417         }
418     }
419
420     public PropAccess access() {
421         return access;
422     }
423
424     public StringBuilder err() {
425         return err;
426     }
427
428     public String user() {
429         return user;
430     }
431
432     public String enc_pass() {
433         return encrypted_pass;
434     }
435
436     public boolean useX509() {
437         return use_X509;
438     }
439
440     public void close() {
441         if (close != null) {
442             try {
443                 close.invoke(null);
444             } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
445                 // nothing to do here.
446             }
447             close = null;
448         }
449     }
450
451     private List<String> parseArgs(String[] args)
452     {
453         List<String> larg = new ArrayList<>(args.length);
454
455         // Cover for bash's need to escape *.. (\\*)
456         // also, remove SSO if required
457         for (int i = 0; i < args.length; ++i) {
458             if ("\\*".equals(args[i])) {
459                 args[i] = "*";
460             }
461
462             if ("-logout".equalsIgnoreCase(args[i])) {
463                 removeSSO = true;
464             } else if ("-login".equalsIgnoreCase(args[i])) {
465                 loginOnly = true;
466             } else if ("-noexit".equalsIgnoreCase(args[i])) {
467                 doExit = false;
468             } else {
469                 larg.add(args[i]);
470             }
471         }
472         return larg;
473     }
474     
475     private void setReadonly(File file) {
476         file.setExecutable(false, false);
477         file.setWritable(false, false);
478         file.setReadable(false, false);
479         file.setReadable(true, true);
480     }
481
482     public boolean ok() {
483         return ok;
484     }
485     
486     public static interface ProcessArgs {
487         public Properties process(final String[] args, final Properties props);
488     }
489 }