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