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