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