bdd95a779f607d83e88b808f751cb9910a178e6e
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / cm / CmAgent.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.cm;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.net.InetAddress;
28 import java.net.UnknownHostException;
29 import java.security.KeyStore;
30 import java.security.cert.X509Certificate;
31 import java.util.ArrayDeque;
32 import java.util.Deque;
33 import java.util.GregorianCalendar;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.Map;
37 import java.util.Map.Entry;
38
39 import org.onap.aaf.cadi.PropAccess;
40 import org.onap.aaf.cadi.Symm;
41 import org.onap.aaf.cadi.aaf.client.ErrMessage;
42 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
43 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
44 import org.onap.aaf.cadi.client.Future;
45 import org.onap.aaf.cadi.config.Config;
46 import org.onap.aaf.cadi.http.HBasicAuthSS;
47 import org.onap.aaf.cadi.sso.AAFSSO;
48 import org.onap.aaf.cadi.util.FQI;
49 import org.onap.aaf.misc.env.Env;
50 import org.onap.aaf.misc.env.TimeTaken;
51 import org.onap.aaf.misc.env.Trans;
52 import org.onap.aaf.misc.env.Data.TYPE;
53 import org.onap.aaf.misc.env.util.Chrono;
54 import org.onap.aaf.misc.env.util.Split;
55 import org.onap.aaf.misc.rosetta.env.RosettaDF;
56 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
57
58 import java.util.Properties;
59
60 import certman.v1_0.Artifacts;
61 import certman.v1_0.Artifacts.Artifact;
62 import certman.v1_0.CertInfo;
63 import certman.v1_0.CertificateRequest;
64
65 public class CmAgent {
66         private static final String PRINT = "print";
67         private static final String FILE = "file";
68         private static final String PKCS12 = "pkcs12";
69         private static final String JKS = "jks";
70         private static final String SCRIPT="script";
71         
72         private static final String CM_VER = "1.0";
73         public static final int PASS_SIZE = 24;
74         private static int TIMEOUT;
75         
76         private static RosettaDF<CertificateRequest> reqDF;
77         private static RosettaDF<CertInfo> certDF;
78         private static RosettaDF<Artifacts> artifactsDF;
79         private static ErrMessage errMsg;
80         private static Map<String,PlaceArtifact> placeArtifact;
81         private static RosettaEnv env;
82         
83         private static boolean doExit;
84
85         public static void main(String[] args) {
86                 int exitCode = 0;
87                 doExit = true;
88                 try {
89                         AAFSSO aafsso = new AAFSSO(args);
90                         if(aafsso.loginOnly()) {
91                                 aafsso.setLogDefault();
92                                 aafsso.writeFiles();
93                                 System.out.println("AAF SSO information created in ~/.aaf");
94                         } else {
95                                 PropAccess access = aafsso.access();
96                                 env = new RosettaEnv(access.getProperties());
97                                 Deque<String> cmds = new ArrayDeque<String>();
98                                 for(String p : args) {
99                                         if("-noexit".equalsIgnoreCase(p)) {
100                                                 doExit = false;
101                                         } else if(p.indexOf('=') < 0) {
102                                                 cmds.add(p);
103                                         }
104                                 }
105                                 
106                                 if(cmds.size()==0) {
107                                         aafsso.setLogDefault();
108                                         System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
109                                         System.out.println("   create   <mechID> [<machine>]");
110                                         System.out.println("   read     <mechID> [<machine>]");
111                                         System.out.println("   update   <mechID> [<machine>]");
112                                         System.out.println("   delete   <mechID> [<machine>]");
113                                         System.out.println("   copy     <mechID> <machine> <newmachine>[,<newmachine>]*");
114                                         System.out.println("   place    <mechID> [<machine>]");
115                                         System.out.println("   showpass <mechID> [<machine>]");
116                                         System.out.println("   check    <mechID> [<machine>]");
117                                         System.out.println("   genkeypair");
118                                         if (doExit) {
119                                                 System.exit(1);
120                                         }
121                                 }
122                                 
123                                 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
124                         
125                                 reqDF = env.newDataFactory(CertificateRequest.class);
126                                 artifactsDF = env.newDataFactory(Artifacts.class);
127                                 certDF = env.newDataFactory(CertInfo.class);
128                                 errMsg = new ErrMessage(env);
129         
130                                 placeArtifact = new HashMap<String,PlaceArtifact>();
131                                 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
132                                 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
133                                 placeArtifact.put(FILE, new PlaceArtifactInFiles());
134                                 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
135                                 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
136                                 
137                                 Trans trans = env.newTrans();
138                                 String token;
139                                 if((token=access.getProperty("oauth_token"))!=null) {
140                                         trans.setProperty("oauth_token", token);
141                                 }
142                                 try {
143                                         // show Std out again
144                                         aafsso.setLogDefault();
145                                         aafsso.setStdErrDefault();
146                                         
147                                         // if CM_URL can be obtained, add to sso.props, if written
148                                         String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": ");
149                                         if(cm_url!=null) {
150                                                 aafsso.addProp(Config.CM_URL, cm_url);
151                                         }
152                                         aafsso.writeFiles();
153
154                                         AAFCon<?> aafcon = new AAFConHttp(access,Config.CM_URL);
155
156                                         String cmd = cmds.removeFirst();
157                                         if("place".equals(cmd)) {
158                                                 placeCerts(trans,aafcon,cmds);
159                                         } else if("create".equals(cmd)) {
160                                                 createArtifact(trans, aafcon,cmds);
161                                         } else if("read".equals(cmd)) {
162                                                 readArtifact(trans, aafcon, cmds);
163                                         } else if("copy".equals(cmd)) {
164                                                 copyArtifact(trans, aafcon, cmds);
165                                         } else if("update".equals(cmd)) {
166                                                 updateArtifact(trans, aafcon, cmds);
167                                         } else if("delete".equals(cmd)) {
168                                                 deleteArtifact(trans, aafcon, cmds);
169                                         } else if("showpass".equals(cmd)) {
170                                                 showPass(trans,aafcon,cmds);
171                                         } else if("check".equals(cmd)) {
172                                                 try {
173                                                         exitCode = check(trans,aafcon,cmds);
174                                                 } catch (Exception e) {
175                                                         exitCode = 1;
176                                                         throw e;
177                                                 }
178                                         } else {
179                                                 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
180                                         }
181                                 } finally {
182                                         StringBuilder sb = new StringBuilder();
183                         trans.auditTrail(4, sb, Trans.REMOTE);
184                         if(sb.length()>0) {
185                                 trans.info().log("Trans Info\n",sb);
186                         }
187                                 }
188                                 aafsso.close();
189                         }
190                 } catch (Exception e) {
191                         e.printStackTrace();
192                 }
193                 if(exitCode != 0 && doExit) {
194                         System.exit(exitCode);
195                 }
196         }
197
198         private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
199                 String value;
200                 if((value=pa.getProperty(tag))==null) {
201                         if(secure) {
202                                 value = new String(AAFSSO.cons.readPassword(prompt, def));
203                         } else {
204                                 value = AAFSSO.cons.readLine(prompt,def).trim();
205                         }
206                         if(value!=null) {
207                                 if(value.length()>0) {
208                                         pa.setProperty(tag,value);
209                                         env.setProperty(tag,value);
210                                 } else if(def.length==1) {
211                                         value=def[0].toString();
212                                         pa.setProperty(tag,value);
213                                         env.setProperty(tag,value);
214                                 }
215                         }
216                 }
217                 return value;
218         }
219
220         private static String mechID(Deque<String> cmds) {
221                 if(cmds.size()<1) {
222                         String alias = env.getProperty(Config.CADI_ALIAS);
223                         return alias!=null?alias:AAFSSO.cons.readLine("MechID: ");
224                 }
225                 return cmds.removeFirst();      
226         }
227
228         private static String machine(Deque<String> cmds) throws UnknownHostException {
229                 if(cmds.size()>0) {
230                         return cmds.removeFirst();
231                 } else {
232                         String mach = env.getProperty(Config.HOSTNAME);
233                         return mach!=null?mach:InetAddress.getLocalHost().getHostName();
234                 }
235         }
236
237         private static String[] machines(Deque<String> cmds)  {
238                 String machines;
239                 if(cmds.size()>0) {
240                         machines = cmds.removeFirst();
241                 } else {
242                         machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
243                 }
244                 return Split.split(',', machines);
245         }
246
247         private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
248                 String mechID = mechID(cmds);
249                 String machine = machine(cmds);
250
251                 Artifacts artifacts = new Artifacts();
252                 Artifact arti = new Artifact();
253                 artifacts.getArtifact().add(arti);
254                 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("MechID: "));
255                 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
256                 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
257                 
258                 String resp = AAFSSO.cons.readLine("Types [file,jks,script] (%s): ", "jks");
259                 for(String s : Split.splitTrim(',', resp)) {
260                         arti.getType().add(s);
261                 }
262                 // Always do Script
263                 if(!resp.contains(SCRIPT)) {
264                         arti.getType().add(SCRIPT);
265                 }
266
267                 // Note: Sponsor is set on Creation by CM
268                 String configRootName = FQI.reverseDomain(arti.getMechid());
269                 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
270                 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
271                 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
272                 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
273                 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
274                 
275                 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
276                 try {
277                         Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
278                         if(future.get(TIMEOUT)) {
279                                 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
280                         } else {
281                                 trans.error().printf("Call to AAF Certman failed, %s",
282                                         errMsg.toMsg(future));
283                         }
284                 } finally {
285                         tt.done();
286                 }
287         }
288
289         private static String toNotification(String notification) {
290                 if(notification==null) {
291                         notification="";
292                 } else if(notification.length()>0) {
293                         if(notification.indexOf(':')<0) {
294                                 notification = "mailto:" + notification;
295                         }
296                 }
297                 return notification;
298         }
299         
300
301         private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
302                 String mechID = mechID(cmds);
303                 String machine = machine(cmds);
304
305                 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
306                 try {
307                         Future<Artifacts> future = aafcon.client(CM_VER)
308                                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
309         
310                         if(future.get(TIMEOUT)) {
311                                 boolean printed = false;
312                                 for(Artifact a : future.value.getArtifact()) {
313                                         AAFSSO.cons.printf("MechID:          %s\n",a.getMechid()); 
314                                         AAFSSO.cons.printf("  Sponsor:       %s\n",a.getSponsor()); 
315                                         AAFSSO.cons.printf("Machine:         %s\n",a.getMachine()); 
316                                         AAFSSO.cons.printf("CA:              %s\n",a.getCa()); 
317                                         StringBuilder sb = new StringBuilder();
318                                         boolean first = true;
319                                         for(String t : a.getType()) {
320                                                 if(first) {first=false;}
321                                                 else{sb.append(',');}
322                                                 sb.append(t);
323                                         }
324                                         AAFSSO.cons.printf("Types:           %s\n",sb);
325                                         AAFSSO.cons.printf("Namespace:       %s\n",a.getNs()); 
326                                         AAFSSO.cons.printf("Directory:       %s\n",a.getDir());
327                                         AAFSSO.cons.printf("O/S User:        %s\n",a.getOsUser());
328                                         AAFSSO.cons.printf("Renew Days:      %d\n",a.getRenewDays());
329                                         AAFSSO.cons.printf("Notification     %s\n",a.getNotification());
330                                         printed = true;
331                                 }
332                                 if(!printed) {
333                                         AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
334                                 }
335                         } else {
336                                 trans.error().log(errMsg.toMsg(future));
337                         }
338                 } finally {
339                         tt.done();
340                 }
341         }
342         
343         private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
344                 String mechID = mechID(cmds);
345                 String machine = machine(cmds);
346                 String[] newmachs = machines(cmds);
347                 if(machine==null || newmachs == null) {
348                         trans.error().log("No machines listed to copy to");
349                 } else {
350                         TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
351                         try {
352                                 Future<Artifacts> future = aafcon.client(CM_VER)
353                                                 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
354                         
355                                 if(future.get(TIMEOUT)) {
356                                         boolean printed = false;
357                                         for(Artifact a : future.value.getArtifact()) {
358                                                 for(String m : newmachs) {
359                                                         a.setMachine(m);
360                                                         Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
361                                                         if(fup.get(TIMEOUT)) {
362                                                                 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
363                                                         } else {
364                                                                 trans.error().printf("Call to AAF Certman failed, %s",
365                                                                         errMsg.toMsg(fup));
366                                                         }
367         
368                                                         printed = true;
369                                                 }
370                                         }
371                                         if(!printed) {
372                                                 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
373                                         }
374                                 } else {
375                                         trans.error().log(errMsg.toMsg(future));
376                                 }
377                         } finally {
378                                 tt.done();
379                         }
380                 }
381         }
382
383         private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
384                 String mechID = mechID(cmds);
385                 String machine = machine(cmds);
386
387                 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
388                 try {
389                         Future<Artifacts> fread = aafcon.client(CM_VER)
390                                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
391         
392                         if(fread.get(TIMEOUT)) {
393                                 Artifacts artifacts = new Artifacts();
394                                 for(Artifact a : fread.value.getArtifact()) {
395                                         Artifact arti = new Artifact();
396                                         artifacts.getArtifact().add(arti);
397                                         
398                                         AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
399                                         arti.setMechid(a.getMechid());
400                                         arti.setMachine(a.getMachine());
401                                         arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
402                                         StringBuilder sb = new StringBuilder();
403                                         boolean first = true;
404                                         for(String t : a.getType()) {
405                                                 if(first) {first=false;}
406                                                 else{sb.append(',');}
407                                                 sb.append(t);
408                                         }
409         
410                                         String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
411                                         for(String s : Split.splitTrim(',', resp)) {
412                                                 arti.getType().add(s);
413                                         }
414                                         // Always do Script
415                                         if(!resp.contains(SCRIPT)) {
416                                                 arti.getType().add(SCRIPT);
417                                         }
418
419                                         // Note: Sponsor is set on Creation by CM
420                                         arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
421                                         arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
422                                         arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
423                                         arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
424                                         arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
425         
426                                 }
427                                 if(artifacts.getArtifact().size()==0) {
428                                         AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
429                                 } else {
430                                         Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
431                                         if(fup.get(TIMEOUT)) {
432                                                 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
433                                         } else {
434                                                 trans.error().printf("Call to AAF Certman failed, %s",
435                                                         errMsg.toMsg(fup));
436                                         }
437                                 }
438                         } else {
439                                 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
440                                                 errMsg.toMsg(fread),mechID,machine);
441                         }
442                 } finally {
443                         tt.done();
444                 }
445         }
446         
447         private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
448                 String mechid = mechID(cmds);
449                 String machine = machine(cmds);
450                 
451                 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
452                 try {
453                         Future<Void> future = aafcon.client(CM_VER)
454                                         .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
455         
456                         if(future.get(TIMEOUT)) {
457                                 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
458                         } else {
459                                 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
460                                         errMsg.toMsg(future),mechid,machine);
461                         }
462                 } finally {
463                         tt.done();
464                 }
465         }
466
467         
468
469         private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
470                 boolean rv = false;
471                 String mechID = mechID(cmds);
472                 String machine = machine(cmds);
473                 String[] fqdns = Split.split(':', machine);
474                 String key;
475                 if(fqdns.length>1) {
476                         key = fqdns[0];
477                         machine = fqdns[1];
478                 } else {
479                         key = machine;
480                 }
481                 
482                 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
483                 try {
484                         Future<Artifacts> acf = aafcon.client(CM_VER)
485                                         .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
486                         if(acf.get(TIMEOUT)) {
487                                 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
488                                         AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
489                                 } else {
490                                         for(Artifact a : acf.value.getArtifact()) {
491                                                 String osID = System.getProperty("user.name");
492                                                 if(a.getOsUser().equals(osID)) {
493                                                         CertificateRequest cr = new CertificateRequest();
494                                                         cr.setMechid(a.getMechid());
495                                                         cr.setSponsor(a.getSponsor());
496                                                         for(int i=0;i<fqdns.length;++i) {
497                                                                 cr.getFqdns().add(fqdns[i]);
498                                                         }
499                                                         Future<String> f = aafcon.client(CM_VER)
500                                                                         .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
501                                                         if(f.get(TIMEOUT)) {
502                                                                 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
503                                                                 for(String type : a.getType()) {
504                                                                         PlaceArtifact pa = placeArtifact.get(type);
505                                                                         if(pa!=null) {
506                                                                                 if(rv = pa.place(trans, capi, a,machine)) {
507                                                                                         notifyPlaced(a,rv);
508                                                                                 }
509                                                                         }
510                                                                 }
511                                                                 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
512                                                         } else {
513                                                                 trans.error().log(errMsg.toMsg(f));
514                                                         }
515                                                 } else {
516                                                         trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
517                                                 }
518                                         }
519                                 }
520                         } else {
521                                 trans.error().log(errMsg.toMsg(acf));
522                         }
523                 } finally {
524                         tt.done();
525                 }
526                 return rv;
527         }
528         
529         private static void notifyPlaced(Artifact a, boolean rv) {
530         }
531
532         private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
533                 String mechID = mechID(cmds);
534                 String machine = machine(cmds);
535
536                 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
537                 try {
538                         Future<Artifacts> acf = aafcon.client(CM_VER)
539                                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
540                         if(acf.get(TIMEOUT)) {
541                                 // Have to wait for JDK 1.7 source...
542                                 //switch(artifact.getType()) {
543                                 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
544                                         AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
545                                 } else {
546                                         String id = aafcon.defID();
547                                         boolean allowed;
548                                         for(Artifact a : acf.value.getArtifact()) {
549                                                 allowed = id!=null && (id.equals(a.getSponsor()) ||
550                                                                 (id.equals(a.getMechid()) 
551                                                                                 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
552                                                 if(!allowed) {
553                                                         Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" + 
554                                                                         a.getNs() + ".certman|"+a.getCa()+"|showpass","*/*");
555                                                         if(pf.get(TIMEOUT)) {
556                                                                 allowed = true;
557                                                         } else {
558                                                                 trans.error().log(errMsg.toMsg(pf));
559                                                         }
560                                                 }
561                                                 if(allowed) {
562                                                         File dir = new File(a.getDir());
563                                                         Properties props = new Properties();
564                                                         FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
565                                                         try {
566                                                                 props.load(fis);
567                                                                 fis.close();
568                                                                 fis = new FileInputStream(new File(dir,a.getNs()+".chal"));
569                                                                 props.load(fis);
570                                                         } finally {
571                                                                 fis.close();
572                                                         }
573                                                         
574                                                         File f = new File(dir,a.getNs()+".keyfile");
575                                                         if(f.exists()) {
576                                                                 Symm symm = Symm.obtain(f);
577                                                                 
578                                                                 for(Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
579                                                                         Entry<Object,Object> en = iter.next();
580                                                                         if(en.getValue().toString().startsWith("enc:")) {
581                                                                                 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
582                                                                         }
583                                                                 }
584                                                         } else {
585                                                                 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
586                                                                                 f.getAbsolutePath(),a.getMechid(), a.getMachine());
587                                                         }
588                                                 }
589                                         }
590                                 }
591                         } else {
592                                 trans.error().log(errMsg.toMsg(acf));
593                         }
594                 } finally {
595                         tt.done();
596                 }
597
598         }
599         
600
601         /**
602          * Check returns Error Codes, so that Scripts can know what to do
603          * 
604          *   0 - Check Complete, nothing to do
605          *   1 - General Error
606          *   2 - Error for specific Artifact - read check.msg
607          *   10 - Certificate Updated - check.msg is email content
608          *   
609          * @param trans
610          * @param aafcon
611          * @param cmds
612          * @return
613          * @throws Exception
614          */
615         private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
616                 int exitCode=1;
617                 String mechID = mechID(cmds);
618                 String machine = machine(cmds);
619                 
620                 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
621                 try {
622                 
623                         Future<Artifacts> acf = aafcon.client(CM_VER)
624                                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
625                         if(acf.get(TIMEOUT)) {
626                                 // Have to wait for JDK 1.7 source...
627                                 //switch(artifact.getType()) {
628                                 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
629                                         AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
630                                 } else {
631                                         String id = aafcon.defID();
632                                         GregorianCalendar now = new GregorianCalendar();
633                                         for(Artifact a : acf.value.getArtifact()) {
634                                                 if(id.equals(a.getMechid())) {
635                                                         File dir = new File(a.getDir());
636                                                         Properties props = new Properties();
637                                                         FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
638                                                         try {
639                                                                 props.load(fis);
640                                                         } finally {
641                                                                 fis.close();
642                                                         }
643                                                         
644                                                         String prop;                                            
645                                                         File f;
646         
647                                                         if((prop=props.getProperty(Config.CADI_KEYFILE))==null ||
648                                                                 !(f=new File(prop)).exists()) {
649                                                                         trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
650                                                                                 a.getMechid(), a.getMachine());
651                                                         } else {
652                                                                 String ksf = props.getProperty(Config.CADI_KEYSTORE);
653                                                                 String ksps = props.getProperty(Config.CADI_KEYSTORE_PASSWORD);
654                                                                 if(ksf==null || ksps == null) {
655                                                                         trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
656                                                                                         Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
657                                                                 } else {
658                                                                         KeyStore ks = KeyStore.getInstance("JKS");
659                                                                         Symm symm = Symm.obtain(f);
660                                                                         
661                                                                         fis = new FileInputStream(ksf);
662                                                                         try {
663                                                                                 ks.load(fis,symm.depass(ksps).toCharArray());
664                                                                         } finally {
665                                                                                 fis.close();
666                                                                         }
667                                                                         X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
668                                                                         String msg = null;
669
670                                                                         if(cert==null) {
671                                                                                 msg = String.format("X509Certificate does not exist for %s on %s in %s",
672                                                                                                 a.getMechid(), a.getMachine(), ksf);
673                                                                                 trans.error().log(msg);
674                                                                                 exitCode = 2;
675                                                                         } else {
676                                                                                 GregorianCalendar renew = new GregorianCalendar();
677                                                                                 renew.setTime(cert.getNotAfter());
678                                                                                 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
679                                                                                 if(renew.after(now)) {
680                                                                                         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", 
681                                                                                                         a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
682                                                                                         trans.info().log(msg);
683                                                                                         exitCode = 0; // OK
684                                                                                 } else {
685                                                                                         trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n", 
686                                                                                                         a.getMechid(), a.getMachine(),cert.getNotAfter());
687                                                                                         cmds.offerLast(mechID);
688                                                                                         cmds.offerLast(machine);
689                                                                                         if(placeCerts(trans,aafcon,cmds)) {
690                                                                                                 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n", 
691                                                                                                                 a.getMechid(), a.getMachine());
692                                                                                                 exitCode = 10; // Refreshed
693                                                                                         } else {
694                                                                                                 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n", 
695                                                                                                                 a.getMechid(), a.getMachine());
696                                                                                                 exitCode = 1; // Error Renewing
697                                                                                         }
698                                                                                 }
699                                                                         }
700                                                                         if(msg!=null) {
701                                                                                 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
702                                                                                 try {
703                                                                                         fos.write(msg.getBytes());
704                                                                                 } finally {
705                                                                                         fos.close();
706                                                                                 }
707                                                                         }
708                                                                 }
709                                                                 
710                                                         }
711                                                 }
712                                         }
713                                 }
714                         } else {
715                                 trans.error().log(errMsg.toMsg(acf));
716                                 exitCode=1;
717                         }
718                 } finally {
719                         tt.done();
720                 }
721                 return exitCode;
722         }
723
724 }
725                         
726                 
727
728