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.CadiException;
48 import org.onap.aaf.cadi.CmdLine;
49 import org.onap.aaf.cadi.LocatorException;
50 import org.onap.aaf.cadi.PropAccess;
51 import org.onap.aaf.cadi.Symm;
52 import org.onap.aaf.cadi.aaf.Defaults;
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) {
166 if ("-noexit".equalsIgnoreCase(p)) {
168 } else if (p.indexOf('=') < 0) {
173 if (cmds.size()==0) {
175 aafsso.setLogDefault();
177 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
178 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
179 System.out.println(" create <FQI> [<machine>]");
180 System.out.println(" read <FQI> [<machine>]");
181 System.out.println(" update <FQI> [<machine>]");
182 System.out.println(" delete <FQI> [<machine>]");
183 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
184 System.out.println(" place <FQI> [<machine>]");
185 System.out.println(" showpass <FQI> [<machine>]");
186 System.out.println(" check <FQI> [<machine>]");
187 System.out.println(" keypairgen <FQI>");
188 System.out.println(" config <FQI>");
189 System.out.println(" validate <NS>.props>");
190 System.out.println(" --- Additional Tool Access ---");
191 System.out.println(" ** Type with no params for Tool Help");
192 System.out.println(" ** If using with Agent, preface with \"cadi\"");
193 System.out.println(" cadi <cadi tool params, see -?>");
200 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
202 reqDF = env.newDataFactory(CertificateRequest.class);
203 artifactsDF = env.newDataFactory(Artifacts.class);
204 certDF = env.newDataFactory(CertInfo.class);
205 configDF = env.newDataFactory(Configuration.class);
206 permDF = env.newDataFactory(Perms.class);
207 errMsg = new ErrMessage(env);
209 placeArtifact = new HashMap<>();
210 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
211 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
212 placeArtifact.put(FILE, new PlaceArtifactInFiles());
213 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
214 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
216 Trans trans = env.newTrans();
218 if ((token=access.getProperty("oauth_token"))!=null) {
219 trans.setProperty("oauth_token", token);
223 // show Std out again
224 aafsso.setLogDefault();
225 aafsso.setStdErrDefault();
227 // if CM_URL can be obtained, add to sso.props, if written
228 String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": ");
230 aafsso.addProp(Config.CM_URL, cm_url);
237 String cmd = cmds.removeFirst();
240 placeCerts(trans,aafcon(access),cmds);
243 createArtifact(trans, aafcon(access),cmds);
246 readArtifact(trans, aafcon(access), cmds);
249 copyArtifact(trans, aafcon(access), cmds);
252 updateArtifact(trans, aafcon(access), cmds);
255 deleteArtifact(trans, aafcon(access), cmds);
258 showPass(trans, aafcon(access), cmds);
261 keypairGen(trans, access, cmds);
264 if (access.getProperty(Config.CADI_PROP_FILES)!=null) {
265 // Get Properties from initialization Prop Files
266 config(trans,access,null,cmds);
268 // Get Properties from existing AAF Instance
269 config(trans,access,aafcon(access),cmds);
277 exitCode = check(trans,aafcon(access),cmds);
278 } catch (Exception e) {
284 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
287 StringBuilder sb = new StringBuilder();
288 trans.auditTrail(4, sb, Trans.REMOTE);
290 trans.info().log("Trans Info\n",sb);
297 } catch (Exception e) {
301 if (exitCode != 0 && doExit) {
302 System.exit(exitCode);
306 private static synchronized AAFCon<?> aafcon(PropAccess access) throws APIException, CadiException, LocatorException {
308 aafcon = new AAFConHttp(access,Config.CM_URL);
313 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
315 if ((value=pa.getProperty(tag))==null) {
317 value = new String(AAFSSO.cons.readPassword(prompt, def));
319 value = AAFSSO.cons.readLine(prompt,def).trim();
322 if (value.length()>0) {
323 pa.setProperty(tag,value);
324 env.setProperty(tag,value);
325 } else if (def.length==1) {
326 value=def[0].toString();
327 pa.setProperty(tag,value);
328 env.setProperty(tag,value);
335 private static String fqi(Deque<String> cmds) {
337 String alias = env.getProperty(Config.CADI_ALIAS);
338 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
340 return cmds.removeFirst();
343 private static String machine(Deque<String> cmds) throws UnknownHostException {
345 return cmds.removeFirst();
347 String mach = env.getProperty(Config.HOSTNAME);
348 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
352 private static String[] machines(Deque<String> cmds) {
355 machines = cmds.removeFirst();
357 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
359 return Split.split(',', machines);
362 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
363 final String mechID = fqi(cmds);
364 final String machine = machine(cmds);
366 Artifacts artifacts = new Artifacts();
367 Artifact arti = new Artifact();
368 artifacts.getArtifact().add(arti);
369 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
370 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
371 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
373 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
374 for (String s : Split.splitTrim(',', resp)) {
375 arti.getType().add(s);
378 if (!resp.contains(SCRIPT)) {
379 arti.getType().add(SCRIPT);
382 // Note: Sponsor is set on Creation by CM
383 String configRootName = FQI.reverseDomain(arti.getMechid());
384 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
385 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
386 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
387 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
388 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
390 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
392 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
393 if (future.get(TIMEOUT)) {
394 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
396 trans.error().printf("Call to AAF Certman failed, %s",
397 errMsg.toMsg(future));
404 private static String toNotification(String notification) {
405 if (notification==null) {
407 } else if (notification.length()>0) {
408 if (notification.indexOf(':')<0) {
409 notification = "mailto:" + notification;
416 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
417 String mechID = fqi(cmds);
418 String machine = machine(cmds);
420 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
422 Future<Artifacts> future = aafcon.client(CM_VER)
423 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
425 if (future.get(TIMEOUT)) {
426 boolean printed = false;
427 for (Artifact a : future.value.getArtifact()) {
428 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
429 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
430 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
431 AAFSSO.cons.printf("CA: %s\n",a.getCa());
432 StringBuilder sb = new StringBuilder();
433 boolean first = true;
434 for (String t : a.getType()) {
435 if (first) {first=false;}
436 else{sb.append(',');}
439 AAFSSO.cons.printf("Types: %s\n",sb);
440 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
441 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
442 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
443 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
444 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
448 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
451 trans.error().log(errMsg.toMsg(future));
458 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
459 String mechID = fqi(cmds);
460 String machine = machine(cmds);
461 String[] newmachs = machines(cmds);
462 if (machine==null || newmachs == null) {
463 trans.error().log("No machines listed to copy to");
465 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
467 Future<Artifacts> future = aafcon.client(CM_VER)
468 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
470 if (future.get(TIMEOUT)) {
471 boolean printed = false;
472 for (Artifact a : future.value.getArtifact()) {
473 for (String m : newmachs) {
475 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
476 if (fup.get(TIMEOUT)) {
477 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
479 trans.error().printf("Call to AAF Certman failed, %s",
487 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
490 trans.error().log(errMsg.toMsg(future));
498 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
499 String mechID = fqi(cmds);
500 String machine = machine(cmds);
502 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
504 Future<Artifacts> fread = aafcon.client(CM_VER)
505 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
507 if (fread.get(TIMEOUT)) {
508 Artifacts artifacts = new Artifacts();
509 for (Artifact a : fread.value.getArtifact()) {
510 Artifact arti = new Artifact();
511 artifacts.getArtifact().add(arti);
513 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
514 arti.setMechid(a.getMechid());
515 arti.setMachine(a.getMachine());
516 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
517 StringBuilder sb = new StringBuilder();
518 boolean first = true;
519 for (String t : a.getType()) {
520 if (first) {first=false;}
521 else{sb.append(',');}
525 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
526 for (String s : Split.splitTrim(',', resp)) {
527 arti.getType().add(s);
530 if (!resp.contains(SCRIPT)) {
531 arti.getType().add(SCRIPT);
534 // Note: Sponsor is set on Creation by CM
535 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
536 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
537 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
538 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
539 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
542 if (artifacts.getArtifact().size()==0) {
543 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
545 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
546 if (fup.get(TIMEOUT)) {
547 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
549 trans.error().printf("Call to AAF Certman failed, %s",
554 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
555 errMsg.toMsg(fread),mechID,machine);
562 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
563 String mechid = fqi(cmds);
564 String machine = machine(cmds);
566 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
568 Future<Void> future = aafcon.client(CM_VER)
569 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
571 if (future.get(TIMEOUT)) {
572 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
574 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
575 errMsg.toMsg(future),mechid,machine);
584 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
586 String mechID = fqi(cmds);
587 String machine = machine(cmds);
588 String[] fqdns = Split.split(':', machine);
590 if (fqdns.length>1) {
597 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
599 Future<Artifacts> acf = aafcon.client(CM_VER)
600 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
601 if (acf.get(TIMEOUT)) {
602 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
603 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
605 for (Artifact a : acf.value.getArtifact()) {
606 String osID = System.getProperty("user.name");
607 if (a.getOsUser().equals(osID)) {
608 CertificateRequest cr = new CertificateRequest();
609 cr.setMechid(a.getMechid());
610 cr.setSponsor(a.getSponsor());
611 for (int i=0;i<fqdns.length;++i) {
612 cr.getFqdns().add(fqdns[i]);
614 Future<String> f = aafcon.client(CM_VER)
615 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
616 if (f.get(TIMEOUT)) {
617 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
618 for (String type : a.getType()) {
619 PlaceArtifact pa = placeArtifact.get(type);
621 if (rv = pa.place(trans, capi, a,machine)) {
626 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
628 trans.error().log(errMsg.toMsg(f));
631 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
635 PropHolder.writeAll();
637 trans.error().log(errMsg.toMsg(acf));
645 private static void notifyPlaced(Artifact a, boolean rv) {
648 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
649 String mechID = fqi(cmds);
650 String machine = machine(cmds);
652 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
654 Future<Artifacts> acf = aafcon.client(CM_VER)
655 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
656 if (acf.get(TIMEOUT)) {
657 // Have to wait for JDK 1.7 source...
658 //switch(artifact.getType()) {
659 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
660 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
662 String id = aafcon.defID();
664 for (Artifact a : acf.value.getArtifact()) {
665 allowed = id!=null && (id.equals(a.getSponsor()) ||
666 (id.equals(a.getMechid())
667 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
669 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
670 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
671 if (pf.get(TIMEOUT)) {
674 trans.error().log(errMsg.toMsg(pf));
678 File dir = new File(a.getDir());
679 Properties props = new Properties();
680 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
683 File chalFile = new File(dir,a.getNs()+".chal");
684 if(chalFile.exists()) {
686 fis = new FileInputStream(chalFile);
693 File f = new File(dir,a.getNs()+".keyfile");
695 Symm symm = ArtifactDir.getSymm(f);
697 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
698 Entry<Object,Object> en = iter.next();
699 if (en.getValue().toString().startsWith("enc:")) {
700 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
704 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
705 f.getAbsolutePath(),a.getMechid(), a.getMachine());
711 trans.error().log(errMsg.toMsg(acf));
719 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
720 final String fqi = fqi(cmds);
721 final String ns = FQI.reverseDomain(fqi);
722 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
723 File f = new File(dir,ns+".key");
726 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
727 if (!"Y".equalsIgnoreCase(line)) {
728 System.out.println("Canceling...");
733 KeyPair kp = Factory.generateKeyPair(trans);
734 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
735 System.out.printf("Wrote %s\n", f.getCanonicalFile());
737 f=new File(dir,ns+".pubkey");
738 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
739 System.out.printf("Wrote %s\n", f.getCanonicalFile());
742 private static void config(Trans trans, PropAccess pa, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
744 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
746 final String fqi = fqi(cmds);
747 Artifact arti = new Artifact();
748 arti.setDir(pa.getProperty(Config.CADI_ETCDIR, "."));
749 arti.setNs(FQI.reverseDomain(fqi));
751 PropHolder loc = PropHolder.get(arti, "location.props");
752 PropHolder cred = PropHolder.get(arti,"cred.props");
753 PropHolder app= PropHolder.get(arti,"props");
754 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
756 for (String tag : LOC_TAGS) {
757 loc.add(tag, getProperty(pa, trans, false, tag, "%s: ",tag));
760 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
761 cred.addEnc(Config.AAF_APPPASS, pa, null);
763 app.add(Config.AAF_LOCATE_URL, pa, null);
764 app.add(Config.AAF_APPID, fqi);
765 app.add(Config.AAF_URL, pa, Defaults.AAF_URL);
767 String cts = pa.getProperty(Config.CADI_TRUSTSTORE);
769 File origTruststore = new File(cts);
770 if (!origTruststore.exists()) {
771 // Try same directory as cadi_prop_files
772 String cpf = pa.getProperty(Config.CADI_PROP_FILES);
774 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
775 File fcpf = new File(f);
777 int lastSep = cts.lastIndexOf(File.pathSeparator);
778 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
779 if (origTruststore.exists()) {
784 if (!origTruststore.exists()) {
785 throw new CadiException(cts + " does not exist");
790 File newTruststore = new File(app.getDir(),origTruststore.getName());
791 if (!newTruststore.exists()) {
792 Files.copy(origTruststore.toPath(), newTruststore.toPath());
795 cred.add(Config.CADI_TRUSTSTORE, pa, newTruststore.getCanonicalPath());
796 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, pa, "changeit" /* Java default */);
798 if (aafcon!=null) { // get Properties from Remote AAF
799 final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
801 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
802 .read("/configure/"+fqi+"/aaf", configDF);
803 if (acf.get(TIMEOUT)) {
804 for (Props props : acf.value.getProps()) {
805 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
806 if(props.getTag().endsWith("_password")) {
807 ph.addEnc(props.getTag(), props.getValue());
809 ph.add(props.getTag(), props.getValue());
812 } else if (acf.code()==401){
813 trans.error().log("Bad Password sent to AAF");
815 trans.error().log(errMsg.toMsg(acf));
818 String cpf = pa.getProperty(Config.CADI_PROP_FILES);
820 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
821 System.out.format("Reading %s\n",f);
822 FileInputStream fis = new FileInputStream(f);
824 Properties props = new Properties();
826 for (Entry<Object, Object> prop : props.entrySet()) {
827 boolean lower = true;
828 String key = prop.getKey().toString();
829 for(int i=0;lower && i<key.length();++i) {
830 if(Character.isUpperCase(key.charAt(i))) {
835 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
836 if(key.endsWith("_password")) {
837 ph.addEnc(key, prop.getValue().toString());
839 ph.add(key, prop.getValue().toString());
851 PropHolder.writeAll();
858 private static List<String> LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE});
860 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
861 System.out.println("Validating Configuration...");
862 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
863 aafcon.best(new Retryable<Void>() {
865 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
866 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
867 if (fc.get(aafcon.timeout)) {
868 System.out.print("Success connecting to ");
869 System.out.println(client.getURI());
870 System.out.print(" Permissions for ");
871 System.out.println(aafcon.defID());
872 for (Perm p : fc.value.getPerm()) {
873 System.out.print('\t');
874 System.out.print(p.getType());
875 System.out.print('|');
876 System.out.print(p.getInstance());
877 System.out.print('|');
878 System.out.println(p.getAction());
881 System.err.println("Error: " + fc.code() + ' ' + fc.body());
889 * Check returns Error Codes, so that Scripts can know what to do
891 * 0 - Check Complete, nothing to do
893 * 2 - Error for specific Artifact - read check.msg
894 * 10 - Certificate Updated - check.msg is email content
902 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
904 String mechID = fqi(cmds);
905 String machine = machine(cmds);
907 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
910 Future<Artifacts> acf = aafcon.client(CM_VER)
911 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
912 if (acf.get(TIMEOUT)) {
913 // Have to wait for JDK 1.7 source...
914 //switch(artifact.getType()) {
915 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
916 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
918 String id = aafcon.defID();
919 GregorianCalendar now = new GregorianCalendar();
920 for (Artifact a : acf.value.getArtifact()) {
921 if (id.equals(a.getMechid())) {
922 File dir = new File(a.getDir());
923 Properties props = new Properties();
924 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
934 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
935 !(f=new File(prop)).exists()) {
936 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
937 a.getMechid(), a.getMachine());
939 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
940 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
941 if (ksf==null || ksps == null) {
942 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
943 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
945 Symm symm = ArtifactDir.getSymm(f);
947 KeyStore ks = KeyStore.getInstance("JKS");
949 fis = new FileInputStream(ksf);
951 ks.load(fis,symm.depass(ksps).toCharArray());
955 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
959 msg = String.format("X509Certificate does not exist for %s on %s in %s",
960 a.getMechid(), a.getMachine(), ksf);
961 trans.error().log(msg);
964 GregorianCalendar renew = new GregorianCalendar();
965 renew.setTime(cert.getNotAfter());
966 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
967 if (renew.after(now)) {
968 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",
969 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
970 trans.info().log(msg);
973 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
974 a.getMechid(), a.getMachine(),cert.getNotAfter());
975 cmds.offerLast(mechID);
976 cmds.offerLast(machine);
977 if (placeCerts(trans,aafcon,cmds)) {
978 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
979 a.getMechid(), a.getMachine());
980 exitCode = 10; // Refreshed
982 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
983 a.getMechid(), a.getMachine());
984 exitCode = 1; // Error Renewing
989 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
991 fos.write(msg.getBytes());
1003 trans.error().log(errMsg.toMsg(acf));