2 * ============LICENSE_START====================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
22 package org.onap.aaf.cadi.cm;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.PrintStream;
28 import java.net.ConnectException;
29 import java.net.InetAddress;
30 import java.net.UnknownHostException;
31 import java.nio.file.Files;
32 import java.security.KeyStore;
33 import java.security.cert.X509Certificate;
34 import java.util.ArrayDeque;
35 import java.util.Date;
36 import java.util.Deque;
37 import java.util.GregorianCalendar;
38 import java.util.HashMap;
39 import java.util.Iterator;
41 import java.util.Map.Entry;
42 import java.util.Properties;
44 import org.onap.aaf.cadi.CadiException;
45 import org.onap.aaf.cadi.CmdLine;
46 import org.onap.aaf.cadi.LocatorException;
47 import org.onap.aaf.cadi.PropAccess;
48 import org.onap.aaf.cadi.Symm;
49 import org.onap.aaf.cadi.aaf.client.ErrMessage;
50 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
51 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
52 import org.onap.aaf.cadi.client.Future;
53 import org.onap.aaf.cadi.client.Rcli;
54 import org.onap.aaf.cadi.client.Retryable;
55 import org.onap.aaf.cadi.config.Config;
56 import org.onap.aaf.cadi.http.HBasicAuthSS;
57 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
58 import org.onap.aaf.cadi.sso.AAFSSO;
59 import org.onap.aaf.cadi.util.FQI;
60 import org.onap.aaf.misc.env.APIException;
61 import org.onap.aaf.misc.env.Data.TYPE;
62 import org.onap.aaf.misc.env.Env;
63 import org.onap.aaf.misc.env.TimeTaken;
64 import org.onap.aaf.misc.env.Trans;
65 import org.onap.aaf.misc.env.util.Chrono;
66 import org.onap.aaf.misc.env.util.Split;
67 import org.onap.aaf.misc.rosetta.env.RosettaDF;
68 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
71 import aaf.v2_0.Perms;
72 import certman.v1_0.Artifacts;
73 import certman.v1_0.Artifacts.Artifact;
74 import certman.v1_0.CertInfo;
75 import certman.v1_0.CertificateRequest;
76 import locate.v1_1.Configuration;
77 import locate.v1_1.Configuration.Props;
79 public class CmAgent {
80 private static final String HASHES = "######################";
81 private static final String PRINT = "print";
82 private static final String FILE = "file";
83 private static final String PKCS12 = "pkcs12";
84 private static final String JKS = "jks";
85 private static final String SCRIPT="script";
87 private static final String CM_VER = "1.0";
88 public static final int PASS_SIZE = 24;
89 private static int TIMEOUT;
91 private static RosettaDF<CertificateRequest> reqDF;
92 private static RosettaDF<CertInfo> certDF;
93 private static RosettaDF<Artifacts> artifactsDF;
94 private static RosettaDF<Configuration> configDF;
95 private static RosettaDF<Perms> permDF;
96 private static ErrMessage errMsg;
97 private static Map<String,PlaceArtifact> placeArtifact;
98 private static RosettaEnv env;
100 private static boolean doExit;
102 public static void main(String[] args) {
106 AAFSSO aafsso = new AAFSSO(args, new AAFSSO.ProcessArgs() {
108 public Properties process(String[] args, Properties props) {
110 if(args[0].equals("validate")) {
111 props.put(Config.CADI_PROP_FILES, args[1]);
112 } else if (!args[0].equals("genkeypair")) {
113 props.put("aaf_id", args[1]);
119 if(aafsso.loginOnly()) {
120 aafsso.setLogDefault();
122 System.out.println("AAF SSO information created in ~/.aaf");
124 PropAccess access = aafsso.access();
125 env = new RosettaEnv(access.getProperties());
126 Deque<String> cmds = new ArrayDeque<String>();
127 for(String p : args) {
128 if("-noexit".equalsIgnoreCase(p)) {
130 } else if(p.indexOf('=') < 0) {
136 aafsso.setLogDefault();
137 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
138 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
139 System.out.println(" create <FQI> [<machine>]");
140 System.out.println(" read <FQI> [<machine>]");
141 System.out.println(" update <FQI> [<machine>]");
142 System.out.println(" delete <FQI> [<machine>]");
143 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
144 System.out.println(" place <FQI> [<machine>]");
145 System.out.println(" showpass <FQI> [<machine>]");
146 System.out.println(" check <FQI> [<machine>]");
147 System.out.println(" config <FQI>");
148 System.out.println(" validate <cadi.props>");
149 System.out.println(" genkeypair");
155 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
157 reqDF = env.newDataFactory(CertificateRequest.class);
158 artifactsDF = env.newDataFactory(Artifacts.class);
159 certDF = env.newDataFactory(CertInfo.class);
160 configDF = env.newDataFactory(Configuration.class);
161 permDF = env.newDataFactory(Perms.class);
162 errMsg = new ErrMessage(env);
164 placeArtifact = new HashMap<String,PlaceArtifact>();
165 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
166 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
167 placeArtifact.put(FILE, new PlaceArtifactInFiles());
168 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
169 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
171 Trans trans = env.newTrans();
173 if((token=access.getProperty("oauth_token"))!=null) {
174 trans.setProperty("oauth_token", token);
177 // show Std out again
178 aafsso.setLogDefault();
179 aafsso.setStdErrDefault();
181 // if CM_URL can be obtained, add to sso.props, if written
182 String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": ");
184 aafsso.addProp(Config.CM_URL, cm_url);
188 AAFCon<?> aafcon = new AAFConHttp(access,Config.CM_URL);
190 String cmd = cmds.removeFirst();
193 placeCerts(trans,aafcon,cmds);
196 createArtifact(trans, aafcon,cmds);
199 readArtifact(trans, aafcon, cmds);
202 copyArtifact(trans, aafcon, cmds);
205 updateArtifact(trans, aafcon, cmds);
208 deleteArtifact(trans, aafcon, cmds);
211 showPass(trans, aafcon, cmds);
214 initConfig(trans,access,aafcon,cmds);
217 validate(aafsso,aafcon);
221 exitCode = check(trans,aafcon,cmds);
222 } catch (Exception e) {
228 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
231 StringBuilder sb = new StringBuilder();
232 trans.auditTrail(4, sb, Trans.REMOTE);
234 trans.info().log("Trans Info\n",sb);
239 } catch (Exception e) {
242 if(exitCode != 0 && doExit) {
243 System.exit(exitCode);
247 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
249 if((value=pa.getProperty(tag))==null) {
251 value = new String(AAFSSO.cons.readPassword(prompt, def));
253 value = AAFSSO.cons.readLine(prompt,def).trim();
256 if(value.length()>0) {
257 pa.setProperty(tag,value);
258 env.setProperty(tag,value);
259 } else if(def.length==1) {
260 value=def[0].toString();
261 pa.setProperty(tag,value);
262 env.setProperty(tag,value);
269 private static String fqi(Deque<String> cmds) {
271 String alias = env.getProperty(Config.CADI_ALIAS);
272 return alias!=null?alias:AAFSSO.cons.readLine("MechID: ");
274 return cmds.removeFirst();
277 private static String machine(Deque<String> cmds) throws UnknownHostException {
279 return cmds.removeFirst();
281 String mach = env.getProperty(Config.HOSTNAME);
282 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
286 private static String[] machines(Deque<String> cmds) {
289 machines = cmds.removeFirst();
291 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
293 return Split.split(',', machines);
296 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
297 String mechID = fqi(cmds);
298 String machine = machine(cmds);
300 Artifacts artifacts = new Artifacts();
301 Artifact arti = new Artifact();
302 artifacts.getArtifact().add(arti);
303 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("MechID: "));
304 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
305 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
307 String resp = AAFSSO.cons.readLine("Types [file,jks,script] (%s): ", "jks");
308 for(String s : Split.splitTrim(',', resp)) {
309 arti.getType().add(s);
312 if(!resp.contains(SCRIPT)) {
313 arti.getType().add(SCRIPT);
316 // Note: Sponsor is set on Creation by CM
317 String configRootName = FQI.reverseDomain(arti.getMechid());
318 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
319 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
320 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
321 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
322 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
324 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
326 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
327 if(future.get(TIMEOUT)) {
328 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
330 trans.error().printf("Call to AAF Certman failed, %s",
331 errMsg.toMsg(future));
338 private static String toNotification(String notification) {
339 if(notification==null) {
341 } else if(notification.length()>0) {
342 if(notification.indexOf(':')<0) {
343 notification = "mailto:" + notification;
350 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
351 String mechID = fqi(cmds);
352 String machine = machine(cmds);
354 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
356 Future<Artifacts> future = aafcon.client(CM_VER)
357 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
359 if(future.get(TIMEOUT)) {
360 boolean printed = false;
361 for(Artifact a : future.value.getArtifact()) {
362 AAFSSO.cons.printf("MechID: %s\n",a.getMechid());
363 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
364 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
365 AAFSSO.cons.printf("CA: %s\n",a.getCa());
366 StringBuilder sb = new StringBuilder();
367 boolean first = true;
368 for(String t : a.getType()) {
369 if(first) {first=false;}
370 else{sb.append(',');}
373 AAFSSO.cons.printf("Types: %s\n",sb);
374 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
375 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
376 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
377 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
378 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
382 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
385 trans.error().log(errMsg.toMsg(future));
392 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
393 String mechID = fqi(cmds);
394 String machine = machine(cmds);
395 String[] newmachs = machines(cmds);
396 if(machine==null || newmachs == null) {
397 trans.error().log("No machines listed to copy to");
399 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
401 Future<Artifacts> future = aafcon.client(CM_VER)
402 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
404 if(future.get(TIMEOUT)) {
405 boolean printed = false;
406 for(Artifact a : future.value.getArtifact()) {
407 for(String m : newmachs) {
409 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
410 if(fup.get(TIMEOUT)) {
411 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
413 trans.error().printf("Call to AAF Certman failed, %s",
421 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
424 trans.error().log(errMsg.toMsg(future));
432 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
433 String mechID = fqi(cmds);
434 String machine = machine(cmds);
436 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
438 Future<Artifacts> fread = aafcon.client(CM_VER)
439 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
441 if(fread.get(TIMEOUT)) {
442 Artifacts artifacts = new Artifacts();
443 for(Artifact a : fread.value.getArtifact()) {
444 Artifact arti = new Artifact();
445 artifacts.getArtifact().add(arti);
447 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
448 arti.setMechid(a.getMechid());
449 arti.setMachine(a.getMachine());
450 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
451 StringBuilder sb = new StringBuilder();
452 boolean first = true;
453 for(String t : a.getType()) {
454 if(first) {first=false;}
455 else{sb.append(',');}
459 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
460 for(String s : Split.splitTrim(',', resp)) {
461 arti.getType().add(s);
464 if(!resp.contains(SCRIPT)) {
465 arti.getType().add(SCRIPT);
468 // Note: Sponsor is set on Creation by CM
469 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
470 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
471 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
472 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
473 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
476 if(artifacts.getArtifact().size()==0) {
477 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
479 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
480 if(fup.get(TIMEOUT)) {
481 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
483 trans.error().printf("Call to AAF Certman failed, %s",
488 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
489 errMsg.toMsg(fread),mechID,machine);
496 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
497 String mechid = fqi(cmds);
498 String machine = machine(cmds);
500 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
502 Future<Void> future = aafcon.client(CM_VER)
503 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
505 if(future.get(TIMEOUT)) {
506 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
508 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
509 errMsg.toMsg(future),mechid,machine);
518 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
520 String mechID = fqi(cmds);
521 String machine = machine(cmds);
522 String[] fqdns = Split.split(':', machine);
531 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
533 Future<Artifacts> acf = aafcon.client(CM_VER)
534 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
535 if(acf.get(TIMEOUT)) {
536 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
537 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
539 for(Artifact a : acf.value.getArtifact()) {
540 String osID = System.getProperty("user.name");
541 if(a.getOsUser().equals(osID)) {
542 CertificateRequest cr = new CertificateRequest();
543 cr.setMechid(a.getMechid());
544 cr.setSponsor(a.getSponsor());
545 for(int i=0;i<fqdns.length;++i) {
546 cr.getFqdns().add(fqdns[i]);
548 Future<String> f = aafcon.client(CM_VER)
549 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
551 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
552 for(String type : a.getType()) {
553 PlaceArtifact pa = placeArtifact.get(type);
555 if(rv = pa.place(trans, capi, a,machine)) {
560 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
562 trans.error().log(errMsg.toMsg(f));
565 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
570 trans.error().log(errMsg.toMsg(acf));
578 private static void notifyPlaced(Artifact a, boolean rv) {
581 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
582 String mechID = fqi(cmds);
583 String machine = machine(cmds);
585 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
587 Future<Artifacts> acf = aafcon.client(CM_VER)
588 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
589 if(acf.get(TIMEOUT)) {
590 // Have to wait for JDK 1.7 source...
591 //switch(artifact.getType()) {
592 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
593 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
595 String id = aafcon.defID();
597 for(Artifact a : acf.value.getArtifact()) {
598 allowed = id!=null && (id.equals(a.getSponsor()) ||
599 (id.equals(a.getMechid())
600 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
602 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
603 a.getNs() + ".certman|"+a.getCa()+"|showpass","*/*");
604 if(pf.get(TIMEOUT)) {
607 trans.error().log(errMsg.toMsg(pf));
611 File dir = new File(a.getDir());
612 Properties props = new Properties();
613 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
617 fis = new FileInputStream(new File(dir,a.getNs()+".chal"));
623 File f = new File(dir,a.getNs()+".keyfile");
625 Symm symm = Symm.obtain(f);
627 for(Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
628 Entry<Object,Object> en = iter.next();
629 if(en.getValue().toString().startsWith("enc:")) {
630 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
634 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
635 f.getAbsolutePath(),a.getMechid(), a.getMachine());
641 trans.error().log(errMsg.toMsg(acf));
650 private static void initConfig(Trans trans, PropAccess pa, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
651 final String fqi = fqi(cmds);
652 final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
653 final String rootFile = FQI.reverseDomain(fqi);
654 final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, "."));
656 System.out.println("Writing to " + dir.getCanonicalFile());
657 } else if(dir.mkdirs()) {
658 System.out.println("Created directory " + dir.getCanonicalFile());
660 System.err.println("Unable to create or write to " + dir.getCanonicalPath());
664 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
667 File fprops = File.createTempFile(rootFile, ".tmp",dir);
668 PrintStream out = new PrintStream(new FileOutputStream(fprops));
670 out.print("# Configuration File generated on ");
671 out.println(new Date().toString());
674 File fkf = new File(dir,rootFile+".keyfile");
676 CmdLine.main(new String[] {"keygen",fkf.toString()});
678 out.print("cadi_keyfile=");
679 out.println(fkf.getCanonicalPath());
681 out.print(Config.AAF_APPID);
685 Symm filesymm = Symm.obtain(fkf);
686 out.print(Config.AAF_APPPASS);
688 String ps = pa.decrypt(pa.getProperty(Config.AAF_APPPASS), false);
689 ps = filesymm.enpass(ps);
692 out.print(Config.CADI_TRUSTSTORE);
694 File origTruststore = new File(pa.getProperty(Config.CADI_TRUSTSTORE));
695 File newTruststore = new File(dir,origTruststore.getName());
696 if(!newTruststore.exists()) {
697 Files.copy(origTruststore.toPath(), newTruststore.toPath());
699 out.println(newTruststore.getCanonicalPath());
701 out.print(Config.CADI_TRUSTSTORE_PASSWORD);
703 ps = pa.decrypt(pa.getProperty(Config.CADI_TRUSTSTORE_PASSWORD), false);
704 ps = filesymm.enpass(ps);
709 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
710 .read("/configure/"+fqi+"/aaf", configDF);
711 if(acf.get(TIMEOUT)) {
712 // out.println(acf.value.getName());
713 for(Props props : acf.value.getProps()) {
714 out.println(props.getTag() + '=' + props.getValue());
717 } else if(acf.code()==401){
718 trans.error().log("Bad Password sent to AAF");
720 trans.error().log(errMsg.toMsg(acf));
726 File newFile = new File(dir,rootFile+".common.props");
727 fprops.renameTo(newFile);
728 System.out.println("Created " + newFile.getCanonicalPath());
738 private static void validate(final AAFSSO aafsso, final AAFCon<?> aafcon) throws LocatorException, CadiException, APIException {
739 System.out.println("Validating Configuration...");
740 aafcon.clone(aafsso.access().getProperty(Config.AAF_URL)).best(new Retryable<Void>() {
742 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
743 Future<Perms> fc = client.read("/authz/perms/user/"+aafsso.user(),permDF);
744 if(fc.get(aafcon.timeout)) {
745 System.out.print("Success connecting to ");
746 System.out.println(client.getURI());
747 System.out.print(" Permissions for ");
748 System.out.println(aafsso.user());
749 for(Perm p : fc.value.getPerm()) {
750 System.out.print('\t');
751 System.out.print(p.getType());
752 System.out.print('|');
753 System.out.print(p.getInstance());
754 System.out.print('|');
755 System.out.println(p.getAction());
758 System.err.println("Error: " + fc.code() + ' ' + fc.body());
766 * Check returns Error Codes, so that Scripts can know what to do
768 * 0 - Check Complete, nothing to do
770 * 2 - Error for specific Artifact - read check.msg
771 * 10 - Certificate Updated - check.msg is email content
779 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
781 String mechID = fqi(cmds);
782 String machine = machine(cmds);
784 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
787 Future<Artifacts> acf = aafcon.client(CM_VER)
788 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
789 if(acf.get(TIMEOUT)) {
790 // Have to wait for JDK 1.7 source...
791 //switch(artifact.getType()) {
792 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
793 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
795 String id = aafcon.defID();
796 GregorianCalendar now = new GregorianCalendar();
797 for(Artifact a : acf.value.getArtifact()) {
798 if(id.equals(a.getMechid())) {
799 File dir = new File(a.getDir());
800 Properties props = new Properties();
801 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
811 if((prop=props.getProperty(Config.CADI_KEYFILE))==null ||
812 !(f=new File(prop)).exists()) {
813 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
814 a.getMechid(), a.getMachine());
816 String ksf = props.getProperty(Config.CADI_KEYSTORE);
817 String ksps = props.getProperty(Config.CADI_KEYSTORE_PASSWORD);
818 if(ksf==null || ksps == null) {
819 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
820 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
822 KeyStore ks = KeyStore.getInstance("JKS");
823 Symm symm = Symm.obtain(f);
825 fis = new FileInputStream(ksf);
827 ks.load(fis,symm.depass(ksps).toCharArray());
831 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
835 msg = String.format("X509Certificate does not exist for %s on %s in %s",
836 a.getMechid(), a.getMachine(), ksf);
837 trans.error().log(msg);
840 GregorianCalendar renew = new GregorianCalendar();
841 renew.setTime(cert.getNotAfter());
842 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
843 if(renew.after(now)) {
844 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",
845 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
846 trans.info().log(msg);
849 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
850 a.getMechid(), a.getMachine(),cert.getNotAfter());
851 cmds.offerLast(mechID);
852 cmds.offerLast(machine);
853 if(placeCerts(trans,aafcon,cmds)) {
854 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
855 a.getMechid(), a.getMachine());
856 exitCode = 10; // Refreshed
858 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
859 a.getMechid(), a.getMachine());
860 exitCode = 1; // Error Renewing
865 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
867 fos.write(msg.getBytes());
879 trans.error().log(errMsg.toMsg(acf));