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.Arrays;
39 import java.util.Date;
40 import java.util.Deque;
41 import java.util.GregorianCalendar;
42 import java.util.HashMap;
43 import java.util.Iterator;
44 import java.util.List;
46 import java.util.Map.Entry;
47 import java.util.Properties;
48 import java.util.TreeMap;
50 import org.onap.aaf.cadi.CadiException;
51 import org.onap.aaf.cadi.CmdLine;
52 import org.onap.aaf.cadi.LocatorException;
53 import org.onap.aaf.cadi.PropAccess;
54 import org.onap.aaf.cadi.Symm;
55 import org.onap.aaf.cadi.aaf.client.ErrMessage;
56 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
57 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
58 import org.onap.aaf.cadi.client.Future;
59 import org.onap.aaf.cadi.client.Rcli;
60 import org.onap.aaf.cadi.client.Retryable;
61 import org.onap.aaf.cadi.config.Config;
62 import org.onap.aaf.cadi.config.SecurityInfoC;
63 import org.onap.aaf.cadi.http.HBasicAuthSS;
64 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
65 import org.onap.aaf.cadi.sso.AAFSSO;
66 import org.onap.aaf.cadi.util.Chmod;
67 import org.onap.aaf.cadi.util.FQI;
68 import org.onap.aaf.misc.env.APIException;
69 import org.onap.aaf.misc.env.Data.TYPE;
70 import org.onap.aaf.misc.env.Env;
71 import org.onap.aaf.misc.env.TimeTaken;
72 import org.onap.aaf.misc.env.Trans;
73 import org.onap.aaf.misc.env.util.Chrono;
74 import org.onap.aaf.misc.env.util.Split;
75 import org.onap.aaf.misc.rosetta.env.RosettaDF;
76 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
79 import aaf.v2_0.Perms;
80 import certman.v1_0.Artifacts;
81 import certman.v1_0.Artifacts.Artifact;
82 import certman.v1_0.CertInfo;
83 import certman.v1_0.CertificateRequest;
84 import locate.v1_1.Configuration;
85 import locate.v1_1.Configuration.Props;
88 private static final String HASHES = "################################################################";
89 private static final String PRINT = "print";
90 private static final String FILE = "file";
91 private static final String PKCS12 = "pkcs12";
92 private static final String JKS = "jks";
93 private static final String SCRIPT="script";
95 private static final String CM_VER = "1.0";
96 public static final int PASS_SIZE = 24;
97 private static int TIMEOUT;
99 private static RosettaDF<CertificateRequest> reqDF;
100 private static RosettaDF<CertInfo> certDF;
101 private static RosettaDF<Artifacts> artifactsDF;
102 private static RosettaDF<Configuration> configDF;
103 private static RosettaDF<Perms> permDF;
104 private static ErrMessage errMsg;
105 private static Map<String,PlaceArtifact> placeArtifact;
106 private static RosettaEnv env;
108 private static boolean doExit;
109 private static AAFCon<?> aafcon;
111 public static void main(String[] args) {
114 if(args.length>0 && "cadi".equals(args[0])) {
115 String[] newArgs = new String[args.length-1];
116 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
117 if(newArgs.length==0) {
118 System.out.println(HASHES);
119 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
120 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
121 System.out.println(HASHES);
123 CmdLine.main(newArgs);
129 if(args.length>0 && args[0].equals("validate")) {
130 int idx = args[1].indexOf('=');
132 access = new PropAccess(
133 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
135 (idx<0?args[1]:args[1].substring(idx+1)));
137 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
139 public Properties process(String[] args, Properties props) {
141 if (!args[0].equals("keypairgen")) {
142 props.put("aaf_id", args[1]);
148 access = aafsso.access();
151 if(aafsso!=null && aafsso.loginOnly()) {
152 aafsso.setLogDefault();
154 System.out.println("AAF SSO information created in ~/.aaf");
156 env = new RosettaEnv(access.getProperties());
157 Deque<String> cmds = new ArrayDeque<String>();
158 for(String p : args) {
159 if("-noexit".equalsIgnoreCase(p)) {
161 } else if(p.indexOf('=') < 0) {
168 aafsso.setLogDefault();
170 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
171 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
172 System.out.println(" create <FQI> [<machine>]");
173 System.out.println(" read <FQI> [<machine>]");
174 System.out.println(" update <FQI> [<machine>]");
175 System.out.println(" delete <FQI> [<machine>]");
176 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
177 System.out.println(" place <FQI> [<machine>]");
178 System.out.println(" showpass <FQI> [<machine>]");
179 System.out.println(" check <FQI> [<machine>]");
180 System.out.println(" keypairgen <FQI>");
181 System.out.println(" config <FQI>");
182 System.out.println(" validate <NS>.props>");
183 System.out.println(" --- Additional Tool Access ---");
184 System.out.println(" ** Type with no params for Tool Help");
185 System.out.println(" ** If using with Agent, preface with \"cadi\"");
186 System.out.println(" cadi <cadi tool params, see -?>");
193 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
195 reqDF = env.newDataFactory(CertificateRequest.class);
196 artifactsDF = env.newDataFactory(Artifacts.class);
197 certDF = env.newDataFactory(CertInfo.class);
198 configDF = env.newDataFactory(Configuration.class);
199 permDF = env.newDataFactory(Perms.class);
200 errMsg = new ErrMessage(env);
202 placeArtifact = new HashMap<>();
203 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
204 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
205 placeArtifact.put(FILE, new PlaceArtifactInFiles());
206 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
207 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
209 Trans trans = env.newTrans();
211 if((token=access.getProperty("oauth_token"))!=null) {
212 trans.setProperty("oauth_token", token);
216 // show Std out again
217 aafsso.setLogDefault();
218 aafsso.setStdErrDefault();
220 // if CM_URL can be obtained, add to sso.props, if written
221 String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": ");
223 aafsso.addProp(Config.CM_URL, cm_url);
230 String cmd = cmds.removeFirst();
233 placeCerts(trans,aafcon(access),cmds);
236 createArtifact(trans, aafcon(access),cmds);
239 readArtifact(trans, aafcon(access), cmds);
242 copyArtifact(trans, aafcon(access), cmds);
245 updateArtifact(trans, aafcon(access), cmds);
248 deleteArtifact(trans, aafcon(access), cmds);
251 showPass(trans, aafcon(access), cmds);
254 keypairGen(trans, access, cmds);
257 if(access.getProperty(Config.CADI_PROP_FILES)!=null) {
258 // Get Properties from initialization Prop Files
259 config(trans,access,null,cmds);
261 // Get Properties from existing AAF Instance
262 config(trans,access,aafcon(access),cmds);
270 exitCode = check(trans,aafcon(access),cmds);
271 } catch (Exception e) {
277 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
280 StringBuilder sb = new StringBuilder();
281 trans.auditTrail(4, sb, Trans.REMOTE);
283 trans.info().log("Trans Info\n",sb);
290 } catch (Exception e) {
294 if(exitCode != 0 && doExit) {
295 System.exit(exitCode);
299 private static synchronized AAFCon<?> aafcon(PropAccess access) throws APIException, CadiException, LocatorException {
301 aafcon = new AAFConHttp(access,Config.CM_URL);
306 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
308 if((value=pa.getProperty(tag))==null) {
310 value = new String(AAFSSO.cons.readPassword(prompt, def));
312 value = AAFSSO.cons.readLine(prompt,def).trim();
315 if(value.length()>0) {
316 pa.setProperty(tag,value);
317 env.setProperty(tag,value);
318 } else if(def.length==1) {
319 value=def[0].toString();
320 pa.setProperty(tag,value);
321 env.setProperty(tag,value);
328 private static String fqi(Deque<String> cmds) {
330 String alias = env.getProperty(Config.CADI_ALIAS);
331 return alias!=null?alias:AAFSSO.cons.readLine("MechID: ");
333 return cmds.removeFirst();
336 private static String machine(Deque<String> cmds) throws UnknownHostException {
338 return cmds.removeFirst();
340 String mach = env.getProperty(Config.HOSTNAME);
341 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
345 private static String[] machines(Deque<String> cmds) {
348 machines = cmds.removeFirst();
350 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
352 return Split.split(',', machines);
355 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
356 String mechID = fqi(cmds);
357 String machine = machine(cmds);
359 Artifacts artifacts = new Artifacts();
360 Artifact arti = new Artifact();
361 artifacts.getArtifact().add(arti);
362 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("MechID: "));
363 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
364 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
366 String resp = AAFSSO.cons.readLine("Types [file,jks,script] (%s): ", "jks");
367 for(String s : Split.splitTrim(',', resp)) {
368 arti.getType().add(s);
371 if(!resp.contains(SCRIPT)) {
372 arti.getType().add(SCRIPT);
375 // Note: Sponsor is set on Creation by CM
376 String configRootName = FQI.reverseDomain(arti.getMechid());
377 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
378 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
379 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
380 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
381 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
383 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
385 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
386 if(future.get(TIMEOUT)) {
387 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
389 trans.error().printf("Call to AAF Certman failed, %s",
390 errMsg.toMsg(future));
397 private static String toNotification(String notification) {
398 if(notification==null) {
400 } else if(notification.length()>0) {
401 if(notification.indexOf(':')<0) {
402 notification = "mailto:" + notification;
409 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
410 String mechID = fqi(cmds);
411 String machine = machine(cmds);
413 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
415 Future<Artifacts> future = aafcon.client(CM_VER)
416 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
418 if(future.get(TIMEOUT)) {
419 boolean printed = false;
420 for(Artifact a : future.value.getArtifact()) {
421 AAFSSO.cons.printf("MechID: %s\n",a.getMechid());
422 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
423 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
424 AAFSSO.cons.printf("CA: %s\n",a.getCa());
425 StringBuilder sb = new StringBuilder();
426 boolean first = true;
427 for(String t : a.getType()) {
428 if(first) {first=false;}
429 else{sb.append(',');}
432 AAFSSO.cons.printf("Types: %s\n",sb);
433 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
434 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
435 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
436 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
437 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
441 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
444 trans.error().log(errMsg.toMsg(future));
451 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
452 String mechID = fqi(cmds);
453 String machine = machine(cmds);
454 String[] newmachs = machines(cmds);
455 if(machine==null || newmachs == null) {
456 trans.error().log("No machines listed to copy to");
458 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
460 Future<Artifacts> future = aafcon.client(CM_VER)
461 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
463 if(future.get(TIMEOUT)) {
464 boolean printed = false;
465 for(Artifact a : future.value.getArtifact()) {
466 for(String m : newmachs) {
468 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
469 if(fup.get(TIMEOUT)) {
470 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
472 trans.error().printf("Call to AAF Certman failed, %s",
480 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
483 trans.error().log(errMsg.toMsg(future));
491 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
492 String mechID = fqi(cmds);
493 String machine = machine(cmds);
495 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
497 Future<Artifacts> fread = aafcon.client(CM_VER)
498 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
500 if(fread.get(TIMEOUT)) {
501 Artifacts artifacts = new Artifacts();
502 for(Artifact a : fread.value.getArtifact()) {
503 Artifact arti = new Artifact();
504 artifacts.getArtifact().add(arti);
506 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
507 arti.setMechid(a.getMechid());
508 arti.setMachine(a.getMachine());
509 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
510 StringBuilder sb = new StringBuilder();
511 boolean first = true;
512 for(String t : a.getType()) {
513 if(first) {first=false;}
514 else{sb.append(',');}
518 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
519 for(String s : Split.splitTrim(',', resp)) {
520 arti.getType().add(s);
523 if(!resp.contains(SCRIPT)) {
524 arti.getType().add(SCRIPT);
527 // Note: Sponsor is set on Creation by CM
528 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
529 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
530 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
531 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
532 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
535 if(artifacts.getArtifact().size()==0) {
536 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
538 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
539 if(fup.get(TIMEOUT)) {
540 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
542 trans.error().printf("Call to AAF Certman failed, %s",
547 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
548 errMsg.toMsg(fread),mechID,machine);
555 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
556 String mechid = fqi(cmds);
557 String machine = machine(cmds);
559 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
561 Future<Void> future = aafcon.client(CM_VER)
562 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
564 if(future.get(TIMEOUT)) {
565 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
567 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
568 errMsg.toMsg(future),mechid,machine);
577 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
579 String mechID = fqi(cmds);
580 String machine = machine(cmds);
581 String[] fqdns = Split.split(':', machine);
590 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
592 Future<Artifacts> acf = aafcon.client(CM_VER)
593 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
594 if(acf.get(TIMEOUT)) {
595 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
596 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
598 for(Artifact a : acf.value.getArtifact()) {
599 String osID = System.getProperty("user.name");
600 if(a.getOsUser().equals(osID)) {
601 CertificateRequest cr = new CertificateRequest();
602 cr.setMechid(a.getMechid());
603 cr.setSponsor(a.getSponsor());
604 for(int i=0;i<fqdns.length;++i) {
605 cr.getFqdns().add(fqdns[i]);
607 Future<String> f = aafcon.client(CM_VER)
608 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
610 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
611 for(String type : a.getType()) {
612 PlaceArtifact pa = placeArtifact.get(type);
614 if(rv = pa.place(trans, capi, a,machine)) {
619 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
621 trans.error().log(errMsg.toMsg(f));
624 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
629 trans.error().log(errMsg.toMsg(acf));
637 private static void notifyPlaced(Artifact a, boolean rv) {
640 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
641 String mechID = fqi(cmds);
642 String machine = machine(cmds);
644 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
646 Future<Artifacts> acf = aafcon.client(CM_VER)
647 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
648 if(acf.get(TIMEOUT)) {
649 // Have to wait for JDK 1.7 source...
650 //switch(artifact.getType()) {
651 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
652 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
654 String id = aafcon.defID();
656 for(Artifact a : acf.value.getArtifact()) {
657 allowed = id!=null && (id.equals(a.getSponsor()) ||
658 (id.equals(a.getMechid())
659 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
661 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
662 a.getNs() + ".certman|"+a.getCa()+"|showpass","*/*");
663 if(pf.get(TIMEOUT)) {
666 trans.error().log(errMsg.toMsg(pf));
670 File dir = new File(a.getDir());
671 Properties props = new Properties();
672 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
676 fis = new FileInputStream(new File(dir,a.getNs()+".chal"));
682 File f = new File(dir,a.getNs()+".keyfile");
684 Symm symm = Symm.obtain(f);
686 for(Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
687 Entry<Object,Object> en = iter.next();
688 if(en.getValue().toString().startsWith("enc:")) {
689 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
693 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
694 f.getAbsolutePath(),a.getMechid(), a.getMachine());
700 trans.error().log(errMsg.toMsg(acf));
708 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
709 final String fqi = fqi(cmds);
710 final String ns = FQI.reverseDomain(fqi);
711 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
712 File f = new File(dir,ns+".key");
715 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
716 if(!"Y".equalsIgnoreCase(line)) {
717 System.out.println("Canceling...");
722 KeyPair kp = Factory.generateKeyPair(trans);
723 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
724 System.out.printf("Wrote %s\n", f.getCanonicalFile());
726 f=new File(dir,ns+".pubkey");
727 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
728 System.out.printf("Wrote %s\n", f.getCanonicalFile());
731 private static void config(Trans trans, PropAccess pa, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
732 final String fqi = fqi(cmds);
733 final String rootFile = FQI.reverseDomain(fqi);
734 final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, "."));
736 System.out.println("Writing to " + dir.getCanonicalFile());
737 } else if(dir.mkdirs()) {
738 System.out.println("Created directory " + dir.getCanonicalFile());
740 System.err.println("Unable to create or write to " + dir.getCanonicalPath());
744 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
747 File fProps = File.createTempFile(rootFile, ".tmp",dir);
748 File fSecureTempProps = File.createTempFile(rootFile, ".cred.tmp",dir);
749 File fSecureProps = new File(dir,rootFile+".cred.props");
752 File fLocProps = new File(dir,rootFile + ".location.props");
753 if(!fLocProps.exists()) {
754 psProps = new PrintStream(new FileOutputStream(fLocProps));
756 psProps.println(HASHES);
757 psProps.print("# Configuration File generated on ");
758 psProps.println(new Date().toString());
759 psProps.println(HASHES);
760 for(String tag : LOC_TAGS) {
763 psProps.println(getProperty(pa, trans, false, tag, "%s: ",tag));
770 psProps = new PrintStream(new FileOutputStream(fProps));
772 PrintStream psCredProps = new PrintStream(new FileOutputStream(fSecureTempProps));
774 psCredProps.println(HASHES);
775 psCredProps.print("# Configuration File generated on ");
776 psCredProps.println(new Date().toString());
777 psCredProps.println(HASHES);
779 psProps.println(HASHES);
780 psProps.print("# Configuration File generated on ");
781 psProps.println(new Date().toString());
782 psProps.println(HASHES);
784 psProps.print(Config.CADI_PROP_FILES);
786 psProps.print(fSecureProps.getCanonicalPath());
787 psProps.print(File.pathSeparatorChar);
788 psProps.println(fLocProps.getCanonicalPath());
790 File fkf = new File(dir,rootFile+".keyfile");
792 CmdLine.main(new String[] {"keygen",fkf.toString()});
794 Symm filesymm = Symm.obtain(fkf);
795 Map<String,String> normal = new TreeMap<>();
796 Map<String,String> creds = new TreeMap<>();
798 directedPut(pa, filesymm, normal,creds, Config.CADI_KEYFILE, fkf.getCanonicalPath());
799 directedPut(pa, filesymm, normal,creds, Config.AAF_APPID,fqi);
800 directedPut(pa, filesymm, normal,creds, Config.AAF_APPPASS,null);
803 String cts = pa.getProperty(Config.CADI_TRUSTSTORE);
805 File origTruststore = new File(cts);
806 if(!origTruststore.exists()) {
807 // Try same directory as cadi_prop_files
808 String cpf = pa.getProperty(Config.CADI_PROP_FILES);
810 for(String f : Split.split(File.pathSeparatorChar, cpf)) {
811 File fcpf = new File(f);
813 int lastSep = cts.lastIndexOf(File.pathSeparator);
814 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
815 if(origTruststore.exists()) {
820 if(!origTruststore.exists()) {
821 throw new CadiException(cts + " does not exist");
826 File newTruststore = new File(dir,origTruststore.getName());
827 if(!newTruststore.exists()) {
828 Files.copy(origTruststore.toPath(), newTruststore.toPath());
831 directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE,newTruststore.getCanonicalPath());
832 directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE_PASSWORD,null);
835 if(aafcon!=null) { // get Properties from Remote AAF
836 final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
838 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
839 .read("/configure/"+fqi+"/aaf", configDF);
840 if(acf.get(TIMEOUT)) {
841 for(Props props : acf.value.getProps()) {
842 directedPut(pa, filesymm, normal,creds, props.getTag(),props.getValue());
845 } else if(acf.code()==401){
846 trans.error().log("Bad Password sent to AAF");
848 trans.error().log(errMsg.toMsg(acf));
851 String cpf = pa.getProperty(Config.CADI_PROP_FILES);
853 for(String f : Split.split(File.pathSeparatorChar, cpf)) {
854 System.out.format("Reading %s\n",f);
855 FileInputStream fis = new FileInputStream(f);
857 Properties props = new Properties();
859 for(Entry<Object, Object> prop : props.entrySet()) {
860 directedPut(pa, filesymm, normal,creds, prop.getKey().toString(),prop.getValue().toString());
870 for(Entry<String, String> es : normal.entrySet()) {
871 psProps.print(es.getKey());
873 psProps.println(es.getValue());
876 for(Entry<String, String> es : creds.entrySet()) {
877 psCredProps.print(es.getKey());
878 psCredProps.print('=');
879 psCredProps.println(es.getValue());
882 File newFile = new File(dir,rootFile+".props");
883 if(newFile.exists()) {
884 File backup = new File(dir,rootFile+".props.backup");
885 newFile.renameTo(backup);
886 System.out.println("Backed up to " + backup.getCanonicalPath());
888 fProps.renameTo(newFile);
889 System.out.println("Created " + newFile.getCanonicalPath());
892 if(fSecureProps.exists()) {
893 File backup = new File(dir,fSecureProps.getName()+".backup");
894 fSecureProps.renameTo(backup);
895 System.out.println("Backed up to " + backup.getCanonicalPath());
897 fSecureTempProps.renameTo(fSecureProps);
898 System.out.println("Created " + fSecureProps.getCanonicalPath());
902 fSecureTempProps.delete();
915 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
917 Config.AAF_APPID, Config.AAF_APPPASS,
918 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
919 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
920 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
923 private static List<String> LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE});
925 private static void directedPut(final PropAccess orig, final Symm symm, final Map<String,String> main, final Map<String,String> secured, final String tag, final String value) throws IOException {
926 if(!LOC_TAGS.contains(tag)) { // Location already covered
927 String val = value==null?orig.getProperty(tag):value;
928 if(tag.endsWith("_password")) {
930 if(val.startsWith("enc:")) {
931 val = orig.decrypt(value, true);
933 val = "enc:" + symm.enpass(val);
936 if(CRED_TAGS.contains(tag)) {
937 secured.put(tag, val);
944 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
945 System.out.println("Validating Configuration...");
946 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
947 aafcon.best(new Retryable<Void>() {
949 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
950 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
951 if(fc.get(aafcon.timeout)) {
952 System.out.print("Success connecting to ");
953 System.out.println(client.getURI());
954 System.out.print(" Permissions for ");
955 System.out.println(aafcon.defID());
956 for(Perm p : fc.value.getPerm()) {
957 System.out.print('\t');
958 System.out.print(p.getType());
959 System.out.print('|');
960 System.out.print(p.getInstance());
961 System.out.print('|');
962 System.out.println(p.getAction());
965 System.err.println("Error: " + fc.code() + ' ' + fc.body());
973 * Check returns Error Codes, so that Scripts can know what to do
975 * 0 - Check Complete, nothing to do
977 * 2 - Error for specific Artifact - read check.msg
978 * 10 - Certificate Updated - check.msg is email content
986 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
988 String mechID = fqi(cmds);
989 String machine = machine(cmds);
991 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
994 Future<Artifacts> acf = aafcon.client(CM_VER)
995 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
996 if(acf.get(TIMEOUT)) {
997 // Have to wait for JDK 1.7 source...
998 //switch(artifact.getType()) {
999 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1000 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1002 String id = aafcon.defID();
1003 GregorianCalendar now = new GregorianCalendar();
1004 for(Artifact a : acf.value.getArtifact()) {
1005 if(id.equals(a.getMechid())) {
1006 File dir = new File(a.getDir());
1007 Properties props = new Properties();
1008 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1018 if((prop=props.getProperty(Config.CADI_KEYFILE))==null ||
1019 !(f=new File(prop)).exists()) {
1020 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1021 a.getMechid(), a.getMachine());
1023 String ksf = props.getProperty(Config.CADI_KEYSTORE);
1024 String ksps = props.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1025 if(ksf==null || ksps == null) {
1026 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1027 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1029 KeyStore ks = KeyStore.getInstance("JKS");
1030 Symm symm = Symm.obtain(f);
1032 fis = new FileInputStream(ksf);
1034 ks.load(fis,symm.depass(ksps).toCharArray());
1038 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1042 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1043 a.getMechid(), a.getMachine(), ksf);
1044 trans.error().log(msg);
1047 GregorianCalendar renew = new GregorianCalendar();
1048 renew.setTime(cert.getNotAfter());
1049 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1050 if(renew.after(now)) {
1051 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",
1052 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1053 trans.info().log(msg);
1056 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1057 a.getMechid(), a.getMachine(),cert.getNotAfter());
1058 cmds.offerLast(mechID);
1059 cmds.offerLast(machine);
1060 if(placeCerts(trans,aafcon,cmds)) {
1061 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1062 a.getMechid(), a.getMachine());
1063 exitCode = 10; // Refreshed
1065 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1066 a.getMechid(), a.getMachine());
1067 exitCode = 1; // Error Renewing
1072 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1074 fos.write(msg.getBytes());
1086 trans.error().log(errMsg.toMsg(acf));