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.client.ErrMessage;
54 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
55 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
56 import org.onap.aaf.cadi.client.Future;
57 import org.onap.aaf.cadi.client.Rcli;
58 import org.onap.aaf.cadi.client.Retryable;
59 import org.onap.aaf.cadi.config.Config;
60 import org.onap.aaf.cadi.config.SecurityInfoC;
61 import org.onap.aaf.cadi.http.HBasicAuthSS;
62 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
63 import org.onap.aaf.cadi.sso.AAFSSO;
64 import org.onap.aaf.cadi.util.Chmod;
65 import org.onap.aaf.cadi.util.FQI;
66 import org.onap.aaf.misc.env.APIException;
67 import org.onap.aaf.misc.env.Data.TYPE;
68 import org.onap.aaf.misc.env.Env;
69 import org.onap.aaf.misc.env.TimeTaken;
70 import org.onap.aaf.misc.env.Trans;
71 import org.onap.aaf.misc.env.util.Chrono;
72 import org.onap.aaf.misc.env.util.Split;
73 import org.onap.aaf.misc.rosetta.env.RosettaDF;
74 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
77 import aaf.v2_0.Perms;
78 import certman.v1_0.Artifacts;
79 import certman.v1_0.Artifacts.Artifact;
80 import certman.v1_0.CertInfo;
81 import certman.v1_0.CertificateRequest;
82 import locate.v1_1.Configuration;
83 import locate.v1_1.Configuration.Props;
86 private static final String HASHES = "################################################################";
87 private static final String PRINT = "print";
88 private static final String FILE = "file";
89 public static final String PKCS12 = "pkcs12";
90 public static final String JKS = "jks";
91 private static final String SCRIPT="script";
93 private static final String CM_VER = "1.0";
94 public static final int PASS_SIZE = 24;
95 private static int TIMEOUT;
97 private static RosettaDF<CertificateRequest> reqDF;
98 private static RosettaDF<CertInfo> certDF;
99 private static RosettaDF<Artifacts> artifactsDF;
100 private static RosettaDF<Configuration> configDF;
101 private static RosettaDF<Perms> permDF;
102 private static ErrMessage errMsg;
103 private static Map<String,PlaceArtifact> placeArtifact;
104 private static RosettaEnv env;
106 private static boolean doExit;
107 private static AAFCon<?> aafcon;
109 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
111 Config.AAF_APPID, Config.AAF_APPPASS,
112 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
113 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
114 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
118 public static void main(String[] args) {
121 if (args.length>0 && "cadi".equals(args[0])) {
122 String[] newArgs = new String[args.length-1];
123 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
124 if (newArgs.length==0) {
125 System.out.println(HASHES);
126 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
127 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
128 System.out.println(HASHES);
130 CmdLine.main(newArgs);
136 if (args.length>1 && args[0].equals("validate") ) {
137 int idx = args[1].indexOf('=');
139 access = new PropAccess(
140 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
142 (idx<0?args[1]:args[1].substring(idx+1)));
144 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
146 public Properties process(String[] args, Properties props) {
148 if (!args[0].equals("keypairgen")) {
149 props.put(Config.AAF_APPID, args[1]);
155 access = aafsso.access();
158 if (aafsso!=null && aafsso.loginOnly()) {
159 aafsso.setLogDefault();
161 System.out.println("AAF SSO information created in ~/.aaf");
163 env = new RosettaEnv(access.getProperties());
164 Deque<String> cmds = new ArrayDeque<String>();
165 for (String p : args) {
167 if ("-noexit".equalsIgnoreCase(p)) {
169 } else if ((eq=p.indexOf('=')) < 0) {
172 access.setProperty(p.substring(0,eq), p.substring(eq+1));
176 if (cmds.size()==0) {
178 aafsso.setLogDefault();
180 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
181 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
182 System.out.println(" create <FQI> [<machine>]");
183 System.out.println(" read <FQI> [<machine>]");
184 System.out.println(" update <FQI> [<machine>]");
185 System.out.println(" delete <FQI> [<machine>]");
186 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
187 System.out.println(" place <FQI> [<machine>]");
188 System.out.println(" showpass <FQI> [<machine>]");
189 System.out.println(" check <FQI> [<machine>]");
190 System.out.println(" keypairgen <FQI>");
191 System.out.println(" config <FQI>");
192 System.out.println(" validate <NS>.props>");
193 System.out.println(" --- Additional Tool Access ---");
194 System.out.println(" ** Type with no params for Tool Help");
195 System.out.println(" ** If using with Agent, preface with \"cadi\"");
196 System.out.println(" cadi <cadi tool params, see -?>");
203 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
205 reqDF = env.newDataFactory(CertificateRequest.class);
206 artifactsDF = env.newDataFactory(Artifacts.class);
207 certDF = env.newDataFactory(CertInfo.class);
208 configDF = env.newDataFactory(Configuration.class);
209 permDF = env.newDataFactory(Perms.class);
210 errMsg = new ErrMessage(env);
212 placeArtifact = new HashMap<>();
213 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
214 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
215 placeArtifact.put(FILE, new PlaceArtifactInFiles());
216 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
217 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
219 Trans trans = env.newTrans();
221 if ((token=access.getProperty("oauth_token"))!=null) {
222 trans.setProperty("oauth_token", token);
226 // show Std out again
227 aafsso.setLogDefault();
228 aafsso.setStdErrDefault();
230 // if CM_URL can be obtained, add to sso.props, if written
231 String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL_DEF);
233 aafsso.addProp(Config.CM_URL, cm_url);
240 String cmd = cmds.removeFirst();
243 placeCerts(trans,aafcon(access),cmds);
246 createArtifact(trans, aafcon(access),cmds);
249 readArtifact(trans, aafcon(access), cmds);
252 copyArtifact(trans, aafcon(access), cmds);
255 updateArtifact(trans, aafcon(access), cmds);
258 deleteArtifact(trans, aafcon(access), cmds);
261 showPass(trans, aafcon(access), cmds);
264 keypairGen(trans, access, cmds);
267 config(trans,access,args,cmds);
274 exitCode = check(trans,aafcon(access),cmds);
275 } catch (Exception e) {
281 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
284 StringBuilder sb = new StringBuilder();
285 trans.auditTrail(4, sb, Trans.REMOTE);
287 trans.info().log("Trans Info\n",sb);
294 } catch (Exception e) {
298 if (exitCode != 0 && doExit) {
299 System.exit(exitCode);
303 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
305 aafcon = new AAFConHttp(access,Config.CM_URL);
310 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
312 if ((value=pa.getProperty(tag))==null) {
314 value = new String(AAFSSO.cons.readPassword(prompt, def));
316 value = AAFSSO.cons.readLine(prompt,def).trim();
319 if (value.length()>0) {
320 pa.setProperty(tag,value);
321 env.setProperty(tag,value);
322 } else if (def.length==1) {
323 value=def[0].toString();
324 pa.setProperty(tag,value);
325 env.setProperty(tag,value);
332 private static String fqi(Deque<String> cmds) {
334 String alias = env.getProperty(Config.CADI_ALIAS);
335 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
337 return cmds.removeFirst();
340 private static String machine(Deque<String> cmds) throws UnknownHostException {
342 return cmds.removeFirst();
344 String mach = env.getProperty(Config.HOSTNAME);
345 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
349 private static String[] machines(Deque<String> cmds) {
352 machines = cmds.removeFirst();
354 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
356 return Split.split(',', machines);
359 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
360 final String mechID = fqi(cmds);
361 final String machine = machine(cmds);
363 Artifacts artifacts = new Artifacts();
364 Artifact arti = new Artifact();
365 artifacts.getArtifact().add(arti);
366 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
367 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
368 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
370 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
371 for (String s : Split.splitTrim(',', resp)) {
372 arti.getType().add(s);
375 if (!resp.contains(SCRIPT)) {
376 arti.getType().add(SCRIPT);
379 // Note: Sponsor is set on Creation by CM
380 String configRootName = FQI.reverseDomain(arti.getMechid());
381 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
382 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
383 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
384 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
385 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
387 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
389 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
390 if (future.get(TIMEOUT)) {
391 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
393 trans.error().printf("Call to AAF Certman failed, %s",
394 errMsg.toMsg(future));
401 private static String toNotification(String notification) {
402 if (notification==null) {
404 } else if (notification.length()>0) {
405 if (notification.indexOf(':')<0) {
406 notification = "mailto:" + notification;
413 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
414 String mechID = fqi(cmds);
415 String machine = machine(cmds);
417 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
419 Future<Artifacts> future = aafcon.client(CM_VER)
420 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
422 if (future.get(TIMEOUT)) {
423 boolean printed = false;
424 for (Artifact a : future.value.getArtifact()) {
425 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
426 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
427 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
428 AAFSSO.cons.printf("CA: %s\n",a.getCa());
429 StringBuilder sb = new StringBuilder();
430 boolean first = true;
431 for (String t : a.getType()) {
432 if (first) {first=false;}
433 else{sb.append(',');}
436 AAFSSO.cons.printf("Types: %s\n",sb);
437 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
438 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
439 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
440 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
441 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
445 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
448 trans.error().log(errMsg.toMsg(future));
455 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
456 String mechID = fqi(cmds);
457 String machine = machine(cmds);
458 String[] newmachs = machines(cmds);
459 if (machine==null || newmachs == null) {
460 trans.error().log("No machines listed to copy to");
462 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
464 Future<Artifacts> future = aafcon.client(CM_VER)
465 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
467 if (future.get(TIMEOUT)) {
468 boolean printed = false;
469 for (Artifact a : future.value.getArtifact()) {
470 for (String m : newmachs) {
472 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
473 if (fup.get(TIMEOUT)) {
474 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
476 trans.error().printf("Call to AAF Certman failed, %s",
484 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
487 trans.error().log(errMsg.toMsg(future));
495 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
496 String mechID = fqi(cmds);
497 String machine = machine(cmds);
499 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
501 Future<Artifacts> fread = aafcon.client(CM_VER)
502 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
504 if (fread.get(TIMEOUT)) {
505 Artifacts artifacts = new Artifacts();
506 for (Artifact a : fread.value.getArtifact()) {
507 Artifact arti = new Artifact();
508 artifacts.getArtifact().add(arti);
510 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
511 arti.setMechid(a.getMechid());
512 arti.setMachine(a.getMachine());
513 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
514 StringBuilder sb = new StringBuilder();
515 boolean first = true;
516 for (String t : a.getType()) {
517 if (first) {first=false;}
518 else{sb.append(',');}
522 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
523 for (String s : Split.splitTrim(',', resp)) {
524 arti.getType().add(s);
527 if (!resp.contains(SCRIPT)) {
528 arti.getType().add(SCRIPT);
531 // Note: Sponsor is set on Creation by CM
532 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
533 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
534 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
535 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
536 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
539 if (artifacts.getArtifact().size()==0) {
540 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
542 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
543 if (fup.get(TIMEOUT)) {
544 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
546 trans.error().printf("Call to AAF Certman failed, %s",
551 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
552 errMsg.toMsg(fread),mechID,machine);
559 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
560 String mechid = fqi(cmds);
561 String machine = machine(cmds);
563 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
565 Future<Void> future = aafcon.client(CM_VER)
566 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
568 if (future.get(TIMEOUT)) {
569 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
571 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
572 errMsg.toMsg(future),mechid,machine);
581 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
583 String mechID = fqi(cmds);
584 String machine = machine(cmds);
585 String[] fqdns = Split.split(':', machine);
587 if (fqdns.length>1) {
594 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
596 Future<Artifacts> acf = aafcon.client(CM_VER)
597 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
598 if (acf.get(TIMEOUT)) {
599 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
600 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
602 for (Artifact a : acf.value.getArtifact()) {
603 String osID = System.getProperty("user.name");
604 if (a.getOsUser().equals(osID)) {
605 CertificateRequest cr = new CertificateRequest();
606 cr.setMechid(a.getMechid());
607 cr.setSponsor(a.getSponsor());
608 for (int i=0;i<fqdns.length;++i) {
609 cr.getFqdns().add(fqdns[i]);
611 Future<String> f = aafcon.client(CM_VER)
612 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
613 if (f.get(TIMEOUT)) {
614 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
615 for (String type : a.getType()) {
616 PlaceArtifact pa = placeArtifact.get(type);
618 if (rv = pa.place(trans, capi, a,machine)) {
623 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
625 trans.error().log(errMsg.toMsg(f));
628 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
632 PropHolder.writeAll();
634 trans.error().log(errMsg.toMsg(acf));
642 private static void notifyPlaced(Artifact a, boolean rv) {
645 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
646 String mechID = fqi(cmds);
647 String machine = machine(cmds);
649 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
651 Future<Artifacts> acf = aafcon.client(CM_VER)
652 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
653 if (acf.get(TIMEOUT)) {
654 // Have to wait for JDK 1.7 source...
655 //switch(artifact.getType()) {
656 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
657 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
659 String id = aafcon.defID();
661 for (Artifact a : acf.value.getArtifact()) {
662 allowed = id!=null && (id.equals(a.getSponsor()) ||
663 (id.equals(a.getMechid())
664 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
666 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
667 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
668 if (pf.get(TIMEOUT)) {
671 trans.error().log(errMsg.toMsg(pf));
675 File dir = new File(a.getDir());
676 Properties props = new Properties();
677 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
680 File chalFile = new File(dir,a.getNs()+".chal");
681 if(chalFile.exists()) {
683 fis = new FileInputStream(chalFile);
690 File f = new File(dir,a.getNs()+".keyfile");
692 Symm symm = ArtifactDir.getSymm(f);
694 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
695 Entry<Object,Object> en = iter.next();
696 if (en.getValue().toString().startsWith("enc:")) {
697 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
701 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
702 f.getAbsolutePath(),a.getMechid(), a.getMachine());
708 trans.error().log(errMsg.toMsg(acf));
716 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
717 final String fqi = fqi(cmds);
718 final String ns = FQI.reverseDomain(fqi);
719 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
720 File f = new File(dir,ns+".key");
723 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
724 if (!"Y".equalsIgnoreCase(line)) {
725 System.out.println("Canceling...");
730 KeyPair kp = Factory.generateKeyPair(trans);
731 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
732 System.out.printf("Wrote %s\n", f.getCanonicalFile());
734 f=new File(dir,ns+".pubkey");
735 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
736 System.out.printf("Wrote %s\n", f.getCanonicalFile());
739 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
740 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
742 final String fqi = fqi(cmds);
743 Artifact arti = new Artifact();
744 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, "."));
745 arti.setNs(FQI.reverseDomain(fqi));
747 PropHolder loc = PropHolder.get(arti, "location.props");
748 PropHolder cred = PropHolder.get(arti,"cred.props");
749 PropHolder app= PropHolder.get(arti,"props");
750 for(String c : args) {
751 int idx = c.indexOf('=');
753 app.add(c.substring(0,idx), c.substring(idx+1));
756 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
758 for (String tag : LOC_TAGS) {
759 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
762 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
763 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
764 if(fqi.equals(ssoAppID)) {
765 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
766 // only Ask for Password when starting scratch
767 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
768 char[] pwd = AAFSSO.cons.readPassword("Password for %s: ", fqi);
770 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
774 app.add(Config.AAF_LOCATE_URL, propAccess, null);
775 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
776 String key = aaf_loc_prop.getKey().toString();
777 if(key.startsWith("aaf_locator")) {
778 app.add(key, aaf_loc_prop.getValue().toString());
782 app.add(Config.AAF_APPID, fqi);
783 app.add(Config.AAF_URL, propAccess, Config.AAF_URL_DEF);
785 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
787 File origTruststore = new File(cts);
788 if (!origTruststore.exists()) {
789 // Try same directory as cadi_prop_files
790 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
792 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
793 File fcpf = new File(f);
795 int lastSep = cts.lastIndexOf(File.pathSeparator);
796 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
797 if (origTruststore.exists()) {
802 if (!origTruststore.exists()) {
803 throw new CadiException(cts + " does not exist");
808 File newTruststore = new File(app.getDir(),origTruststore.getName());
809 if (!newTruststore.exists()) {
810 Files.copy(origTruststore.toPath(), newTruststore.toPath());
813 cred.add(Config.CADI_TRUSTSTORE, propAccess, newTruststore.getCanonicalPath());
814 cred.addEnc(Config.CADI_TRUSTSTORE_PASSWORD, propAccess, "changeit" /* Java default */);
816 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
818 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
819 System.out.format("Reading %s\n",f);
820 FileInputStream fis = new FileInputStream(f);
822 Properties props = new Properties();
824 for (Entry<Object, Object> prop : props.entrySet()) {
825 boolean lower = true;
826 String key = prop.getKey().toString();
827 for(int i=0;lower && i<key.length();++i) {
828 if(Character.isUpperCase(key.charAt(i))) {
833 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
834 if(key.endsWith("_password")) {
835 ph.addEnc(key, prop.getValue().toString());
837 ph.add(key, prop.getValue().toString());
846 aafcon = aafcon(propAccess);
847 if (aafcon!=null) { // get Properties from Remote AAF
848 final String locator = getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
850 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
851 .read("/configure/"+fqi+"/aaf", configDF);
852 if (acf.get(TIMEOUT)) {
853 for (Props props : acf.value.getProps()) {
854 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
855 if(props.getTag().endsWith("_password")) {
856 ph.addEnc(props.getTag(), props.getValue());
858 ph.add(props.getTag(), props.getValue());
861 } else if (acf.code()==401){
862 trans.error().log("Bad Password sent to AAF");
863 } else if (acf.code()==404){
864 trans.error().log("This version of AAF does not support remote Properties");
866 trans.error().log(errMsg.toMsg(acf));
872 PropHolder.writeAll();
879 private static List<String> LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE});
881 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
882 System.out.println("Validating Configuration...");
883 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
884 aafcon.best(new Retryable<Void>() {
886 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
887 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
888 if (fc.get(aafcon.timeout)) {
889 System.out.print("Success connecting to ");
890 System.out.println(client.getURI());
891 System.out.print(" Permissions for ");
892 System.out.println(aafcon.defID());
893 for (Perm p : fc.value.getPerm()) {
894 System.out.print('\t');
895 System.out.print(p.getType());
896 System.out.print('|');
897 System.out.print(p.getInstance());
898 System.out.print('|');
899 System.out.println(p.getAction());
902 System.err.println("Error: " + fc.code() + ' ' + fc.body());
910 * Check returns Error Codes, so that Scripts can know what to do
912 * 0 - Check Complete, nothing to do
914 * 2 - Error for specific Artifact - read check.msg
915 * 10 - Certificate Updated - check.msg is email content
923 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
925 String mechID = fqi(cmds);
926 String machine = machine(cmds);
928 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
931 Future<Artifacts> acf = aafcon.client(CM_VER)
932 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
933 if (acf.get(TIMEOUT)) {
934 // Have to wait for JDK 1.7 source...
935 //switch(artifact.getType()) {
936 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
937 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
939 String id = aafcon.defID();
940 GregorianCalendar now = new GregorianCalendar();
941 for (Artifact a : acf.value.getArtifact()) {
942 if (id.equals(a.getMechid())) {
943 File dir = new File(a.getDir());
944 Properties props = new Properties();
945 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
955 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
956 !(f=new File(prop)).exists()) {
957 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
958 a.getMechid(), a.getMachine());
960 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
961 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
962 if (ksf==null || ksps == null) {
963 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
964 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
966 Symm symm = ArtifactDir.getSymm(f);
968 KeyStore ks = KeyStore.getInstance("JKS");
970 fis = new FileInputStream(ksf);
972 ks.load(fis,symm.depass(ksps).toCharArray());
976 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
980 msg = String.format("X509Certificate does not exist for %s on %s in %s",
981 a.getMechid(), a.getMachine(), ksf);
982 trans.error().log(msg);
985 GregorianCalendar renew = new GregorianCalendar();
986 renew.setTime(cert.getNotAfter());
987 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
988 if (renew.after(now)) {
989 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",
990 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
991 trans.info().log(msg);
994 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
995 a.getMechid(), a.getMachine(),cert.getNotAfter());
996 cmds.offerLast(mechID);
997 cmds.offerLast(machine);
998 if (placeCerts(trans,aafcon,cmds)) {
999 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1000 a.getMechid(), a.getMachine());
1001 exitCode = 10; // Refreshed
1003 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1004 a.getMechid(), a.getMachine());
1005 exitCode = 1; // Error Renewing
1010 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1012 fos.write(msg.getBytes());
1024 trans.error().log(errMsg.toMsg(acf));