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