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.net.ConnectException;
29 import java.net.HttpURLConnection;
30 import java.net.InetAddress;
31 import java.net.UnknownHostException;
32 import java.nio.file.Files;
33 import java.security.KeyPair;
34 import java.security.KeyStore;
35 import java.security.cert.X509Certificate;
36 import java.util.ArrayDeque;
37 import java.util.Arrays;
38 import java.util.Deque;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
44 import java.util.Map.Entry;
45 import java.util.Properties;
47 import org.onap.aaf.cadi.Access;
48 import org.onap.aaf.cadi.CadiException;
49 import org.onap.aaf.cadi.CmdLine;
50 import org.onap.aaf.cadi.LocatorException;
51 import org.onap.aaf.cadi.PropAccess;
52 import org.onap.aaf.cadi.Symm;
53 import org.onap.aaf.cadi.aaf.Defaults;
54 import org.onap.aaf.cadi.aaf.client.ErrMessage;
55 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
56 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
57 import org.onap.aaf.cadi.client.Future;
58 import org.onap.aaf.cadi.client.Rcli;
59 import org.onap.aaf.cadi.client.Retryable;
60 import org.onap.aaf.cadi.config.Config;
61 import org.onap.aaf.cadi.config.SecurityInfoC;
62 import org.onap.aaf.cadi.http.HBasicAuthSS;
63 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
64 import org.onap.aaf.cadi.sso.AAFSSO;
65 import org.onap.aaf.cadi.util.Chmod;
66 import org.onap.aaf.cadi.util.FQI;
67 import org.onap.aaf.misc.env.APIException;
68 import org.onap.aaf.misc.env.Data.TYPE;
69 import org.onap.aaf.misc.env.Env;
70 import org.onap.aaf.misc.env.TimeTaken;
71 import org.onap.aaf.misc.env.Trans;
72 import org.onap.aaf.misc.env.util.Chrono;
73 import org.onap.aaf.misc.env.util.Split;
74 import org.onap.aaf.misc.rosetta.env.RosettaDF;
75 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
78 import aaf.v2_0.Perms;
79 import certman.v1_0.Artifacts;
80 import certman.v1_0.Artifacts.Artifact;
81 import certman.v1_0.CertInfo;
82 import certman.v1_0.CertificateRequest;
83 import locate.v1_1.Configuration;
84 import locate.v1_1.Configuration.Props;
87 private static final String HASHES = "################################################################";
88 private static final String PRINT = "print";
89 private static final String FILE = "file";
90 public static final String PKCS12 = "pkcs12";
91 public static final String JKS = "jks";
92 private static final String SCRIPT="script";
94 private static final String CM_VER = "1.0";
95 public static final int PASS_SIZE = 24;
96 private static int TIMEOUT;
98 private static RosettaDF<CertificateRequest> reqDF;
99 private static RosettaDF<CertInfo> certDF;
100 private static RosettaDF<Artifacts> artifactsDF;
101 private static RosettaDF<Configuration> configDF;
102 private static RosettaDF<Perms> permDF;
103 private static ErrMessage errMsg;
104 private static Map<String,PlaceArtifact> placeArtifact;
105 private static RosettaEnv env;
107 private static boolean doExit;
108 private static AAFCon<?> aafcon;
110 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
112 Config.AAF_APPID, Config.AAF_APPPASS,
113 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
114 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
115 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
119 public static void main(String[] args) {
122 if (args.length>0 && "cadi".equals(args[0])) {
123 String[] newArgs = new String[args.length-1];
124 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
125 if (newArgs.length==0) {
126 System.out.println(HASHES);
127 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
128 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
129 System.out.println(HASHES);
131 CmdLine.main(newArgs);
137 if (args.length>1 && args[0].equals("validate") ) {
138 int idx = args[1].indexOf('=');
140 access = new PropAccess(
141 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
143 (idx<0?args[1]:args[1].substring(idx+1)));
145 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
147 public Properties process(String[] args, Properties props) {
149 if (!args[0].equals("keypairgen")) {
150 props.put(Config.AAF_APPID, args[1]);
156 access = aafsso.access();
159 if (aafsso!=null && aafsso.loginOnly()) {
160 aafsso.setLogDefault();
162 System.out.println("AAF SSO information created in ~/.aaf");
164 env = new RosettaEnv(access.getProperties());
165 Deque<String> cmds = new ArrayDeque<String>();
166 for (String p : args) {
168 if ("-noexit".equalsIgnoreCase(p)) {
170 } else if ((eq=p.indexOf('=')) < 0) {
173 access.setProperty(p.substring(0,eq), p.substring(eq+1));
177 if (cmds.size()==0) {
179 aafsso.setLogDefault();
181 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
182 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
183 System.out.println(" create <FQI> [<machine>]");
184 System.out.println(" read <FQI> [<machine>]");
185 System.out.println(" update <FQI> [<machine>]");
186 System.out.println(" delete <FQI> [<machine>]");
187 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
188 System.out.println(" place <FQI> [<machine>]");
189 System.out.println(" showpass <FQI> [<machine>]");
190 System.out.println(" check <FQI> [<machine>]");
191 System.out.println(" keypairgen <FQI>");
192 System.out.println(" config <FQI>");
193 System.out.println(" validate <NS>.props>");
194 System.out.println(" --- Additional Tool Access ---");
195 System.out.println(" ** Type with no params for Tool Help");
196 System.out.println(" ** If using with Agent, preface with \"cadi\"");
197 System.out.println(" cadi <cadi tool params, see -?>");
204 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
206 reqDF = env.newDataFactory(CertificateRequest.class);
207 artifactsDF = env.newDataFactory(Artifacts.class);
208 certDF = env.newDataFactory(CertInfo.class);
209 configDF = env.newDataFactory(Configuration.class);
210 permDF = env.newDataFactory(Perms.class);
211 errMsg = new ErrMessage(env);
213 placeArtifact = new HashMap<>();
214 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
215 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
216 placeArtifact.put(FILE, new PlaceArtifactInFiles());
217 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
218 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
220 Trans trans = env.newTrans();
222 if ((token=access.getProperty("oauth_token"))!=null) {
223 trans.setProperty("oauth_token", token);
227 // show Std out again
228 aafsso.setLogDefault();
229 aafsso.setStdErrDefault();
231 // if CM_URL can be obtained, add to sso.props, if written
232 String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL_DEF);
234 aafsso.addProp(Config.CM_URL, cm_url);
241 String cmd = cmds.removeFirst();
244 placeCerts(trans,aafcon(access),cmds);
247 createArtifact(trans, aafcon(access),cmds);
250 readArtifact(trans, aafcon(access), cmds);
253 copyArtifact(trans, aafcon(access), cmds);
256 updateArtifact(trans, aafcon(access), cmds);
259 deleteArtifact(trans, aafcon(access), cmds);
262 showPass(trans, aafcon(access), cmds);
265 keypairGen(trans, access, cmds);
268 config(trans,access,args,cmds);
275 exitCode = check(trans,aafcon(access),cmds);
276 } catch (Exception e) {
282 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
285 StringBuilder sb = new StringBuilder();
286 trans.auditTrail(4, sb, Trans.REMOTE);
288 trans.info().log("Trans Info\n",sb);
295 } catch (Exception e) {
299 if (exitCode != 0 && doExit) {
300 System.exit(exitCode);
304 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
306 aafcon = new AAFConHttp(access,Config.CM_URL);
311 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
313 if ((value=pa.getProperty(tag))==null) {
315 value = new String(AAFSSO.cons.readPassword(prompt, def));
317 value = AAFSSO.cons.readLine(prompt,def).trim();
320 if (value.length()>0) {
321 pa.setProperty(tag,value);
322 env.setProperty(tag,value);
323 } else if (def.length==1) {
324 value=def[0].toString();
325 pa.setProperty(tag,value);
326 env.setProperty(tag,value);
333 private static String fqi(Deque<String> cmds) {
335 String alias = env.getProperty(Config.CADI_ALIAS);
336 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
338 return cmds.removeFirst();
341 private static String machine(Deque<String> cmds) throws UnknownHostException {
343 return cmds.removeFirst();
345 String mach = env.getProperty(Config.HOSTNAME);
346 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
350 private static String[] machines(Deque<String> cmds) {
353 machines = cmds.removeFirst();
355 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
357 return Split.split(',', machines);
360 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
361 final String mechID = fqi(cmds);
362 final String machine = machine(cmds);
364 Artifacts artifacts = new Artifacts();
365 Artifact arti = new Artifact();
366 artifacts.getArtifact().add(arti);
367 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
368 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
369 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
371 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
372 for (String s : Split.splitTrim(',', resp)) {
373 arti.getType().add(s);
376 if (!resp.contains(SCRIPT)) {
377 arti.getType().add(SCRIPT);
380 // Note: Sponsor is set on Creation by CM
381 String configRootName = FQI.reverseDomain(arti.getMechid());
382 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
383 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
384 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
385 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
386 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
388 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
390 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
391 if (future.get(TIMEOUT)) {
392 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
394 trans.error().printf("Call to AAF Certman failed, %s",
395 errMsg.toMsg(future));
402 private static String toNotification(String notification) {
403 if (notification==null) {
405 } else if (notification.length()>0) {
406 if (notification.indexOf(':')<0) {
407 notification = "mailto:" + notification;
414 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
415 String mechID = fqi(cmds);
416 String machine = machine(cmds);
418 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
420 Future<Artifacts> future = aafcon.client(CM_VER)
421 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
423 if (future.get(TIMEOUT)) {
424 boolean printed = false;
425 for (Artifact a : future.value.getArtifact()) {
426 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
427 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
428 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
429 AAFSSO.cons.printf("CA: %s\n",a.getCa());
430 StringBuilder sb = new StringBuilder();
431 boolean first = true;
432 for (String t : a.getType()) {
433 if (first) {first=false;}
434 else{sb.append(',');}
437 AAFSSO.cons.printf("Types: %s\n",sb);
438 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
439 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
440 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
441 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
442 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
446 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
449 trans.error().log(errMsg.toMsg(future));
456 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
457 String mechID = fqi(cmds);
458 String machine = machine(cmds);
459 String[] newmachs = machines(cmds);
460 if (machine==null || newmachs == null) {
461 trans.error().log("No machines listed to copy to");
463 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
465 Future<Artifacts> future = aafcon.client(CM_VER)
466 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
468 if (future.get(TIMEOUT)) {
469 boolean printed = false;
470 for (Artifact a : future.value.getArtifact()) {
471 for (String m : newmachs) {
473 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
474 if (fup.get(TIMEOUT)) {
475 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
477 trans.error().printf("Call to AAF Certman failed, %s",
485 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
488 trans.error().log(errMsg.toMsg(future));
496 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
497 String mechID = fqi(cmds);
498 String machine = machine(cmds);
500 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
502 Future<Artifacts> fread = aafcon.client(CM_VER)
503 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
505 if (fread.get(TIMEOUT)) {
506 Artifacts artifacts = new Artifacts();
507 for (Artifact a : fread.value.getArtifact()) {
508 Artifact arti = new Artifact();
509 artifacts.getArtifact().add(arti);
511 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
512 arti.setMechid(a.getMechid());
513 arti.setMachine(a.getMachine());
514 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
515 StringBuilder sb = new StringBuilder();
516 boolean first = true;
517 for (String t : a.getType()) {
518 if (first) {first=false;}
519 else{sb.append(',');}
523 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
524 for (String s : Split.splitTrim(',', resp)) {
525 arti.getType().add(s);
528 if (!resp.contains(SCRIPT)) {
529 arti.getType().add(SCRIPT);
532 // Note: Sponsor is set on Creation by CM
533 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
534 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
535 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
536 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
537 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
540 if (artifacts.getArtifact().size()==0) {
541 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
543 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
544 if (fup.get(TIMEOUT)) {
545 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
547 trans.error().printf("Call to AAF Certman failed, %s",
552 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
553 errMsg.toMsg(fread),mechID,machine);
560 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
561 String mechid = fqi(cmds);
562 String machine = machine(cmds);
564 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
566 Future<Void> future = aafcon.client(CM_VER)
567 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
569 if (future.get(TIMEOUT)) {
570 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
572 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
573 errMsg.toMsg(future),mechid,machine);
582 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
584 String mechID = fqi(cmds);
585 String machine = machine(cmds);
586 String[] fqdns = Split.split(':', machine);
588 if (fqdns.length>1) {
595 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
597 Future<Artifacts> acf = aafcon.client(CM_VER)
598 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
599 if (acf.get(TIMEOUT)) {
600 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
601 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
603 for (Artifact a : acf.value.getArtifact()) {
604 String osID = System.getProperty("user.name");
605 if (a.getOsUser().equals(osID)) {
606 CertificateRequest cr = new CertificateRequest();
607 cr.setMechid(a.getMechid());
608 cr.setSponsor(a.getSponsor());
609 for (int i=0;i<fqdns.length;++i) {
610 cr.getFqdns().add(fqdns[i]);
612 Future<String> f = aafcon.client(CM_VER)
613 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
614 if (f.get(TIMEOUT)) {
615 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
616 for (String type : a.getType()) {
617 PlaceArtifact pa = placeArtifact.get(type);
619 if (rv = pa.place(trans, capi, a,machine)) {
624 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
626 trans.error().log(errMsg.toMsg(f));
629 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
633 PropHolder.writeAll();
635 trans.error().log(errMsg.toMsg(acf));
643 private static void notifyPlaced(Artifact a, boolean rv) {
646 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
647 String mechID = fqi(cmds);
648 String machine = machine(cmds);
650 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
652 Future<Artifacts> acf = aafcon.client(CM_VER)
653 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
654 if (acf.get(TIMEOUT)) {
655 // Have to wait for JDK 1.7 source...
656 //switch(artifact.getType()) {
657 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
658 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
660 String id = aafcon.defID();
662 for (Artifact a : acf.value.getArtifact()) {
663 allowed = id!=null && (id.equals(a.getSponsor()) ||
664 (id.equals(a.getMechid())
665 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
667 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
668 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
669 if (pf.get(TIMEOUT)) {
672 trans.error().log(errMsg.toMsg(pf));
676 File dir = new File(a.getDir());
677 Properties props = new Properties();
678 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
681 File chalFile = new File(dir,a.getNs()+".chal");
682 if(chalFile.exists()) {
684 fis = new FileInputStream(chalFile);
691 File f = new File(dir,a.getNs()+".keyfile");
693 Symm symm = ArtifactDir.getSymm(f);
695 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
696 Entry<Object,Object> en = iter.next();
697 if (en.getValue().toString().startsWith("enc:")) {
698 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
702 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
703 f.getAbsolutePath(),a.getMechid(), a.getMachine());
709 trans.error().log(errMsg.toMsg(acf));
717 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
718 final String fqi = fqi(cmds);
719 final String ns = FQI.reverseDomain(fqi);
720 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
721 File f = new File(dir,ns+".key");
724 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
725 if (!"Y".equalsIgnoreCase(line)) {
726 System.out.println("Canceling...");
731 KeyPair kp = Factory.generateKeyPair(trans);
732 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
733 System.out.printf("Wrote %s\n", f.getCanonicalFile());
735 f=new File(dir,ns+".pubkey");
736 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
737 System.out.printf("Wrote %s\n", f.getCanonicalFile());
740 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
741 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
743 final String fqi = fqi(cmds);
744 Artifact arti = new Artifact();
745 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, "."));
746 arti.setNs(FQI.reverseDomain(fqi));
748 PropHolder loc = PropHolder.get(arti, "location.props");
749 PropHolder cred = PropHolder.get(arti,"cred.props");
750 PropHolder app= PropHolder.get(arti,"props");
751 for(String c : args) {
752 int idx = c.indexOf('=');
754 app.add(c.substring(0,idx), c.substring(idx+1));
757 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
759 for (String tag : LOC_TAGS) {
760 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
763 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
764 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
765 if(fqi.equals(ssoAppID)) {
766 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
767 // only Ask for Password when starting scratch
768 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
769 char[] pwd = AAFSSO.cons.readPassword("Password for %s: ", fqi);
771 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
775 app.add(Config.AAF_LOCATE_URL, propAccess, null);
776 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
777 String key = aaf_loc_prop.getKey().toString();
778 if(key.startsWith("aaf_locator")) {
779 app.add(key, aaf_loc_prop.getValue().toString());
783 app.add(Config.AAF_APPID, fqi);
784 app.add(Config.AAF_URL, propAccess, Config.AAF_URL_DEF);
786 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
788 File origTruststore = new File(cts);
789 if (!origTruststore.exists()) {
790 // Try same directory as cadi_prop_files
791 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
793 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
794 File fcpf = new File(f);
796 int lastSep = cts.lastIndexOf(File.pathSeparator);
797 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
798 if (origTruststore.exists()) {
803 if (!origTruststore.exists()) {
804 throw new CadiException(cts + " does not exist");
809 File newTruststore = new File(app.getDir(),origTruststore.getName());
810 if (!newTruststore.exists()) {
811 Files.copy(origTruststore.toPath(), newTruststore.toPath());
814 cred.add(Config.CADI_TRUSTSTORE, propAccess, newTruststore.getCanonicalPath());
815 cred.addEnc(Config.CADI_TRUSTSTORE_PASSWORD, propAccess, "changeit" /* Java default */);
817 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
819 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
820 System.out.format("Reading %s\n",f);
821 FileInputStream fis = new FileInputStream(f);
823 Properties props = new Properties();
825 for (Entry<Object, Object> prop : props.entrySet()) {
826 boolean lower = true;
827 String key = prop.getKey().toString();
828 for(int i=0;lower && i<key.length();++i) {
829 if(Character.isUpperCase(key.charAt(i))) {
834 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
835 if(key.endsWith("_password")) {
836 ph.addEnc(key, prop.getValue().toString());
838 ph.add(key, prop.getValue().toString());
847 aafcon = aafcon(propAccess);
848 if (aafcon!=null) { // get Properties from Remote AAF
849 final String locator = getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
851 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
852 .read("/configure/"+fqi+"/aaf", configDF);
853 if (acf.get(TIMEOUT)) {
854 for (Props props : acf.value.getProps()) {
855 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
856 if(props.getTag().endsWith("_password")) {
857 ph.addEnc(props.getTag(), props.getValue());
859 ph.add(props.getTag(), props.getValue());
862 } else if (acf.code()==401){
863 trans.error().log("Bad Password sent to AAF");
864 } else if (acf.code()==404){
865 trans.error().log("This version of AAF does not support remote Properties");
867 trans.error().log(errMsg.toMsg(acf));
873 PropHolder.writeAll();
880 private static List<String> LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE});
882 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
883 System.out.println("Validating Configuration...");
884 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
885 aafcon.best(new Retryable<Void>() {
887 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
888 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
889 if (fc.get(aafcon.timeout)) {
890 System.out.print("Success connecting to ");
891 System.out.println(client.getURI());
892 System.out.print(" Permissions for ");
893 System.out.println(aafcon.defID());
894 for (Perm p : fc.value.getPerm()) {
895 System.out.print('\t');
896 System.out.print(p.getType());
897 System.out.print('|');
898 System.out.print(p.getInstance());
899 System.out.print('|');
900 System.out.println(p.getAction());
903 System.err.println("Error: " + fc.code() + ' ' + fc.body());
911 * Check returns Error Codes, so that Scripts can know what to do
913 * 0 - Check Complete, nothing to do
915 * 2 - Error for specific Artifact - read check.msg
916 * 10 - Certificate Updated - check.msg is email content
924 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
926 String mechID = fqi(cmds);
927 String machine = machine(cmds);
929 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
932 Future<Artifacts> acf = aafcon.client(CM_VER)
933 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
934 if (acf.get(TIMEOUT)) {
935 // Have to wait for JDK 1.7 source...
936 //switch(artifact.getType()) {
937 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
938 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
940 String id = aafcon.defID();
941 GregorianCalendar now = new GregorianCalendar();
942 for (Artifact a : acf.value.getArtifact()) {
943 if (id.equals(a.getMechid())) {
944 File dir = new File(a.getDir());
945 Properties props = new Properties();
946 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
956 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
957 !(f=new File(prop)).exists()) {
958 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
959 a.getMechid(), a.getMachine());
961 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
962 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
963 if (ksf==null || ksps == null) {
964 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
965 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
967 Symm symm = ArtifactDir.getSymm(f);
969 KeyStore ks = KeyStore.getInstance("JKS");
971 fis = new FileInputStream(ksf);
973 ks.load(fis,symm.depass(ksps).toCharArray());
977 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
981 msg = String.format("X509Certificate does not exist for %s on %s in %s",
982 a.getMechid(), a.getMachine(), ksf);
983 trans.error().log(msg);
986 GregorianCalendar renew = new GregorianCalendar();
987 renew.setTime(cert.getNotAfter());
988 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
989 if (renew.after(now)) {
990 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",
991 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
992 trans.info().log(msg);
995 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
996 a.getMechid(), a.getMachine(),cert.getNotAfter());
997 cmds.offerLast(mechID);
998 cmds.offerLast(machine);
999 if (placeCerts(trans,aafcon,cmds)) {
1000 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1001 a.getMechid(), a.getMachine());
1002 exitCode = 10; // Refreshed
1004 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1005 a.getMechid(), a.getMachine());
1006 exitCode = 1; // Error Renewing
1011 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1013 fos.write(msg.getBytes());
1025 trans.error().log(errMsg.toMsg(acf));