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.configure;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.PrintStream;
29 import java.net.ConnectException;
30 import java.net.HttpURLConnection;
31 import java.net.InetAddress;
32 import java.net.UnknownHostException;
33 import java.nio.file.Files;
34 import java.security.KeyPair;
35 import java.security.KeyStore;
36 import java.security.cert.X509Certificate;
37 import java.util.ArrayDeque;
38 import java.util.Date;
39 import java.util.Deque;
40 import java.util.GregorianCalendar;
41 import java.util.HashMap;
42 import java.util.Iterator;
44 import java.util.Map.Entry;
45 import java.util.Properties;
47 import org.onap.aaf.cadi.CadiException;
48 import org.onap.aaf.cadi.CmdLine;
49 import org.onap.aaf.cadi.LocatorException;
50 import org.onap.aaf.cadi.PropAccess;
51 import org.onap.aaf.cadi.Symm;
52 import org.onap.aaf.cadi.aaf.client.ErrMessage;
53 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
54 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
55 import org.onap.aaf.cadi.client.Future;
56 import org.onap.aaf.cadi.client.Rcli;
57 import org.onap.aaf.cadi.client.Retryable;
58 import org.onap.aaf.cadi.config.Config;
59 import org.onap.aaf.cadi.config.SecurityInfoC;
60 import org.onap.aaf.cadi.http.HBasicAuthSS;
61 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
62 import org.onap.aaf.cadi.sso.AAFSSO;
63 import org.onap.aaf.cadi.util.Chmod;
64 import org.onap.aaf.cadi.util.FQI;
65 import org.onap.aaf.misc.env.APIException;
66 import org.onap.aaf.misc.env.Data.TYPE;
67 import org.onap.aaf.misc.env.Env;
68 import org.onap.aaf.misc.env.TimeTaken;
69 import org.onap.aaf.misc.env.Trans;
70 import org.onap.aaf.misc.env.util.Chrono;
71 import org.onap.aaf.misc.env.util.Split;
72 import org.onap.aaf.misc.rosetta.env.RosettaDF;
73 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
76 import aaf.v2_0.Perms;
77 import certman.v1_0.Artifacts;
78 import certman.v1_0.Artifacts.Artifact;
79 import certman.v1_0.CertInfo;
80 import certman.v1_0.CertificateRequest;
81 import locate.v1_1.Configuration;
82 import locate.v1_1.Configuration.Props;
85 private static final String HASHES = "################################################################";
86 private static final String PRINT = "print";
87 private static final String FILE = "file";
88 private static final String PKCS12 = "pkcs12";
89 private static final String JKS = "jks";
90 private static final String SCRIPT="script";
92 private static final String CM_VER = "1.0";
93 public static final int PASS_SIZE = 24;
94 private static int TIMEOUT;
96 private static RosettaDF<CertificateRequest> reqDF;
97 private static RosettaDF<CertInfo> certDF;
98 private static RosettaDF<Artifacts> artifactsDF;
99 private static RosettaDF<Configuration> configDF;
100 private static RosettaDF<Perms> permDF;
101 private static ErrMessage errMsg;
102 private static Map<String,PlaceArtifact> placeArtifact;
103 private static RosettaEnv env;
105 private static boolean doExit;
106 private static AAFCon<?> aafcon;
108 public static void main(String[] args) {
111 if(args.length>0 && "cadi".equals(args[0])) {
112 String[] newArgs = new String[args.length-1];
113 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
114 if(newArgs.length==0) {
115 System.out.println(HASHES);
116 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
117 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
118 System.out.println(HASHES);
120 CmdLine.main(newArgs);
126 if(args.length>0 && args[0].equals("validate")) {
127 int idx = args[1].indexOf('=');
129 access = new PropAccess(
130 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
132 (idx<0?args[1]:args[1].substring(idx+1)));
134 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
136 public Properties process(String[] args, Properties props) {
138 if (!args[0].equals("keypairgen")) {
139 props.put("aaf_id", args[1]);
145 access = aafsso.access();
148 if(aafsso!=null && aafsso.loginOnly()) {
149 aafsso.setLogDefault();
151 System.out.println("AAF SSO information created in ~/.aaf");
153 env = new RosettaEnv(access.getProperties());
154 Deque<String> cmds = new ArrayDeque<String>();
155 for(String p : args) {
156 if("-noexit".equalsIgnoreCase(p)) {
158 } else if(p.indexOf('=') < 0) {
165 aafsso.setLogDefault();
167 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
168 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
169 System.out.println(" create <FQI> [<machine>]");
170 System.out.println(" read <FQI> [<machine>]");
171 System.out.println(" update <FQI> [<machine>]");
172 System.out.println(" delete <FQI> [<machine>]");
173 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
174 System.out.println(" place <FQI> [<machine>]");
175 System.out.println(" showpass <FQI> [<machine>]");
176 System.out.println(" check <FQI> [<machine>]");
177 System.out.println(" keypairgen <FQI>");
178 System.out.println(" config <FQI>");
179 System.out.println(" validate <FQI>.props>");
180 System.out.println(" --- Additional Tool Access ---");
181 System.out.println(" ** Type with no params for Tool Help");
182 System.out.println(" ** If using with Agent, preface with \"cadi\"");
183 System.out.println(" cadi <cadi tool params, see -?>");
190 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
192 reqDF = env.newDataFactory(CertificateRequest.class);
193 artifactsDF = env.newDataFactory(Artifacts.class);
194 certDF = env.newDataFactory(CertInfo.class);
195 configDF = env.newDataFactory(Configuration.class);
196 permDF = env.newDataFactory(Perms.class);
197 errMsg = new ErrMessage(env);
199 placeArtifact = new HashMap<>();
200 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
201 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
202 placeArtifact.put(FILE, new PlaceArtifactInFiles());
203 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
204 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
206 Trans trans = env.newTrans();
208 if((token=access.getProperty("oauth_token"))!=null) {
209 trans.setProperty("oauth_token", token);
213 // show Std out again
214 aafsso.setLogDefault();
215 aafsso.setStdErrDefault();
217 // if CM_URL can be obtained, add to sso.props, if written
218 String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": ");
220 aafsso.addProp(Config.CM_URL, cm_url);
227 String cmd = cmds.removeFirst();
230 placeCerts(trans,aafcon(access),cmds);
233 createArtifact(trans, aafcon(access),cmds);
236 readArtifact(trans, aafcon(access), cmds);
239 copyArtifact(trans, aafcon(access), cmds);
242 updateArtifact(trans, aafcon(access), cmds);
245 deleteArtifact(trans, aafcon(access), cmds);
248 showPass(trans, aafcon(access), cmds);
251 keypairGen(trans, access, cmds);
254 config(trans,access,aafcon(access),cmds);
261 exitCode = check(trans,aafcon(access),cmds);
262 } catch (Exception e) {
268 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
271 StringBuilder sb = new StringBuilder();
272 trans.auditTrail(4, sb, Trans.REMOTE);
274 trans.info().log("Trans Info\n",sb);
281 } catch (Exception e) {
285 if(exitCode != 0 && doExit) {
286 System.exit(exitCode);
290 private static synchronized AAFCon<?> aafcon(PropAccess access) throws APIException, CadiException, LocatorException {
292 aafcon = new AAFConHttp(access,Config.CM_URL);
297 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
299 if((value=pa.getProperty(tag))==null) {
301 value = new String(AAFSSO.cons.readPassword(prompt, def));
303 value = AAFSSO.cons.readLine(prompt,def).trim();
306 if(value.length()>0) {
307 pa.setProperty(tag,value);
308 env.setProperty(tag,value);
309 } else if(def.length==1) {
310 value=def[0].toString();
311 pa.setProperty(tag,value);
312 env.setProperty(tag,value);
319 private static String fqi(Deque<String> cmds) {
321 String alias = env.getProperty(Config.CADI_ALIAS);
322 return alias!=null?alias:AAFSSO.cons.readLine("MechID: ");
324 return cmds.removeFirst();
327 private static String machine(Deque<String> cmds) throws UnknownHostException {
329 return cmds.removeFirst();
331 String mach = env.getProperty(Config.HOSTNAME);
332 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
336 private static String[] machines(Deque<String> cmds) {
339 machines = cmds.removeFirst();
341 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
343 return Split.split(',', machines);
346 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
347 String mechID = fqi(cmds);
348 String machine = machine(cmds);
350 Artifacts artifacts = new Artifacts();
351 Artifact arti = new Artifact();
352 artifacts.getArtifact().add(arti);
353 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("MechID: "));
354 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
355 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
357 String resp = AAFSSO.cons.readLine("Types [file,jks,script] (%s): ", "jks");
358 for(String s : Split.splitTrim(',', resp)) {
359 arti.getType().add(s);
362 if(!resp.contains(SCRIPT)) {
363 arti.getType().add(SCRIPT);
366 // Note: Sponsor is set on Creation by CM
367 String configRootName = FQI.reverseDomain(arti.getMechid());
368 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
369 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
370 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
371 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
372 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
374 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
376 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
377 if(future.get(TIMEOUT)) {
378 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
380 trans.error().printf("Call to AAF Certman failed, %s",
381 errMsg.toMsg(future));
388 private static String toNotification(String notification) {
389 if(notification==null) {
391 } else if(notification.length()>0) {
392 if(notification.indexOf(':')<0) {
393 notification = "mailto:" + notification;
400 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
401 String mechID = fqi(cmds);
402 String machine = machine(cmds);
404 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
406 Future<Artifacts> future = aafcon.client(CM_VER)
407 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
409 if(future.get(TIMEOUT)) {
410 boolean printed = false;
411 for(Artifact a : future.value.getArtifact()) {
412 AAFSSO.cons.printf("MechID: %s\n",a.getMechid());
413 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
414 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
415 AAFSSO.cons.printf("CA: %s\n",a.getCa());
416 StringBuilder sb = new StringBuilder();
417 boolean first = true;
418 for(String t : a.getType()) {
419 if(first) {first=false;}
420 else{sb.append(',');}
423 AAFSSO.cons.printf("Types: %s\n",sb);
424 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
425 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
426 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
427 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
428 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
432 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
435 trans.error().log(errMsg.toMsg(future));
442 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
443 String mechID = fqi(cmds);
444 String machine = machine(cmds);
445 String[] newmachs = machines(cmds);
446 if(machine==null || newmachs == null) {
447 trans.error().log("No machines listed to copy to");
449 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
451 Future<Artifacts> future = aafcon.client(CM_VER)
452 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
454 if(future.get(TIMEOUT)) {
455 boolean printed = false;
456 for(Artifact a : future.value.getArtifact()) {
457 for(String m : newmachs) {
459 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
460 if(fup.get(TIMEOUT)) {
461 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
463 trans.error().printf("Call to AAF Certman failed, %s",
471 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
474 trans.error().log(errMsg.toMsg(future));
482 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
483 String mechID = fqi(cmds);
484 String machine = machine(cmds);
486 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
488 Future<Artifacts> fread = aafcon.client(CM_VER)
489 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
491 if(fread.get(TIMEOUT)) {
492 Artifacts artifacts = new Artifacts();
493 for(Artifact a : fread.value.getArtifact()) {
494 Artifact arti = new Artifact();
495 artifacts.getArtifact().add(arti);
497 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
498 arti.setMechid(a.getMechid());
499 arti.setMachine(a.getMachine());
500 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
501 StringBuilder sb = new StringBuilder();
502 boolean first = true;
503 for(String t : a.getType()) {
504 if(first) {first=false;}
505 else{sb.append(',');}
509 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
510 for(String s : Split.splitTrim(',', resp)) {
511 arti.getType().add(s);
514 if(!resp.contains(SCRIPT)) {
515 arti.getType().add(SCRIPT);
518 // Note: Sponsor is set on Creation by CM
519 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
520 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
521 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
522 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
523 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
526 if(artifacts.getArtifact().size()==0) {
527 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
529 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
530 if(fup.get(TIMEOUT)) {
531 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
533 trans.error().printf("Call to AAF Certman failed, %s",
538 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
539 errMsg.toMsg(fread),mechID,machine);
546 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
547 String mechid = fqi(cmds);
548 String machine = machine(cmds);
550 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
552 Future<Void> future = aafcon.client(CM_VER)
553 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
555 if(future.get(TIMEOUT)) {
556 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
558 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
559 errMsg.toMsg(future),mechid,machine);
568 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
570 String mechID = fqi(cmds);
571 String machine = machine(cmds);
572 String[] fqdns = Split.split(':', machine);
581 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
583 Future<Artifacts> acf = aafcon.client(CM_VER)
584 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
585 if(acf.get(TIMEOUT)) {
586 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
587 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
589 for(Artifact a : acf.value.getArtifact()) {
590 String osID = System.getProperty("user.name");
591 if(a.getOsUser().equals(osID)) {
592 CertificateRequest cr = new CertificateRequest();
593 cr.setMechid(a.getMechid());
594 cr.setSponsor(a.getSponsor());
595 for(int i=0;i<fqdns.length;++i) {
596 cr.getFqdns().add(fqdns[i]);
598 Future<String> f = aafcon.client(CM_VER)
599 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
601 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
602 for(String type : a.getType()) {
603 PlaceArtifact pa = placeArtifact.get(type);
605 if(rv = pa.place(trans, capi, a,machine)) {
610 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
612 trans.error().log(errMsg.toMsg(f));
615 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
620 trans.error().log(errMsg.toMsg(acf));
628 private static void notifyPlaced(Artifact a, boolean rv) {
631 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
632 String mechID = fqi(cmds);
633 String machine = machine(cmds);
635 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
637 Future<Artifacts> acf = aafcon.client(CM_VER)
638 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
639 if(acf.get(TIMEOUT)) {
640 // Have to wait for JDK 1.7 source...
641 //switch(artifact.getType()) {
642 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
643 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
645 String id = aafcon.defID();
647 for(Artifact a : acf.value.getArtifact()) {
648 allowed = id!=null && (id.equals(a.getSponsor()) ||
649 (id.equals(a.getMechid())
650 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
652 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
653 a.getNs() + ".certman|"+a.getCa()+"|showpass","*/*");
654 if(pf.get(TIMEOUT)) {
657 trans.error().log(errMsg.toMsg(pf));
661 File dir = new File(a.getDir());
662 Properties props = new Properties();
663 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
667 fis = new FileInputStream(new File(dir,a.getNs()+".chal"));
673 File f = new File(dir,a.getNs()+".keyfile");
675 Symm symm = Symm.obtain(f);
677 for(Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
678 Entry<Object,Object> en = iter.next();
679 if(en.getValue().toString().startsWith("enc:")) {
680 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
684 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
685 f.getAbsolutePath(),a.getMechid(), a.getMachine());
691 trans.error().log(errMsg.toMsg(acf));
699 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
700 final String fqi = fqi(cmds);
701 final String ns = FQI.reverseDomain(fqi);
702 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
703 File f = new File(dir,ns+".key");
706 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
707 if(!"Y".equalsIgnoreCase(line)) {
708 System.out.println("Canceling...");
713 KeyPair kp = Factory.generateKeyPair(trans);
714 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
715 System.out.printf("Wrote %s\n", f.getCanonicalFile());
717 f=new File(dir,ns+".pubkey");
718 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
719 System.out.printf("Wrote %s\n", f.getCanonicalFile());
722 private static void config(Trans trans, PropAccess pa, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
723 final String fqi = fqi(cmds);
724 final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
725 final String rootFile = FQI.reverseDomain(fqi);
726 final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, "."));
728 System.out.println("Writing to " + dir.getCanonicalFile());
729 } else if(dir.mkdirs()) {
730 System.out.println("Created directory " + dir.getCanonicalFile());
732 System.err.println("Unable to create or write to " + dir.getCanonicalPath());
736 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
739 File fProps = File.createTempFile(rootFile, ".tmp",dir);
740 File fSecureTempProps = File.createTempFile(rootFile, ".cred.tmp",dir);
741 File fSecureProps = new File(dir,rootFile+".cred.props");
744 File fLocProps = new File(dir,rootFile + ".location.props");
745 if(!fLocProps.exists()) {
746 psProps = new PrintStream(new FileOutputStream(fLocProps));
748 psProps.println(HASHES);
749 psProps.print("# Configuration File generated on ");
750 psProps.println(new Date().toString());
751 psProps.println(HASHES);
752 for(String tag : new String[] {Config.CADI_LATITUDE,Config.CADI_LONGITUDE}) {
755 psProps.println(getProperty(pa, trans, false, tag, "%s: ",tag));
762 psProps = new PrintStream(new FileOutputStream(fProps));
764 PrintStream psCredProps = new PrintStream(new FileOutputStream(fSecureTempProps));
766 psCredProps.println(HASHES);
767 psCredProps.print("# Configuration File generated on ");
768 psCredProps.println(new Date().toString());
769 psCredProps.println(HASHES);
771 psProps.println(HASHES);
772 psProps.print("# Configuration File generated on ");
773 psProps.println(new Date().toString());
774 psProps.println(HASHES);
776 psProps.print(Config.CADI_PROP_FILES);
778 psProps.print(fSecureProps.getCanonicalPath());
779 psProps.print(File.pathSeparatorChar);
780 psProps.println(fLocProps.getCanonicalPath());
782 File fkf = new File(dir,rootFile+".keyfile");
784 CmdLine.main(new String[] {"keygen",fkf.toString()});
786 psCredProps.print("cadi_keyfile=");
787 psCredProps.println(fkf.getCanonicalPath());
789 psCredProps.print(Config.AAF_APPID);
790 psCredProps.print('=');
791 psCredProps.println(fqi);
793 Symm filesymm = Symm.obtain(fkf);
794 psCredProps.print(Config.AAF_APPPASS);
795 psCredProps.print("=enc:");
796 String ps = pa.decrypt(pa.getProperty(Config.AAF_APPPASS), false);
797 ps = filesymm.enpass(ps);
798 psCredProps.println(ps);
800 psCredProps.print(Config.CADI_TRUSTSTORE);
801 psCredProps.print("=");
802 File origTruststore = new File(pa.getProperty(Config.CADI_TRUSTSTORE));
803 File newTruststore = new File(dir,origTruststore.getName());
804 if(!newTruststore.exists()) {
805 Files.copy(origTruststore.toPath(), newTruststore.toPath());
807 psCredProps.println(newTruststore.getCanonicalPath());
809 psCredProps.print(Config.CADI_TRUSTSTORE_PASSWORD);
810 psCredProps.print("=enc:");
811 ps = pa.decrypt(pa.getProperty(Config.CADI_TRUSTSTORE_PASSWORD), false);
812 ps = filesymm.enpass(ps);
813 psCredProps.println(ps);
816 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
817 .read("/configure/"+fqi+"/aaf", configDF);
818 if(acf.get(TIMEOUT)) {
819 // out.println(acf.value.getName());
820 for(Props props : acf.value.getProps()) {
821 psProps.println(props.getTag() + '=' + props.getValue());
824 } else if(acf.code()==401){
825 trans.error().log("Bad Password sent to AAF");
827 trans.error().log(errMsg.toMsg(acf));
833 File newFile = new File(dir,rootFile+".props");
834 fProps.renameTo(newFile);
835 System.out.println("Created " + newFile.getCanonicalPath());
838 fSecureTempProps.renameTo(fSecureProps);
839 System.out.println("Created " + fSecureProps.getCanonicalPath());
843 fSecureTempProps.delete();
856 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
857 System.out.println("Validating Configuration...");
858 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
859 aafcon.best(new Retryable<Void>() {
861 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
862 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
863 if(fc.get(aafcon.timeout)) {
864 System.out.print("Success connecting to ");
865 System.out.println(client.getURI());
866 System.out.print(" Permissions for ");
867 System.out.println(aafcon.defID());
868 for(Perm p : fc.value.getPerm()) {
869 System.out.print('\t');
870 System.out.print(p.getType());
871 System.out.print('|');
872 System.out.print(p.getInstance());
873 System.out.print('|');
874 System.out.println(p.getAction());
877 System.err.println("Error: " + fc.code() + ' ' + fc.body());
885 * Check returns Error Codes, so that Scripts can know what to do
887 * 0 - Check Complete, nothing to do
889 * 2 - Error for specific Artifact - read check.msg
890 * 10 - Certificate Updated - check.msg is email content
898 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
900 String mechID = fqi(cmds);
901 String machine = machine(cmds);
903 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
906 Future<Artifacts> acf = aafcon.client(CM_VER)
907 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
908 if(acf.get(TIMEOUT)) {
909 // Have to wait for JDK 1.7 source...
910 //switch(artifact.getType()) {
911 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
912 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
914 String id = aafcon.defID();
915 GregorianCalendar now = new GregorianCalendar();
916 for(Artifact a : acf.value.getArtifact()) {
917 if(id.equals(a.getMechid())) {
918 File dir = new File(a.getDir());
919 Properties props = new Properties();
920 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
930 if((prop=props.getProperty(Config.CADI_KEYFILE))==null ||
931 !(f=new File(prop)).exists()) {
932 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
933 a.getMechid(), a.getMachine());
935 String ksf = props.getProperty(Config.CADI_KEYSTORE);
936 String ksps = props.getProperty(Config.CADI_KEYSTORE_PASSWORD);
937 if(ksf==null || ksps == null) {
938 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
939 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
941 KeyStore ks = KeyStore.getInstance("JKS");
942 Symm symm = Symm.obtain(f);
944 fis = new FileInputStream(ksf);
946 ks.load(fis,symm.depass(ksps).toCharArray());
950 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
954 msg = String.format("X509Certificate does not exist for %s on %s in %s",
955 a.getMechid(), a.getMachine(), ksf);
956 trans.error().log(msg);
959 GregorianCalendar renew = new GregorianCalendar();
960 renew.setTime(cert.getNotAfter());
961 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
962 if(renew.after(now)) {
963 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",
964 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
965 trans.info().log(msg);
968 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
969 a.getMechid(), a.getMachine(),cert.getNotAfter());
970 cmds.offerLast(mechID);
971 cmds.offerLast(machine);
972 if(placeCerts(trans,aafcon,cmds)) {
973 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
974 a.getMechid(), a.getMachine());
975 exitCode = 10; // Refreshed
977 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
978 a.getMechid(), a.getMachine());
979 exitCode = 1; // Error Renewing
984 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
986 fos.write(msg.getBytes());
998 trans.error().log(errMsg.toMsg(acf));