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.Defaults;
56 import org.onap.aaf.cadi.aaf.client.ErrMessage;
57 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
58 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
59 import org.onap.aaf.cadi.client.Future;
60 import org.onap.aaf.cadi.client.Rcli;
61 import org.onap.aaf.cadi.client.Retryable;
62 import org.onap.aaf.cadi.config.Config;
63 import org.onap.aaf.cadi.config.SecurityInfoC;
64 import org.onap.aaf.cadi.http.HBasicAuthSS;
65 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
66 import org.onap.aaf.cadi.sso.AAFSSO;
67 import org.onap.aaf.cadi.util.Chmod;
68 import org.onap.aaf.cadi.util.FQI;
69 import org.onap.aaf.misc.env.APIException;
70 import org.onap.aaf.misc.env.Data.TYPE;
71 import org.onap.aaf.misc.env.Env;
72 import org.onap.aaf.misc.env.TimeTaken;
73 import org.onap.aaf.misc.env.Trans;
74 import org.onap.aaf.misc.env.util.Chrono;
75 import org.onap.aaf.misc.env.util.Split;
76 import org.onap.aaf.misc.rosetta.env.RosettaDF;
77 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
80 import aaf.v2_0.Perms;
81 import certman.v1_0.Artifacts;
82 import certman.v1_0.Artifacts.Artifact;
83 import certman.v1_0.CertInfo;
84 import certman.v1_0.CertificateRequest;
85 import locate.v1_1.Configuration;
86 import locate.v1_1.Configuration.Props;
89 private static final String HASHES = "################################################################";
90 private static final String PRINT = "print";
91 private static final String FILE = "file";
92 public static final String PKCS12 = "pkcs12";
93 public static final String JKS = "jks";
94 private static final String SCRIPT="script";
96 private static final String CM_VER = "1.0";
97 public static final int PASS_SIZE = 24;
98 private static int TIMEOUT;
100 private static RosettaDF<CertificateRequest> reqDF;
101 private static RosettaDF<CertInfo> certDF;
102 private static RosettaDF<Artifacts> artifactsDF;
103 private static RosettaDF<Configuration> configDF;
104 private static RosettaDF<Perms> permDF;
105 private static ErrMessage errMsg;
106 private static Map<String,PlaceArtifact> placeArtifact;
107 private static RosettaEnv env;
109 private static boolean doExit;
110 private static AAFCon<?> aafcon;
112 public static void main(String[] args) {
115 if(args.length>0 && "cadi".equals(args[0])) {
116 String[] newArgs = new String[args.length-1];
117 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
118 if(newArgs.length==0) {
119 System.out.println(HASHES);
120 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
121 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
122 System.out.println(HASHES);
124 CmdLine.main(newArgs);
130 if(args.length>1 && args[0].equals("validate") ) {
131 int idx = args[1].indexOf('=');
133 access = new PropAccess(
134 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
136 (idx<0?args[1]:args[1].substring(idx+1)));
138 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
140 public Properties process(String[] args, Properties props) {
142 if (!args[0].equals("keypairgen")) {
143 props.put("aaf_id", args[1]);
149 access = aafsso.access();
152 if(aafsso!=null && aafsso.loginOnly()) {
153 aafsso.setLogDefault();
155 System.out.println("AAF SSO information created in ~/.aaf");
157 env = new RosettaEnv(access.getProperties());
158 Deque<String> cmds = new ArrayDeque<String>();
159 for(String p : args) {
160 if("-noexit".equalsIgnoreCase(p)) {
162 } else if(p.indexOf('=') < 0) {
169 aafsso.setLogDefault();
171 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
172 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
173 System.out.println(" create <FQI> [<machine>]");
174 System.out.println(" read <FQI> [<machine>]");
175 System.out.println(" update <FQI> [<machine>]");
176 System.out.println(" delete <FQI> [<machine>]");
177 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
178 System.out.println(" place <FQI> [<machine>]");
179 System.out.println(" showpass <FQI> [<machine>]");
180 System.out.println(" check <FQI> [<machine>]");
181 System.out.println(" keypairgen <FQI>");
182 System.out.println(" config <FQI>");
183 System.out.println(" validate <NS>.props>");
184 System.out.println(" --- Additional Tool Access ---");
185 System.out.println(" ** Type with no params for Tool Help");
186 System.out.println(" ** If using with Agent, preface with \"cadi\"");
187 System.out.println(" cadi <cadi tool params, see -?>");
194 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
196 reqDF = env.newDataFactory(CertificateRequest.class);
197 artifactsDF = env.newDataFactory(Artifacts.class);
198 certDF = env.newDataFactory(CertInfo.class);
199 configDF = env.newDataFactory(Configuration.class);
200 permDF = env.newDataFactory(Perms.class);
201 errMsg = new ErrMessage(env);
203 placeArtifact = new HashMap<>();
204 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
205 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
206 placeArtifact.put(FILE, new PlaceArtifactInFiles());
207 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
208 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
210 Trans trans = env.newTrans();
212 if((token=access.getProperty("oauth_token"))!=null) {
213 trans.setProperty("oauth_token", token);
217 // show Std out again
218 aafsso.setLogDefault();
219 aafsso.setStdErrDefault();
221 // if CM_URL can be obtained, add to sso.props, if written
222 String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": ");
224 aafsso.addProp(Config.CM_URL, cm_url);
231 String cmd = cmds.removeFirst();
234 placeCerts(trans,aafcon(access),cmds);
237 createArtifact(trans, aafcon(access),cmds);
240 readArtifact(trans, aafcon(access), cmds);
243 copyArtifact(trans, aafcon(access), cmds);
246 updateArtifact(trans, aafcon(access), cmds);
249 deleteArtifact(trans, aafcon(access), cmds);
252 showPass(trans, aafcon(access), cmds);
255 keypairGen(trans, access, cmds);
258 if(access.getProperty(Config.CADI_PROP_FILES)!=null) {
259 // Get Properties from initialization Prop Files
260 config(trans,access,null,cmds);
262 // Get Properties from existing AAF Instance
263 config(trans,access,aafcon(access),cmds);
271 exitCode = check(trans,aafcon(access),cmds);
272 } catch (Exception e) {
278 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
281 StringBuilder sb = new StringBuilder();
282 trans.auditTrail(4, sb, Trans.REMOTE);
284 trans.info().log("Trans Info\n",sb);
291 } catch (Exception e) {
295 if(exitCode != 0 && doExit) {
296 System.exit(exitCode);
300 private static synchronized AAFCon<?> aafcon(PropAccess access) throws APIException, CadiException, LocatorException {
302 aafcon = new AAFConHttp(access,Config.CM_URL);
307 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
309 if((value=pa.getProperty(tag))==null) {
311 value = new String(AAFSSO.cons.readPassword(prompt, def));
313 value = AAFSSO.cons.readLine(prompt,def).trim();
316 if(value.length()>0) {
317 pa.setProperty(tag,value);
318 env.setProperty(tag,value);
319 } else if(def.length==1) {
320 value=def[0].toString();
321 pa.setProperty(tag,value);
322 env.setProperty(tag,value);
329 private static String fqi(Deque<String> cmds) {
331 String alias = env.getProperty(Config.CADI_ALIAS);
332 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
334 return cmds.removeFirst();
337 private static String machine(Deque<String> cmds) throws UnknownHostException {
339 return cmds.removeFirst();
341 String mach = env.getProperty(Config.HOSTNAME);
342 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
346 private static String[] machines(Deque<String> cmds) {
349 machines = cmds.removeFirst();
351 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
353 return Split.split(',', machines);
356 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
357 final String mechID = fqi(cmds);
358 final String machine = machine(cmds);
360 Artifacts artifacts = new Artifacts();
361 Artifact arti = new Artifact();
362 artifacts.getArtifact().add(arti);
363 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
364 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
365 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
367 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
368 for(String s : Split.splitTrim(',', resp)) {
369 arti.getType().add(s);
372 if(!resp.contains(SCRIPT)) {
373 arti.getType().add(SCRIPT);
376 // Note: Sponsor is set on Creation by CM
377 String configRootName = FQI.reverseDomain(arti.getMechid());
378 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
379 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
380 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
381 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
382 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
384 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
386 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
387 if(future.get(TIMEOUT)) {
388 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
390 trans.error().printf("Call to AAF Certman failed, %s",
391 errMsg.toMsg(future));
398 private static String toNotification(String notification) {
399 if(notification==null) {
401 } else if(notification.length()>0) {
402 if(notification.indexOf(':')<0) {
403 notification = "mailto:" + notification;
410 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
411 String mechID = fqi(cmds);
412 String machine = machine(cmds);
414 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
416 Future<Artifacts> future = aafcon.client(CM_VER)
417 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
419 if(future.get(TIMEOUT)) {
420 boolean printed = false;
421 for(Artifact a : future.value.getArtifact()) {
422 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
423 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
424 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
425 AAFSSO.cons.printf("CA: %s\n",a.getCa());
426 StringBuilder sb = new StringBuilder();
427 boolean first = true;
428 for(String t : a.getType()) {
429 if(first) {first=false;}
430 else{sb.append(',');}
433 AAFSSO.cons.printf("Types: %s\n",sb);
434 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
435 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
436 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
437 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
438 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
442 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
445 trans.error().log(errMsg.toMsg(future));
452 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
453 String mechID = fqi(cmds);
454 String machine = machine(cmds);
455 String[] newmachs = machines(cmds);
456 if(machine==null || newmachs == null) {
457 trans.error().log("No machines listed to copy to");
459 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
461 Future<Artifacts> future = aafcon.client(CM_VER)
462 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
464 if(future.get(TIMEOUT)) {
465 boolean printed = false;
466 for(Artifact a : future.value.getArtifact()) {
467 for(String m : newmachs) {
469 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
470 if(fup.get(TIMEOUT)) {
471 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
473 trans.error().printf("Call to AAF Certman failed, %s",
481 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
484 trans.error().log(errMsg.toMsg(future));
492 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
493 String mechID = fqi(cmds);
494 String machine = machine(cmds);
496 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
498 Future<Artifacts> fread = aafcon.client(CM_VER)
499 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
501 if(fread.get(TIMEOUT)) {
502 Artifacts artifacts = new Artifacts();
503 for(Artifact a : fread.value.getArtifact()) {
504 Artifact arti = new Artifact();
505 artifacts.getArtifact().add(arti);
507 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
508 arti.setMechid(a.getMechid());
509 arti.setMachine(a.getMachine());
510 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
511 StringBuilder sb = new StringBuilder();
512 boolean first = true;
513 for(String t : a.getType()) {
514 if(first) {first=false;}
515 else{sb.append(',');}
519 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
520 for(String s : Split.splitTrim(',', resp)) {
521 arti.getType().add(s);
524 if(!resp.contains(SCRIPT)) {
525 arti.getType().add(SCRIPT);
528 // Note: Sponsor is set on Creation by CM
529 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
530 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
531 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
532 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
533 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
536 if(artifacts.getArtifact().size()==0) {
537 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
539 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
540 if(fup.get(TIMEOUT)) {
541 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
543 trans.error().printf("Call to AAF Certman failed, %s",
548 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
549 errMsg.toMsg(fread),mechID,machine);
556 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
557 String mechid = fqi(cmds);
558 String machine = machine(cmds);
560 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
562 Future<Void> future = aafcon.client(CM_VER)
563 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
565 if(future.get(TIMEOUT)) {
566 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
568 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
569 errMsg.toMsg(future),mechid,machine);
578 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
580 String mechID = fqi(cmds);
581 String machine = machine(cmds);
582 String[] fqdns = Split.split(':', machine);
591 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
593 Future<Artifacts> acf = aafcon.client(CM_VER)
594 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
595 if(acf.get(TIMEOUT)) {
596 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
597 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
599 for(Artifact a : acf.value.getArtifact()) {
600 String osID = System.getProperty("user.name");
601 if(a.getOsUser().equals(osID)) {
602 CertificateRequest cr = new CertificateRequest();
603 cr.setMechid(a.getMechid());
604 cr.setSponsor(a.getSponsor());
605 for(int i=0;i<fqdns.length;++i) {
606 cr.getFqdns().add(fqdns[i]);
608 Future<String> f = aafcon.client(CM_VER)
609 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
611 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
612 for(String type : a.getType()) {
613 PlaceArtifact pa = placeArtifact.get(type);
615 if(rv = pa.place(trans, capi, a,machine)) {
620 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
622 trans.error().log(errMsg.toMsg(f));
625 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
630 trans.error().log(errMsg.toMsg(acf));
638 private static void notifyPlaced(Artifact a, boolean rv) {
641 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
642 String mechID = fqi(cmds);
643 String machine = machine(cmds);
645 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
647 Future<Artifacts> acf = aafcon.client(CM_VER)
648 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
649 if(acf.get(TIMEOUT)) {
650 // Have to wait for JDK 1.7 source...
651 //switch(artifact.getType()) {
652 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
653 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
655 String id = aafcon.defID();
657 for(Artifact a : acf.value.getArtifact()) {
658 allowed = id!=null && (id.equals(a.getSponsor()) ||
659 (id.equals(a.getMechid())
660 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
662 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
663 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
664 if(pf.get(TIMEOUT)) {
667 trans.error().log(errMsg.toMsg(pf));
671 File dir = new File(a.getDir());
672 Properties props = new Properties();
673 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
677 fis = new FileInputStream(new File(dir,a.getNs()+".chal"));
683 File f = new File(dir,a.getNs()+".keyfile");
685 Symm symm = Symm.obtain(f);
687 for(Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
688 Entry<Object,Object> en = iter.next();
689 if(en.getValue().toString().startsWith("enc:")) {
690 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
694 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
695 f.getAbsolutePath(),a.getMechid(), a.getMachine());
701 trans.error().log(errMsg.toMsg(acf));
709 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
710 final String fqi = fqi(cmds);
711 final String ns = FQI.reverseDomain(fqi);
712 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
713 File f = new File(dir,ns+".key");
716 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
717 if(!"Y".equalsIgnoreCase(line)) {
718 System.out.println("Canceling...");
723 KeyPair kp = Factory.generateKeyPair(trans);
724 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
725 System.out.printf("Wrote %s\n", f.getCanonicalFile());
727 f=new File(dir,ns+".pubkey");
728 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
729 System.out.printf("Wrote %s\n", f.getCanonicalFile());
732 private static void config(Trans trans, PropAccess pa, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
733 final String fqi = fqi(cmds);
734 final String rootFile = FQI.reverseDomain(fqi);
735 final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, "."));
737 System.out.println("Writing to " + dir.getCanonicalFile());
738 } else if(dir.mkdirs()) {
739 System.out.println("Created directory " + dir.getCanonicalFile());
741 System.err.println("Unable to create or write to " + dir.getCanonicalPath());
745 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
748 File fProps = File.createTempFile(rootFile, ".tmp",dir);
749 File fSecureTempProps = File.createTempFile(rootFile, ".cred.tmp",dir);
750 File fSecureProps = new File(dir,rootFile+".cred.props");
753 File fLocProps = new File(dir,rootFile + ".location.props");
754 if(!fLocProps.exists()) {
755 psProps = new PrintStream(new FileOutputStream(fLocProps));
757 psProps.println(HASHES);
758 psProps.print("# Configuration File generated on ");
759 psProps.println(new Date().toString());
760 psProps.println(HASHES);
761 for(String tag : LOC_TAGS) {
764 psProps.println(getProperty(pa, trans, false, tag, "%s: ",tag));
771 psProps = new PrintStream(new FileOutputStream(fProps));
773 PrintStream psCredProps = new PrintStream(new FileOutputStream(fSecureTempProps));
775 psCredProps.println(HASHES);
776 psCredProps.print("# Configuration File generated on ");
777 psCredProps.println(new Date().toString());
778 psCredProps.println(HASHES);
780 psProps.println(HASHES);
781 psProps.print("# Configuration File generated on ");
782 psProps.println(new Date().toString());
783 psProps.println(HASHES);
785 psProps.print(Config.CADI_PROP_FILES);
787 psProps.print(fSecureProps.getCanonicalPath());
788 psProps.print(File.pathSeparatorChar);
789 psProps.println(fLocProps.getCanonicalPath());
791 File fkf = new File(dir,rootFile+".keyfile");
793 CmdLine.main(new String[] {"keygen",fkf.toString()});
795 Symm filesymm = Symm.obtain(fkf);
796 Map<String,String> normal = new TreeMap<>();
797 Map<String,String> creds = new TreeMap<>();
799 directedPut(pa, filesymm, normal,creds, Config.CADI_KEYFILE, fkf.getCanonicalPath());
800 directedPut(pa, filesymm, normal,creds, Config.AAF_APPID,fqi);
801 directedPut(pa, filesymm, normal,creds, Config.AAF_APPPASS,null);
802 directedPut(pa, filesymm, normal,creds, Config.AAF_URL, Defaults.AAF_URL);
805 String cts = pa.getProperty(Config.CADI_TRUSTSTORE);
807 File origTruststore = new File(cts);
808 if(!origTruststore.exists()) {
809 // Try same directory as cadi_prop_files
810 String cpf = pa.getProperty(Config.CADI_PROP_FILES);
812 for(String f : Split.split(File.pathSeparatorChar, cpf)) {
813 File fcpf = new File(f);
815 int lastSep = cts.lastIndexOf(File.pathSeparator);
816 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
817 if(origTruststore.exists()) {
822 if(!origTruststore.exists()) {
823 throw new CadiException(cts + " does not exist");
828 File newTruststore = new File(dir,origTruststore.getName());
829 if(!newTruststore.exists()) {
830 Files.copy(origTruststore.toPath(), newTruststore.toPath());
833 directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE,newTruststore.getCanonicalPath());
834 directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE_PASSWORD,null);
837 if(aafcon!=null) { // get Properties from Remote AAF
838 final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
840 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
841 .read("/configure/"+fqi+"/aaf", configDF);
842 if(acf.get(TIMEOUT)) {
843 for(Props props : acf.value.getProps()) {
844 directedPut(pa, filesymm, normal,creds, props.getTag(),props.getValue());
847 } else if(acf.code()==401){
848 trans.error().log("Bad Password sent to AAF");
850 trans.error().log(errMsg.toMsg(acf));
853 String cpf = pa.getProperty(Config.CADI_PROP_FILES);
855 for(String f : Split.split(File.pathSeparatorChar, cpf)) {
856 System.out.format("Reading %s\n",f);
857 FileInputStream fis = new FileInputStream(f);
859 Properties props = new Properties();
861 for(Entry<Object, Object> prop : props.entrySet()) {
862 directedPut(pa, filesymm, normal,creds, prop.getKey().toString(),prop.getValue().toString());
872 for(Entry<String, String> es : normal.entrySet()) {
873 psProps.print(es.getKey());
875 psProps.println(es.getValue());
878 for(Entry<String, String> es : creds.entrySet()) {
879 psCredProps.print(es.getKey());
880 psCredProps.print('=');
881 psCredProps.println(es.getValue());
884 File newFile = new File(dir,rootFile+".props");
885 if(newFile.exists()) {
886 File backup = new File(dir,rootFile+".props.backup");
887 newFile.renameTo(backup);
888 System.out.println("Backed up to " + backup.getCanonicalPath());
890 fProps.renameTo(newFile);
891 System.out.println("Created " + newFile.getCanonicalPath());
894 if(fSecureProps.exists()) {
895 File backup = new File(dir,fSecureProps.getName()+".backup");
896 fSecureProps.renameTo(backup);
897 System.out.println("Backed up to " + backup.getCanonicalPath());
899 fSecureTempProps.renameTo(fSecureProps);
900 System.out.println("Created " + fSecureProps.getCanonicalPath());
904 fSecureTempProps.delete();
917 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
919 Config.AAF_APPID, Config.AAF_APPPASS,
920 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
921 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
922 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
925 private static List<String> LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE});
927 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 {
928 if(!LOC_TAGS.contains(tag)) { // Location already covered
929 String val = value==null?orig.getProperty(tag):value;
930 if(tag.endsWith("_password")) {
932 if(val.startsWith("enc:")) {
933 val = orig.decrypt(val, true);
935 val = "enc:" + symm.enpass(val);
938 if(CRED_TAGS.contains(tag)) {
939 secured.put(tag, val);
946 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
947 System.out.println("Validating Configuration...");
948 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
949 aafcon.best(new Retryable<Void>() {
951 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
952 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
953 if(fc.get(aafcon.timeout)) {
954 System.out.print("Success connecting to ");
955 System.out.println(client.getURI());
956 System.out.print(" Permissions for ");
957 System.out.println(aafcon.defID());
958 for(Perm p : fc.value.getPerm()) {
959 System.out.print('\t');
960 System.out.print(p.getType());
961 System.out.print('|');
962 System.out.print(p.getInstance());
963 System.out.print('|');
964 System.out.println(p.getAction());
967 System.err.println("Error: " + fc.code() + ' ' + fc.body());
975 * Check returns Error Codes, so that Scripts can know what to do
977 * 0 - Check Complete, nothing to do
979 * 2 - Error for specific Artifact - read check.msg
980 * 10 - Certificate Updated - check.msg is email content
988 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
990 String mechID = fqi(cmds);
991 String machine = machine(cmds);
993 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
996 Future<Artifacts> acf = aafcon.client(CM_VER)
997 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
998 if(acf.get(TIMEOUT)) {
999 // Have to wait for JDK 1.7 source...
1000 //switch(artifact.getType()) {
1001 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1002 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1004 String id = aafcon.defID();
1005 GregorianCalendar now = new GregorianCalendar();
1006 for(Artifact a : acf.value.getArtifact()) {
1007 if(id.equals(a.getMechid())) {
1008 File dir = new File(a.getDir());
1009 Properties props = new Properties();
1010 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1020 if((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1021 !(f=new File(prop)).exists()) {
1022 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1023 a.getMechid(), a.getMachine());
1025 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1026 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1027 if(ksf==null || ksps == null) {
1028 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1029 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1031 KeyStore ks = KeyStore.getInstance("JKS");
1032 Symm symm = Symm.obtain(f);
1034 fis = new FileInputStream(ksf);
1036 ks.load(fis,symm.depass(ksps).toCharArray());
1040 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1044 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1045 a.getMechid(), a.getMachine(), ksf);
1046 trans.error().log(msg);
1049 GregorianCalendar renew = new GregorianCalendar();
1050 renew.setTime(cert.getNotAfter());
1051 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1052 if(renew.after(now)) {
1053 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",
1054 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1055 trans.info().log(msg);
1058 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1059 a.getMechid(), a.getMachine(),cert.getNotAfter());
1060 cmds.offerLast(mechID);
1061 cmds.offerLast(machine);
1062 if(placeCerts(trans,aafcon,cmds)) {
1063 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1064 a.getMechid(), a.getMachine());
1065 exitCode = 10; // Refreshed
1067 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1068 a.getMechid(), a.getMachine());
1069 exitCode = 1; // Error Renewing
1074 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1076 fos.write(msg.getBytes());
1088 trans.error().log(errMsg.toMsg(acf));