caf15d3598a01d8b8f31de76d1d4d6e6c6bcc2eb
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / configure / Agent.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.configure;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.net.ConnectException;
29 import java.net.HttpURLConnection;
30 import java.net.InetAddress;
31 import java.net.UnknownHostException;
32 import java.nio.file.Files;
33 import java.security.KeyPair;
34 import java.security.KeyStore;
35 import java.security.cert.X509Certificate;
36 import java.util.ArrayDeque;
37 import java.util.Arrays;
38 import java.util.Deque;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Map.Entry;
45 import java.util.Properties;
46
47 import org.onap.aaf.cadi.Access;
48 import org.onap.aaf.cadi.CadiException;
49 import org.onap.aaf.cadi.CmdLine;
50 import org.onap.aaf.cadi.LocatorException;
51 import org.onap.aaf.cadi.PropAccess;
52 import org.onap.aaf.cadi.Symm;
53 import org.onap.aaf.cadi.Access.Level;
54 import org.onap.aaf.cadi.aaf.client.ErrMessage;
55 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
56 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
57 import org.onap.aaf.cadi.client.Future;
58 import org.onap.aaf.cadi.client.Rcli;
59 import org.onap.aaf.cadi.client.Retryable;
60 import org.onap.aaf.cadi.config.Config;
61 import org.onap.aaf.cadi.config.RegistrationPropHolder;
62 import org.onap.aaf.cadi.config.SecurityInfoC;
63 import org.onap.aaf.cadi.http.HBasicAuthSS;
64 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
65 import org.onap.aaf.cadi.sso.AAFSSO;
66 import org.onap.aaf.cadi.util.Chmod;
67 import org.onap.aaf.cadi.util.FQI;
68 import org.onap.aaf.misc.env.APIException;
69 import org.onap.aaf.misc.env.Data.TYPE;
70 import org.onap.aaf.misc.env.Env;
71 import org.onap.aaf.misc.env.TimeTaken;
72 import org.onap.aaf.misc.env.Trans;
73 import org.onap.aaf.misc.env.util.Chrono;
74 import org.onap.aaf.misc.env.util.Split;
75 import org.onap.aaf.misc.rosetta.env.RosettaDF;
76 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
77
78 import aaf.v2_0.Perm;
79 import aaf.v2_0.Perms;
80 import certman.v1_0.Artifacts;
81 import certman.v1_0.Artifacts.Artifact;
82 import certman.v1_0.CertInfo;
83 import certman.v1_0.CertificateRequest;
84 import locate.v1_1.Configuration;
85 import locate.v1_1.Configuration.Props;
86
87 public class Agent {
88     private static final String HASHES = "################################################################";
89     private static final String PRINT = "print";
90     private static final String FILE = "file";
91     public static final String PKCS12 = "pkcs12";
92     public static final String JKS = "jks";
93     private static final String SCRIPT="script";
94     
95     private static final String CM_VER = "1.0";
96     public static final int PASS_SIZE = 24;
97     private static int TIMEOUT;
98     
99     private static RosettaDF<CertificateRequest> reqDF;
100     private static RosettaDF<CertInfo> certDF;
101     private static RosettaDF<Artifacts> artifactsDF;
102     private static RosettaDF<Configuration> configDF;
103     private static RosettaDF<Perms> permDF;
104     private static ErrMessage errMsg;
105     private static Map<String,PlaceArtifact> placeArtifact;
106     private static RosettaEnv env;
107     
108     private static boolean doExit;
109     private static AAFCon<?> aafcon;
110     
111     private static List<String> CRED_TAGS = Arrays.asList(new String[] {
112             Config.CADI_KEYFILE,
113             Config.AAF_APPID, Config.AAF_APPPASS,
114             Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
115             Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
116             Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
117             });
118     private static List<String> LOC_TAGS = Arrays.asList(new String[] {
119                 Config.CADI_LATITUDE, Config.CADI_LONGITUDE
120                 });
121     // Note: This is set by loadURLs. Use that function as singleton, not directly.
122         private static Map<String,String> aaf_urls = null;
123
124
125     public static void main(String[] args) {
126         int exitCode = 0;
127         doExit = true;
128         if (args.length>0 && "cadi".equals(args[0])) {
129             String[] newArgs = new String[args.length-1];
130             System.arraycopy(args, 1, newArgs, 0, newArgs.length);
131             if (newArgs.length==0) {
132                 System.out.println(HASHES);
133                 System.out.println("Note: Cadi CmdLine is a separate component.  When running with\n\t"
134                         + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
135                 System.out.println(HASHES);
136             }
137             CmdLine.main(newArgs);
138         } else {
139             try {
140                 AAFSSO aafsso=null;
141                 PropAccess access;
142                 
143                 if (args.length>1 && args[0].equals("validate") ) {
144                     int idx = args[1].indexOf('=');
145                     aafsso = null;
146                     access = new PropAccess(
147                                 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
148                                 '='+
149                                 (idx<0?args[1]:args[1].substring(idx+1)));
150                 } else {
151                     aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
152                         @Override
153                         public Properties process(String[] args, Properties props) {
154                             if (args.length>1) {
155                                 if (!args[0].equals("keypairgen")) {
156                                     props.put(Config.AAF_APPID, args[1]);
157                                 }    
158                             }
159                             return props;
160                         }
161                     });
162                     access = aafsso.access();
163                 }
164                     
165                 if (aafsso!=null && aafsso.loginOnly()) {
166                     aafsso.setLogDefault();
167                     aafsso.writeFiles();
168                     System.out.println("AAF SSO information created in ~/.aaf");
169                 } else {
170                     env = new RosettaEnv(access.getProperties());
171                     Deque<String> cmds = new ArrayDeque<String>();
172                     for (String p : args) {
173                         int eq;
174                         if ("-noexit".equalsIgnoreCase(p)) {
175                             doExit = false;
176                         } else if ((eq=p.indexOf('=')) < 0) {
177                             cmds.add(p);
178                         } else {
179                                 access.setProperty(p.substring(0,eq), p.substring(eq+1));
180                         }
181                     }
182                     
183                     if (cmds.size()==0) {
184                         if (aafsso!=null) {
185                             aafsso.setLogDefault();
186                         }
187                         // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
188                         System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
189                         System.out.println("   create     <FQI> [<machine>]");
190                         System.out.println("   read       <FQI> [<machine>]");
191                         System.out.println("   update     <FQI> [<machine>]");
192                         System.out.println("   delete     <FQI> [<machine>]");
193                         System.out.println("   copy       <FQI> <machine> <newmachine>[,<newmachine>]*");
194                         System.out.println("   place      <FQI> [<machine>]");
195                         System.out.println("   showpass   <FQI> [<machine>]");
196                         System.out.println("   check      <FQI> [<machine>]");
197                         System.out.println("   keypairgen <FQI>");
198                         System.out.println("   config     <FQI>");
199                         System.out.println("   validate   <NS>.props>");
200                         System.out.println("   --- Additional Tool Access ---");
201                         System.out.println("     ** Type with no params for Tool Help");
202                         System.out.println("     ** If using with Agent, preface with \"cadi\"");
203                         System.out.println("   cadi <cadi tool params, see -?>");
204                         
205                         if (doExit) {
206                             System.exit(1);
207                         }
208                     }
209                     
210                     TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
211                 
212                     reqDF = env.newDataFactory(CertificateRequest.class);
213                     artifactsDF = env.newDataFactory(Artifacts.class);
214                     certDF = env.newDataFactory(CertInfo.class);
215                     configDF = env.newDataFactory(Configuration.class);
216                     permDF = env.newDataFactory(Perms.class);
217                     errMsg = new ErrMessage(env);
218         
219                     placeArtifact = new HashMap<>();
220                     placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
221                     placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
222                     placeArtifact.put(FILE, new PlaceArtifactInFiles());
223                     placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
224                     placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
225                     
226                     Trans trans = env.newTrans();
227                     String token;
228                     if ((token=access.getProperty("oauth_token"))!=null) {
229                         trans.setProperty("oauth_token", token);
230                     }
231                     try {
232                         if (aafsso!=null) {
233                         // show Std out again
234                             aafsso.setLogDefault();
235                             aafsso.setStdErrDefault();
236                             
237                             Map<String, String> aaf_urls = loadURLs(access);
238                             aafsso.addProp(Config.AAF_URL_CM, aaf_urls.get(Config.AAF_URL_CM));
239                             aafsso.writeFiles();
240                         }
241     
242                         
243     
244                         String cmd = cmds.removeFirst();
245                         switch(cmd) {
246                             case "place":
247                                 placeCerts(trans,aafcon(access),cmds);
248                                 break;
249                             case "create":
250                                 createArtifact(trans, aafcon(access),cmds);
251                                 break;
252                             case "read":
253                                 readArtifact(trans, aafcon(access), cmds);
254                                 break;
255                             case "copy":
256                                 copyArtifact(trans, aafcon(access), cmds);
257                                 break;
258                             case "update":
259                                 updateArtifact(trans, aafcon(access), cmds);
260                                 break;
261                             case "delete":
262                                 deleteArtifact(trans, aafcon(access), cmds);
263                                 break;
264                             case "showpass":
265                                 showPass(trans, aafcon(access), cmds);
266                                 break;
267                             case "keypairgen":
268                                 keypairGen(trans, access, cmds);
269                                 break;
270                             case "config":
271                                 config(trans,access,args,cmds);
272                                 break;
273                             case "validate":
274                                 validate(access);
275                                 break;
276                             case "check":
277                                 try {
278                                     exitCode = check(trans,aafcon(access),cmds);
279                                 } catch (Exception e) {
280                                     exitCode = 1;
281                                     throw e;
282                                 }
283                                 break;
284                             default:
285                                 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
286                         }
287                     } finally {
288                         StringBuilder sb = new StringBuilder();
289                         trans.auditTrail(4, sb, Trans.REMOTE);
290                         if (sb.length()>0) {
291                             trans.info().log("Trans Info\n",sb);
292                         }
293                     }
294                     if (aafsso!=null) {
295                         aafsso.close();
296                     }
297                 }
298             } catch (Exception e) {
299                 e.printStackTrace();
300             }
301         }
302         if (exitCode != 0 && doExit) {
303             System.exit(exitCode);
304         }
305     }
306
307     public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
308                 if(aaf_urls==null) {
309                 Map<String,String> rv = new HashMap<>();
310                 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
311                 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
312                 dot_le=dot_le==null?"":'.'+dot_le;
313                 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
314                 for(String u : new String[] {"aaf","locate","oauth","cm","gui","fs","hello","token","introspect"}) {
315                         String proto = "fs".equals(u)?"http://":"https://";
316                         String lhost;
317                         if("locate".equals(u)) {
318                                 lhost=rph.default_fqdn;
319                         } else {
320                                 lhost=Config.AAF_LOCATE_URL_TAG;
321                         }
322                         String value = rph.replacements("Agent:loadURLs",
323                                         proto + lhost + "/AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version, 
324                                         null,dot_le);
325                         switch(u) {
326                                 case "aaf": rv.put(Config.AAF_URL, value); break;
327                                 case "locate": rv.put(Config.AAF_LOCATE_URL, value); break;
328                                 case "token": rv.put(Config.AAF_OAUTH2_TOKEN_URL, value); break;
329                                 case "introspect": rv.put(Config.AAF_OAUTH2_INTROSPECT_URL, value); break;
330                                 case "cm": rv.put(Config.AAF_URL_CM, value); break;
331                                 case "gui": rv.put(Config.AAF_URL_GUI, value); break;
332                                 case "fs": rv.put(Config.AAF_URL_FS, value); break;
333                                 case "hello": rv.put(Config.AAF_URL_HELLO, value); break;
334                                 default:
335                                 rv.put("aaf_url_" + u, value);
336                         }
337                 };
338                 aaf_urls = rv;
339                 }
340             return aaf_urls;
341         }
342
343         public static void fillMissing(PropAccess access, Map<String, String> map) {
344                 for(Entry<String, String> es : map.entrySet()) {
345                         if(access.getProperty(es.getKey())==null) {
346                                 access.setProperty(es.getKey(),es.getValue());
347                         }
348                 }
349         }
350
351         private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
352         if (aafcon==null) {
353             aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
354         }
355         return aafcon;
356     }
357
358     private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
359         String value;
360         if ((value=pa.getProperty(tag))==null) {
361             if (secure) {
362                 value = new String(AAFSSO.cons.readPassword(prompt, def));
363             } else {
364                 value = AAFSSO.cons.readLine(prompt,def).trim();
365             }
366             if (value!=null) {
367                 if (value.length()>0) {
368                     pa.setProperty(tag,value);
369                     env.setProperty(tag,value);
370                 } else if (def.length==1) {
371                     value=def[0].toString();
372                     pa.setProperty(tag,value);
373                     env.setProperty(tag,value);
374                 }
375             }
376         }
377         return value;
378     }
379
380     private static String fqi(Deque<String> cmds) {
381         if (cmds.size()<1) {
382             String alias = env.getProperty(Config.CADI_ALIAS);
383             return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
384         }
385         return cmds.removeFirst();    
386     }
387
388     private static String machine(Deque<String> cmds) throws UnknownHostException {
389         if (cmds.size()>0) {
390             return cmds.removeFirst();
391         } else {
392             String mach = env.getProperty(Config.HOSTNAME);
393             return mach!=null?mach:InetAddress.getLocalHost().getHostName();
394         }
395     }
396
397     private static String[] machines(Deque<String> cmds)  {
398         String machines;
399         if (cmds.size()>0) {
400             machines = cmds.removeFirst();
401         } else {
402             machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
403         }
404         return Split.split(',', machines);
405     }
406
407     private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
408         final String mechID = fqi(cmds);
409         final String machine = machine(cmds);
410
411         Artifacts artifacts = new Artifacts();
412         Artifact arti = new Artifact();
413         artifacts.getArtifact().add(arti);
414         arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
415         arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
416         arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
417         
418         String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
419         for (String s : Split.splitTrim(',', resp)) {
420             arti.getType().add(s);
421         }
422         // Always do Script
423         if (!resp.contains(SCRIPT)) {
424             arti.getType().add(SCRIPT);
425         }
426
427         // Note: Sponsor is set on Creation by CM
428         String configRootName = FQI.reverseDomain(arti.getMechid());
429         arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
430         arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
431         arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
432         arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
433         arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
434         
435         TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
436         try {
437             Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
438             if (future.get(TIMEOUT)) {
439                 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
440             } else {
441                 trans.error().printf("Call to AAF Certman failed, %s",
442                     errMsg.toMsg(future));
443             }
444         } finally {
445             tt.done();
446         }
447     }
448
449     private static String toNotification(String notification) {
450         if (notification==null) {
451             notification="";
452         } else if (notification.length()>0) {
453             if (notification.indexOf(':')<0) {
454                 notification = "mailto:" + notification;
455             }
456         }
457         return notification;
458     }
459     
460
461     private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
462         String mechID = fqi(cmds);
463         String machine = machine(cmds);
464
465         TimeTaken tt = trans.start("Read Artifact", Env.SUB);
466         try {
467             Future<Artifacts> future = aafcon.client(CM_VER)
468                     .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
469     
470             if (future.get(TIMEOUT)) {
471                 boolean printed = false;
472                 for (Artifact a : future.value.getArtifact()) {
473                     AAFSSO.cons.printf("AppID:          %s\n",a.getMechid()); 
474                     AAFSSO.cons.printf("  Sponsor:       %s\n",a.getSponsor()); 
475                     AAFSSO.cons.printf("Machine:         %s\n",a.getMachine()); 
476                     AAFSSO.cons.printf("CA:              %s\n",a.getCa()); 
477                     StringBuilder sb = new StringBuilder();
478                     boolean first = true;
479                     for (String t : a.getType()) {
480                         if (first) {first=false;}
481                         else{sb.append(',');}
482                         sb.append(t);
483                     }
484                     AAFSSO.cons.printf("Types:           %s\n",sb);
485                     AAFSSO.cons.printf("Namespace:       %s\n",a.getNs()); 
486                     AAFSSO.cons.printf("Directory:       %s\n",a.getDir());
487                     AAFSSO.cons.printf("O/S User:        %s\n",a.getOsUser());
488                     AAFSSO.cons.printf("Renew Days:      %d\n",a.getRenewDays());
489                     AAFSSO.cons.printf("Notification     %s\n",a.getNotification());
490                     printed = true;
491                 }
492                 if (!printed) {
493                     AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
494                 }
495             } else {
496                 trans.error().log(errMsg.toMsg(future));
497             }
498         } finally {
499             tt.done();
500         }
501     }
502     
503     private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
504         String mechID = fqi(cmds);
505         String machine = machine(cmds);
506         String[] newmachs = machines(cmds);
507         if (machine==null || newmachs == null) {
508             trans.error().log("No machines listed to copy to");
509         } else {
510             TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
511             try {
512                 Future<Artifacts> future = aafcon.client(CM_VER)
513                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
514             
515                 if (future.get(TIMEOUT)) {
516                     boolean printed = false;
517                     for (Artifact a : future.value.getArtifact()) {
518                         for (String m : newmachs) {
519                             a.setMachine(m);
520                             Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
521                             if (fup.get(TIMEOUT)) {
522                                 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
523                             } else {
524                                 trans.error().printf("Call to AAF Certman failed, %s",
525                                     errMsg.toMsg(fup));
526                             }
527     
528                             printed = true;
529                         }
530                     }
531                     if (!printed) {
532                         AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
533                     }
534                 } else {
535                     trans.error().log(errMsg.toMsg(future));
536                 }
537             } finally {
538                 tt.done();
539             }
540         }
541     }
542
543     private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
544         String mechID = fqi(cmds);
545         String machine = machine(cmds);
546
547         TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
548         try {
549             Future<Artifacts> fread = aafcon.client(CM_VER)
550                     .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
551     
552             if (fread.get(TIMEOUT)) {
553                 Artifacts artifacts = new Artifacts();
554                 for (Artifact a : fread.value.getArtifact()) {
555                     Artifact arti = new Artifact();
556                     artifacts.getArtifact().add(arti);
557                     
558                     AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
559                     arti.setMechid(a.getMechid());
560                     arti.setMachine(a.getMachine());
561                     arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
562                     StringBuilder sb = new StringBuilder();
563                     boolean first = true;
564                     for (String t : a.getType()) {
565                         if (first) {first=false;}
566                         else{sb.append(',');}
567                         sb.append(t);
568                     }
569     
570                     String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
571                     for (String s : Split.splitTrim(',', resp)) {
572                         arti.getType().add(s);
573                     }
574                     // Always do Script
575                     if (!resp.contains(SCRIPT)) {
576                         arti.getType().add(SCRIPT);
577                     }
578
579                     // Note: Sponsor is set on Creation by CM
580                     arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
581                     arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
582                     arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
583                     arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
584                     arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
585     
586                 }
587                 if (artifacts.getArtifact().size()==0) {
588                     AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
589                 } else {
590                     Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
591                     if (fup.get(TIMEOUT)) {
592                         trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
593                     } else {
594                         trans.error().printf("Call to AAF Certman failed, %s",
595                             errMsg.toMsg(fup));
596                     }
597                 }
598             } else {
599                 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
600                         errMsg.toMsg(fread),mechID,machine);
601             }
602         } finally {
603             tt.done();
604         }
605     }
606     
607     private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
608         String mechid = fqi(cmds);
609         String machine = machine(cmds);
610         
611         TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
612         try {
613             Future<Void> future = aafcon.client(CM_VER)
614                     .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
615     
616             if (future.get(TIMEOUT)) {
617                 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
618             } else {
619                 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
620                     errMsg.toMsg(future),mechid,machine);
621             }
622         } finally {
623             tt.done();
624         }
625     }
626
627     
628
629     private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
630         boolean rv = false;
631         String mechID = fqi(cmds);
632         String machine = machine(cmds);
633         String[] fqdns = Split.split(':', machine);
634         String key;
635         if (fqdns.length>1) {
636             key = fqdns[0];
637             machine = fqdns[1];
638         } else {
639             key = machine;
640         }
641         
642         TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
643         try {
644             Future<Artifacts> acf = aafcon.client(CM_VER)
645                     .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
646             if (acf.get(TIMEOUT)) {
647                 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
648                     AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
649                 } else {
650                     for (Artifact a : acf.value.getArtifact()) {
651                         String osID = System.getProperty("user.name");
652                         if (a.getOsUser().equals(osID)) {
653                             CertificateRequest cr = new CertificateRequest();
654                             cr.setMechid(a.getMechid());
655                             cr.setSponsor(a.getSponsor());
656                             for (int i=0;i<fqdns.length;++i) {
657                                 cr.getFqdns().add(fqdns[i]);
658                             }
659                             Future<String> f = aafcon.client(CM_VER)
660                                     .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
661                             if (f.get(TIMEOUT)) {
662                                 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
663                                 for (String type : a.getType()) {
664                                     PlaceArtifact pa = placeArtifact.get(type);
665                                     if (pa!=null) {
666                                         if (rv = pa.place(trans, capi, a,machine)) {
667                                             notifyPlaced(a,rv);
668                                         }
669                                     }
670                                 }
671                                 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
672                             } else {
673                                 trans.error().log(errMsg.toMsg(f));
674                             }
675                         } else {
676                             trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
677                         }
678                     }
679                 }
680                 PropHolder.writeAll();
681             } else {
682                 trans.error().log(errMsg.toMsg(acf));
683             }
684         } finally {
685             tt.done();
686         }
687         return rv;
688     }
689     
690     private static void notifyPlaced(Artifact a, boolean rv) {
691     }
692
693     private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
694         String mechID = fqi(cmds);
695         String machine = machine(cmds);
696
697         TimeTaken tt = trans.start("Show Password", Env.REMOTE);
698         try {
699             Future<Artifacts> acf = aafcon.client(CM_VER)
700                     .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
701             if (acf.get(TIMEOUT)) {
702                 // Have to wait for JDK 1.7 source...
703                 //switch(artifact.getType()) {
704                 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
705                     AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
706                 } else {
707                     String id = aafcon.defID();
708                     boolean allowed;
709                     for (Artifact a : acf.value.getArtifact()) {
710                         allowed = id!=null && (id.equals(a.getSponsor()) ||
711                                 (id.equals(a.getMechid()) 
712                                         && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
713                         if (!allowed) {
714                             Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" + 
715                                     a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
716                             if (pf.get(TIMEOUT)) {
717                                 allowed = true;
718                             } else {
719                                 trans.error().log(errMsg.toMsg(pf));
720                             }
721                         }
722                         if (allowed) {
723                             File dir = new File(a.getDir());
724                             Properties props = new Properties();
725                             FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
726                             try {
727                                 props.load(fis);
728                                 File chalFile = new File(dir,a.getNs()+".chal");
729                                 if(chalFile.exists()) {
730                                     fis.close();
731                                         fis = new FileInputStream(chalFile);
732                                         props.load(fis);
733                                 }
734                             } finally {
735                                 fis.close();
736                             }
737                             
738                             File f = new File(dir,a.getNs()+".keyfile");
739                             if (f.exists()) {
740                                 Symm symm = ArtifactDir.getSymm(f);
741                                 
742                                 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
743                                     Entry<Object,Object> en = iter.next();
744                                     if (en.getValue().toString().startsWith("enc:")) {
745                                         System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
746                                     }
747                                 }
748                             } else {
749                                 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
750                                         f.getAbsolutePath(),a.getMechid(), a.getMachine());
751                             }
752                         }
753                     }
754                 }
755             } else {
756                 trans.error().log(errMsg.toMsg(acf));
757             }
758         } finally {
759             tt.done();
760         }
761
762     }
763     
764     private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
765         final String fqi = fqi(cmds);
766         final String ns = FQI.reverseDomain(fqi);
767         File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
768         File f = new File(dir,ns+".key");
769         
770         if (f.exists()) {
771             String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
772             if (!"Y".equalsIgnoreCase(line)) {
773                 System.out.println("Canceling...");
774                 return;
775             }
776         }
777         
778         KeyPair kp = Factory.generateKeyPair(trans);
779         ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
780         System.out.printf("Wrote %s\n", f.getCanonicalFile());
781
782         f=new File(dir,ns+".pubkey");
783         ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
784         System.out.printf("Wrote %s\n", f.getCanonicalFile());
785     }
786     
787     private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
788         TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
789         try {
790                 final String fqi = fqi(cmds);
791                 Artifact arti = new Artifact();
792                 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, "."));
793                 arti.setNs(FQI.reverseDomain(fqi));
794             PropHolder loc = PropHolder.get(arti, "location.props");
795             PropHolder cred = PropHolder.get(arti,"cred.props");
796             PropHolder app= PropHolder.get(arti,"props");
797             for(String c : args) {
798                 int idx = c.indexOf('=');
799                 if(idx>0) {
800                         app.add(c.substring(0,idx), c.substring(idx+1));
801                 }
802             }
803             app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
804
805             for (String tag : LOC_TAGS) {
806                 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
807             }
808             
809             cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
810             final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
811             if(fqi.equals(ssoAppID)) {
812                 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
813             // only Ask for Password when starting scratch
814             } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
815                 char[] pwd = AAFSSO.cons.readPassword("Password for %s: ", fqi);
816                 if(pwd.length>0) {
817                         cred.addEnc(Config.AAF_APPPASS, new String(pwd));
818                 }
819             }
820             
821             // load all properties that are already setup.
822             Map<String, String> aaf_urls = loadURLs(propAccess);
823             for(Entry<String, String> es : aaf_urls.entrySet()) {
824                 app.add(es.getKey(), es.getValue());
825             }
826             
827             app.add(Config.AAF_LOCATE_URL, propAccess, null);
828             for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
829                 String key = aaf_loc_prop.getKey().toString();
830                 if("aaf_env".equals(key) || key.startsWith("aaf_locator")) {
831                         app.add(key, aaf_loc_prop.getValue().toString());
832                 }
833             }
834             
835             app.add(Config.AAF_APPID, fqi);
836
837             String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
838             System.out.println("Passed in Truststore is " + cts);
839             if (cts!=null) {
840                 File origTruststore = new File(cts);
841                 File newTruststore = new File(app.getDir(),origTruststore.getName());
842                 if(!newTruststore.exists()) {
843                         if (!origTruststore.exists()) {
844                             // Try same directory as cadi_prop_files
845                             String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
846                             if (cpf!=null) {
847                                 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
848                                     File fcpf = new File(f);
849                                     if (fcpf.exists()) {
850                                         int lastSep = cts.lastIndexOf(File.pathSeparator);
851                                         origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
852                                         if (origTruststore.exists()) { 
853                                             break;
854                                         }
855                                     }
856                                 }
857                                 if (!origTruststore.exists()) {
858                                     throw new CadiException(cts + " does not exist");
859                                 }
860                             }
861                             
862                         }
863                         if (!newTruststore.exists() && origTruststore.exists()) {
864                             Files.copy(origTruststore.toPath(), newTruststore.toPath());
865                         }
866                 }
867
868                 System.out.println("New Truststore is " + newTruststore);
869                 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
870                 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
871                     
872                 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
873                 if (cpf!=null){
874                         String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf); 
875                     for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
876                         String f = propFiles[pfi];
877                         System.out.format("Reading %s\n",f);
878                         FileInputStream fis = new FileInputStream(f); 
879                         try {
880                             Properties props = new Properties();
881                             props.load(fis);
882                             for (Entry<Object, Object> prop : props.entrySet()) {
883                                 boolean lower = true;
884                                 String key = prop.getKey().toString();
885                                 if(LOC_TAGS.contains(key)) {
886                                         break;
887                                 }
888                                 for(int i=0;lower && i<key.length();++i) {
889                                         if(Character.isUpperCase(key.charAt(i))) {
890                                                 lower = false;
891                                         }
892                                 }
893                                 if(lower) {
894                                         PropHolder ph = CRED_TAGS.contains(key)?cred:app;
895                                         if(key.endsWith("_password")) {
896                                                 ph.addEnc(key, prop.getValue().toString());
897                                         } else {
898                                                 ph.add(key, prop.getValue().toString());
899                                         }
900                                 }
901                             }
902                         } finally {
903                             fis.close();
904                         }
905                     }
906                 } else {
907                     aafcon = aafcon(propAccess);
908                     if (aafcon!=null) { // get Properties from Remote AAF
909                         final String locator = getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
910
911                         Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
912                                 .read("/configure/"+fqi+"/aaf", configDF);
913                         if (acf.get(TIMEOUT)) {
914                             for (Props props : acf.value.getProps()) {
915                                 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
916                                 if(props.getTag().endsWith("_password")) {
917                                         ph.addEnc(props.getTag(), props.getValue());
918                                 } else {
919                                         ph.add(props.getTag(), props.getValue());
920                                 }
921                             }
922                         } else if (acf.code()==401){
923                             trans.error().log("Bad Password sent to AAF");
924                         } else if (acf.code()==404){
925                             trans.error().log("This version of AAF does not support remote Properties");
926                         } else {
927                             trans.error().log(errMsg.toMsg(acf));
928                         }
929                     }
930                 }
931             }
932             
933             PropHolder.writeAll();
934         } finally {
935             tt.done();
936         }
937     }
938
939
940     private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
941         System.out.println("Validating Configuration...");
942         final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
943         aafcon.best(new Retryable<Void>() {
944             @Override
945             public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
946                 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
947                 if (fc.get(aafcon.timeout)) {
948                     System.out.print("Success connecting to ");
949                     System.out.println(client.getURI());
950                     System.out.print("   Permissions for ");
951                     System.out.println(aafcon.defID());
952                     for (Perm p : fc.value.getPerm()) {
953                         System.out.print('\t');
954                         System.out.print(p.getType());
955                         System.out.print('|');
956                         System.out.print(p.getInstance());
957                         System.out.print('|');
958                         System.out.println(p.getAction());
959                     }
960                 } else {
961                     System.err.println("Error: " + fc.code() + ' ' + fc.body());
962                 }
963                 return null;
964             }
965         });
966     }
967
968     /**
969      * Check returns Error Codes, so that Scripts can know what to do
970      * 
971      *   0 - Check Complete, nothing to do
972      *   1 - General Error
973      *   2 - Error for specific Artifact - read check.msg
974      *   10 - Certificate Updated - check.msg is email content
975      *   
976      * @param trans
977      * @param aafcon
978      * @param cmds
979      * @return
980      * @throws Exception
981      */
982     private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
983         int exitCode=1;
984         String mechID = fqi(cmds);
985         String machine = machine(cmds);
986         
987         TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
988         try {
989         
990             Future<Artifacts> acf = aafcon.client(CM_VER)
991                     .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
992             if (acf.get(TIMEOUT)) {
993                 // Have to wait for JDK 1.7 source...
994                 //switch(artifact.getType()) {
995                 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
996                     AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
997                 } else {
998                     String id = aafcon.defID();
999                     GregorianCalendar now = new GregorianCalendar();
1000                     for (Artifact a : acf.value.getArtifact()) {
1001                         if (id.equals(a.getMechid())) {
1002                             File dir = new File(a.getDir());
1003                             Properties props = new Properties();
1004                             FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1005                             try {
1006                                 props.load(fis);
1007                             } finally {
1008                                 fis.close();
1009                             }
1010                             
1011                             String prop;                        
1012                             File f;
1013     
1014                             if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1015                                 !(f=new File(prop)).exists()) {
1016                                     trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1017                                         a.getMechid(), a.getMachine());
1018                             } else {
1019                                 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1020                                 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1021                                 if (ksf==null || ksps == null) {
1022                                     trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1023                                             Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1024                                 } else {
1025                                     Symm symm = ArtifactDir.getSymm(f);
1026
1027                                     KeyStore ks = KeyStore.getInstance("JKS");
1028                                     
1029                                     fis = new FileInputStream(ksf);
1030                                     try {
1031                                         ks.load(fis,symm.depass(ksps).toCharArray());
1032                                     } finally {
1033                                         fis.close();
1034                                     }
1035                                     X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1036                                     String msg = null;
1037
1038                                     if (cert==null) {
1039                                         msg = String.format("X509Certificate does not exist for %s on %s in %s",
1040                                                 a.getMechid(), a.getMachine(), ksf);
1041                                         trans.error().log(msg);
1042                                         exitCode = 2;
1043                                     } else {
1044                                         GregorianCalendar renew = new GregorianCalendar();
1045                                         renew.setTime(cert.getNotAfter());
1046                                         renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1047                                         if (renew.after(now)) {
1048                                             msg = String.format("X509Certificate for %s on %s has been checked on %s. It expires on %s; it will not be renewed until %s.\n", 
1049                                                     a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1050                                             trans.info().log(msg);
1051                                             exitCode = 0; // OK
1052                                         } else {
1053                                             trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n", 
1054                                                     a.getMechid(), a.getMachine(),cert.getNotAfter());
1055                                             cmds.offerLast(mechID);
1056                                             cmds.offerLast(machine);
1057                                             if (placeCerts(trans,aafcon,cmds)) {
1058                                                 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n", 
1059                                                         a.getMechid(), a.getMachine());
1060                                                 exitCode = 10; // Refreshed
1061                                             } else {
1062                                                 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n", 
1063                                                         a.getMechid(), a.getMachine());
1064                                                 exitCode = 1; // Error Renewing
1065                                             }
1066                                         }
1067                                     }
1068                                     if (msg!=null) {
1069                                         FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1070                                         try {
1071                                             fos.write(msg.getBytes());
1072                                         } finally {
1073                                             fos.close();
1074                                         }
1075                                     }
1076                                 }
1077                                 
1078                             }
1079                         }
1080                     }
1081                 }
1082             } else {
1083                 trans.error().log(errMsg.toMsg(acf));
1084                 exitCode=1;
1085             }
1086         } finally {
1087             tt.done();
1088         }
1089         return exitCode;
1090     }
1091
1092 }
1093             
1094         
1095
1096