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