Refine Agent to create CADI Configs
[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                         }
190                         
191                         String keystore=access.getProperty(Config.CADI_KEYSTORE);
192                         String keystore_pass=access.getProperty(Config.CADI_KEYSTORE_PASSWORD);
193                         
194                         if(user==null || (alias!=null && (keystore==null || keystore_pass==null))) {
195                                 String select = null;
196                                 String name;
197                                 for (File tsf : dot_aaf.listFiles()) {
198                                         name = tsf.getName();
199                                         if (!name.contains("trust") && (name.endsWith(".jks") || name.endsWith(".p12"))) {
200                                                 setLogDefault();
201                                                 select = cons.readLine("Use %s for Identity? (y/n): ",tsf.getName());
202                                                 if("y".equalsIgnoreCase(select)) {
203                                                         keystore = tsf.getCanonicalPath();
204                                                         access.setProperty(Config.CADI_KEYSTORE, keystore);
205                                                         addProp(Config.CADI_KEYSTORE, keystore);
206                                                         char[] password = cons.readPassword("Keystore Password: ");
207                                                         encrypted_pass= access.encrypt(new String(password));
208                                                         access.setProperty(Config.CADI_KEYSTORE_PASSWORD, encrypted_pass);
209                                                         addProp(Config.CADI_KEYSTORE_PASSWORD, encrypted_pass);
210                                                         
211                                                         // TODO READ Aliases out of Keystore?
212                                                         user = alias = cons.readLine("Keystore alias: ");
213                                                         access.setProperty(Config.CADI_ALIAS, user);
214                                                         addProp(Config.CADI_ALIAS, user);
215                                                         break;
216                                                 }
217                                         }
218                                 }
219                                 if(alias==null) {
220                                         user = appID = cons.readLine(Config.AAF_APPID + ": ");
221                                         access.setProperty(Config.AAF_APPID, appID);
222                                         addProp(Config.AAF_APPID, appID);
223                                         char[] password = cons.readPassword(Config.AAF_APPPASS + ": ");
224                                         encrypted_pass= access.encrypt(new String(password));
225                                         access.setProperty(Config.AAF_APPPASS, encrypted_pass);
226                                         addProp(Config.AAF_APPPASS, encrypted_pass);
227                                 }
228                         } else {
229                                 encrypted_pass = access.getProperty(Config.CADI_KEYSTORE_PASSWORD);
230                                 if(encrypted_pass == null) {
231                                         keystore_pass = null;
232                                         encrypted_pass = access.getProperty(Config.AAF_APPPASS);
233                                 } else {
234                                         keystore_pass = encrypted_pass;
235                                 }
236                         }
237                         
238         
239                         if (alias!=null) {
240                                 use_X509 = true;
241                         } else {
242                                 use_X509 = false;
243                                 Symm decryptor = Symm.obtain(dot_aaf_kf);
244                                 if (user == null) {
245                                         if (sso.exists()) {
246                                                 String cm_url = access.getProperty(Config.CM_URL); // SSO might overwrite...
247                                                 FileInputStream fos = new FileInputStream(sso);
248                                                 try {
249                                                         access.load(fos);
250                                                         user = access.getProperty(Config.AAF_APPID);
251                                                         encrypted_pass = access.getProperty(Config.AAF_APPPASS);
252                                                         // decrypt with .aaf, and re-encrypt with regular Keyfile
253                                                         access.setProperty(Config.AAF_APPPASS,
254                                                                         access.encrypt(decryptor.depass(encrypted_pass)));
255                                                         if (cm_url != null) { //Command line CM_URL Overwrites ssofile.
256                                                                 access.setProperty(Config.CM_URL, cm_url);
257                                                         }
258                                                 } finally {
259                                                         fos.close();
260                                                 }
261                                         } else {
262                                                 diskprops = new Properties();
263                                                 String realm = Config.getDefaultRealm();
264                                                 // Turn on Console Sysout
265                                                 System.setOut(System.out);
266                                                 user = cons.readLine("aaf_id(%s@%s): ", System.getProperty("user.name"), realm);
267                                                 if (user == null) {
268                                                         user = System.getProperty("user.name") + '@' + realm;
269                                                 } else if (user.length() == 0) { //
270                                                         user = System.getProperty("user.name") + '@' + realm;
271                                                 } else if ((user.indexOf('@') < 0) && (realm != null)) {
272                                                         user = user + '@' + realm;
273                                                 }
274                                                 access.setProperty(Config.AAF_APPID, user);
275                                                 diskprops.setProperty(Config.AAF_APPID, user);
276                                                 encrypted_pass = new String(cons.readPassword("aaf_password: "));
277                                                 System.setOut(os);
278                                                 encrypted_pass = Symm.ENC + decryptor.enpass(encrypted_pass);
279                                                 access.setProperty(Config.AAF_APPPASS, encrypted_pass);
280                                                 diskprops.setProperty(Config.AAF_APPPASS, encrypted_pass);
281                                                 diskprops.setProperty(Config.CADI_KEYFILE, access.getProperty(Config.CADI_KEYFILE));
282                                         }
283                                 }
284                         }
285                         if (user == null) {
286                                 err = new StringBuilder("Add -D" + Config.AAF_APPID + "=<id> ");
287                         }
288         
289                         if (encrypted_pass == null && alias == null) {
290                                 if (err == null) {
291                                         err = new StringBuilder();
292                                 } else {
293                                         err.append("and ");
294                                 }
295                                 err.append("-D" + Config.AAF_APPPASS + "=<passwd> ");
296                         }
297                         
298                         String locateUrl = access.getProperty(Config.AAF_LOCATE_URL);
299                         if(locateUrl==null) {
300                                 locateUrl=AAFSSO.cons.readLine("AAF Locator URL=https://");
301                                 if(locateUrl==null || locateUrl.length()==0) {
302                                         err = new StringBuilder(Config.AAF_LOCATE_URL);
303                                         err.append(" is required.");
304                                         ok = false;
305                                         return;
306                                 } else {
307                                         locateUrl="https://"+locateUrl;
308                                 }
309                                 access.setProperty(Config.AAF_LOCATE_URL, locateUrl);
310                                 addProp(Config.AAF_LOCATE_URL, locateUrl);
311                         }
312                         
313                         String aafUrl = "https://AAF_LOCATE_URL/AAF_NS.service:2.0";
314                         access.setProperty(Config.AAF_URL, aafUrl);
315                         access.setProperty(Config.CM_URL, "https://AAF_LOCATE_URL/AAF_NS.cm:2.0");
316                         String cadiLatitude = access.getProperty(Config.CADI_LATITUDE);
317                         if(cadiLatitude==null) {
318                                 System.out.println("# If you do not know your Global Coordinates, we suggest bing.com/maps");
319                                 cadiLatitude=AAFSSO.cons.readLine("cadi_latitude[0.000]=");
320                                 if(cadiLatitude==null || cadiLatitude.isEmpty()) {
321                                         cadiLatitude="0.000";
322                                 }
323                                 access.setProperty(Config.CADI_LATITUDE, cadiLatitude);
324                                 addProp(Config.CADI_LATITUDE, cadiLatitude);
325                                 
326                         }
327                         String cadiLongitude = access.getProperty(Config.CADI_LONGITUDE);
328                         if(cadiLongitude==null) {
329                                 cadiLongitude=AAFSSO.cons.readLine("cadi_longitude[0.000]=");
330                                 if(cadiLongitude==null || cadiLongitude.isEmpty()) {
331                                         cadiLongitude="0.000";
332                                 }
333                                 access.setProperty(Config.CADI_LONGITUDE, cadiLongitude);
334                                 addProp(Config.CADI_LONGITUDE, cadiLongitude);
335                         }
336         
337                         String cadi_truststore = access.getProperty(Config.CADI_TRUSTSTORE);
338                         if(cadi_truststore==null) {
339                                 String name; 
340                                 String select;
341                                 for (File tsf : dot_aaf.listFiles()) {
342                                         name = tsf.getName();
343                                         if (name.contains("trust") && 
344                                                         (name.endsWith(".jks") || name.endsWith(".p12"))) {
345                                                 select = cons.readLine("Use %s for TrustStore? (y/n):",tsf.getName());
346                                                 if("y".equalsIgnoreCase(select)) {
347                                                         cadi_truststore=tsf.getCanonicalPath();
348                                                         access.setProperty(Config.CADI_TRUSTSTORE, cadi_truststore);
349                                                         addProp(Config.CADI_TRUSTSTORE, cadi_truststore);
350                                                         break;
351                                                 }
352                                         }
353                                 }
354                         }
355                         if(cadi_truststore!=null) {
356                                 if(cadi_truststore.indexOf(File.separatorChar)<0) {
357                                         cadi_truststore=dot_aaf.getPath()+File.separator+cadi_truststore;
358                                 }
359                                 String cadi_truststore_password = access.getProperty(Config.CADI_TRUSTSTORE_PASSWORD);
360                                 if(cadi_truststore_password==null) {
361                                         cadi_truststore_password=AAFSSO.cons.readLine("cadi_truststore_password[%s]=","changeit");
362                                         cadi_truststore_password = access.encrypt(cadi_truststore_password);
363                                         access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password);
364                                         addProp(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password);
365                                 }
366                         }
367                         ok = err==null;
368                 }
369                 writeFiles();
370         }
371
372         public void setLogDefault() {
373                 this.setLogDefault(PropAccess.DEFAULT);
374                 System.setOut(stdOutOrig);
375         }
376
377         public void setStdErrDefault() {
378                 access.setLogLevel(PropAccess.DEFAULT);
379                 System.setErr(stdErrOrig);
380         }
381
382         public void setLogDefault(Level level) {
383                 if(access!=null) {
384                         access.setLogLevel(level);
385                 }
386                 System.setOut(stdOutOrig);
387         }
388
389         public boolean loginOnly() {
390                 return loginOnly;
391         }
392
393         public void addProp(String key, String value) {
394                 if(key==null || value==null) {
395                         return;
396                 }
397                 touchDiskprops=true;
398                 diskprops.setProperty(key, value);
399         }
400
401         public void writeFiles() throws IOException {
402                 if(touchDiskprops) {
403                         // Store Creds, if they work
404                         if (diskprops != null) {
405                                 if (!dot_aaf.exists()) {
406                                         dot_aaf.mkdirs();
407                                 }
408                                 FileOutputStream fos = new FileOutputStream(sso);
409                                 try {
410                                         diskprops.store(fos, "AAF Single Signon");
411                                 } finally {
412                                         fos.close();
413                                         setReadonly(sso);
414                                 }
415                         }
416                         if (sso != null) {
417                                 setReadonly(sso);
418                                 sso.setWritable(true, true);
419                         }
420                 }
421         }
422
423         public PropAccess access() {
424                 return access;
425         }
426
427         public StringBuilder err() {
428                 return err;
429         }
430
431         public String user() {
432                 return user;
433         }
434
435         public String enc_pass() {
436                 return encrypted_pass;
437         }
438
439         public boolean useX509() {
440                 return use_X509;
441         }
442
443         public void close() {
444                 if (close != null) {
445                         try {
446                                 close.invoke(null);
447                         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
448                                 // nothing to do here.
449                         }
450                         close = null;
451                 }
452         }
453
454         private List<String> parseArgs(String[] args)
455         {
456                 List<String> larg = new ArrayList<String>(args.length);
457
458                 // Cover for bash's need to escape *.. (\\*)
459                 // also, remove SSO if required
460                 for (int i = 0; i < args.length; ++i) {
461                         if ("\\*".equals(args[i])) {
462                                 args[i] = "*";
463                         }
464
465                         if ("-logout".equalsIgnoreCase(args[i])) {
466                                 removeSSO = true;
467                         } else if ("-login".equalsIgnoreCase(args[i])) {
468                                 loginOnly = true;
469                         } else if ("-noexit".equalsIgnoreCase(args[i])) {
470                                 doExit = false;
471                         } else {
472                                 larg.add(args[i]);
473                         }
474                 }
475                 return larg;
476         }
477         
478         private void setReadonly(File file) {
479                 file.setExecutable(false, false);
480                 file.setWritable(false, false);
481                 file.setReadable(false, false);
482                 file.setReadable(true, true);
483         }
484
485         public boolean ok() {
486                 return ok;
487         }
488         
489         public static interface ProcessArgs {
490                 public Properties process(final String[] args, final Properties props);
491         }
492 }