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.ArrayList;
38 import java.util.Arrays;
39 import java.util.Deque;
40 import java.util.GregorianCalendar;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
45 import java.util.Map.Entry;
46 import java.util.Properties;
48 import org.onap.aaf.cadi.Access;
49 import org.onap.aaf.cadi.CadiException;
50 import org.onap.aaf.cadi.CmdLine;
51 import org.onap.aaf.cadi.LocatorException;
52 import org.onap.aaf.cadi.PropAccess;
53 import org.onap.aaf.cadi.Symm;
54 import org.onap.aaf.cadi.aaf.TestConnectivity;
55 import org.onap.aaf.cadi.aaf.client.ErrMessage;
56 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
57 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
58 import org.onap.aaf.cadi.client.Future;
59 import org.onap.aaf.cadi.client.Rcli;
60 import org.onap.aaf.cadi.client.Retryable;
61 import org.onap.aaf.cadi.config.Config;
62 import org.onap.aaf.cadi.config.RegistrationPropHolder;
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 AGENT_LOAD_URLS = "Agent:loadURLs";
90 private static final String HASHES = "################################################################";
91 private static final String PRINT = "print";
92 private static final String FILE = "file";
93 public static final String PKCS12 = "pkcs12";
94 public static final String JKS = "jks";
95 private static final String SCRIPT="script";
97 private static final String CM_VER = "1.0";
98 public static final int PASS_SIZE = 24;
99 private static int TIMEOUT;
101 private static RosettaDF<CertificateRequest> reqDF;
102 private static RosettaDF<CertInfo> certDF;
103 private static RosettaDF<Artifacts> artifactsDF;
104 private static RosettaDF<Configuration> configDF;
105 private static RosettaDF<Perms> permDF;
106 private static ErrMessage errMsg;
107 private static Map<String,PlaceArtifact> placeArtifact;
108 private static RosettaEnv env;
110 private static boolean doExit;
111 private static AAFCon<?> aafcon;
113 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
115 Config.AAF_APPID, Config.AAF_APPPASS,
116 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
117 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
118 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
120 private static List<String> LOC_TAGS = Arrays.asList(new String[] {
121 Config.CADI_LATITUDE, Config.CADI_LONGITUDE
123 // Note: This is set by loadURLs. Use that function as singleton, not directly.
124 private static Map<String,String> aaf_urls = null;
125 private static boolean configNoPasswd = false;
128 public static void main(String[] args) {
131 for (String arg: args) {
132 if ("-noexit".equalsIgnoreCase(arg)) {
137 if (args.length>0 && "cadi".equals(args[0])) {
138 String[] newArgs = new String[args.length-1];
139 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
140 if (newArgs.length==0) {
141 System.out.println(HASHES);
142 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
143 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
144 System.out.println(HASHES);
146 CmdLine.main(newArgs);
147 } else if(args.length>0 && "connectivity".equals(args[0])) {
148 String[] newArgs = new String[args.length-1];
149 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
150 if(newArgs.length>0 && newArgs[0].indexOf('@')>=0) {
151 newArgs[0]=FQI.reverseDomain(newArgs[0])+".props";
153 TestConnectivity.main(newArgs);
157 PropAccess access=null;
159 String hasEtc = null;
160 for(String a : args) {
161 if(a.startsWith(Config.CADI_PROP_FILES)) {
162 access = new PropAccess(args);
164 } else if(a.startsWith(Config.CADI_ETCDIR)) {
165 int idx = a.indexOf('=');
166 if(idx>=0 && idx<a.length()) {
167 hasEtc = a.substring(idx+1);
169 } else if(a.equals("--nopasswd")) {
175 if(args.length>1 && args[1].contains("@")) {
176 String domain = FQI.reverseDomain(args[1]);
181 File etc = new File(hasEtc);
183 File nsprops = new File(etc,domain+".props");
184 if(nsprops.exists()) {
185 access = new PropAccess(new String[] {Config.CADI_PROP_FILES+'='+nsprops.getAbsolutePath()});
193 boolean createOutsideForLoop = false;
194 for(Entry<Object, Object> es : System.getProperties().entrySet()) {
195 if(Config.CADI_PROP_FILES.equals(es.getKey())) {
196 createOutsideForLoop = true;
200 if(createOutsideForLoop) {
201 access = new PropAccess();
205 // When using Config file, check if Cred Exists, and if not, work with Deployer.
206 if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) {
207 // not enough credentials to use Props. Use AAFSSO
212 if (args.length>1 && args[0].equals("validate") ) {
213 int idx = args[1].indexOf('=');
215 access = new PropAccess(
216 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
218 (idx<0?args[1]:args[1].substring(idx+1)));
220 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
222 public Properties process(String[] args, Properties props) {
224 if (!args[0].equals("keypairgen")) {
225 props.put(Config.AAF_APPID, args[1]);
231 access = aafsso.access();
236 if (aafsso!=null && aafsso.loginOnly()) {
237 aafsso.setLogDefault();
239 System.out.println("AAF SSO information created in ~/.aaf");
241 env = new RosettaEnv(access.getProperties());
242 Deque<String> cmds = new ArrayDeque<String>();
243 for (String p : args) {
245 if ((eq=p.indexOf('=')) < 0) {
248 access.setProperty(p.substring(0,eq), p.substring(eq+1));
252 if (cmds.size()==0) {
254 aafsso.setLogDefault();
256 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
257 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
258 System.out.println(" create <FQI> [<machine>]");
259 System.out.println(" read <FQI> [<machine>]");
260 System.out.println(" update <FQI> [<machine>]");
261 System.out.println(" delete <FQI> [<machine>]");
262 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
263 System.out.println(" place <FQI> [<machine>[,<san>]*");
264 System.out.println(" showpass <FQI> [<machine>]");
265 System.out.println(" check <FQI> [<machine>]");
266 System.out.println(" keypairgen <FQI>");
267 System.out.println(" config <FQI> [--nopasswd]");
268 System.out.println(" validate <NS>.props>");
269 System.out.println(" connectivity <NS>.props>");
270 System.out.println(" --- Additional Tool Access ---");
271 System.out.println(" ** Type with no params for Tool Help");
272 System.out.println(" ** If using with Agent, preface with \"cadi\"");
273 System.out.println(" cadi <cadi tool params, see -?>");
280 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
282 reqDF = env.newDataFactory(CertificateRequest.class);
283 artifactsDF = env.newDataFactory(Artifacts.class);
284 certDF = env.newDataFactory(CertInfo.class);
285 configDF = env.newDataFactory(Configuration.class);
286 permDF = env.newDataFactory(Perms.class);
287 errMsg = new ErrMessage(env);
289 placeArtifact = new HashMap<>();
290 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
291 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
292 placeArtifact.put(FILE, new PlaceArtifactInFiles());
293 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
294 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
296 Trans trans = env.newTrans();
298 if ((token=access.getProperty("oauth_token"))!=null) {
299 trans.setProperty("oauth_token", token);
303 // show Std out again
304 aafsso.setLogDefault();
305 aafsso.setStdErrDefault();
307 /*urls=*/loadURLs(access);
312 String cmd = cmds.removeFirst();
315 exitCode = placeCerts(trans,aafcon(access),cmds);
318 exitCode = createArtifact(trans, aafcon(access),cmds);
321 exitCode = readArtifact(trans, aafcon(access), cmds);
324 exitCode = copyArtifact(trans, aafcon(access), cmds);
327 exitCode = updateArtifact(trans, aafcon(access), cmds);
330 exitCode = deleteArtifact(trans, aafcon(access), cmds);
333 exitCode = showPass(trans, aafcon(access), cmds);
336 exitCode = keypairGen(trans, access, cmds);
339 exitCode = config(trans,access,args,cmds);
342 exitCode = validate(access);
345 exitCode = check(trans,aafcon(access),cmds);
348 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
352 StringBuilder sb = new StringBuilder();
353 trans.auditTrail(4, sb, Trans.REMOTE);
355 trans.info().log("Trans Info\n",sb);
362 } catch (Exception e) {
368 System.exit(exitCode);
372 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
374 Map<String,String> rv = new HashMap<>();
375 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
376 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
377 dot_le=dot_le==null?"":'.'+dot_le;
378 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
379 for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) {
383 case "aaf": tag = Config.AAF_URL; break;
384 case "locate":tag = Config.AAF_LOCATE_URL; break;
385 case "oauth": tag = Config.AAF_URL_OAUTH; break;
386 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
387 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
388 case "cm": tag = Config.AAF_URL_CM; break;
389 case "gui": tag = Config.AAF_URL_GUI; break;
390 case "fs": tag = Config.AAF_URL_FS; break;
391 case "hello": tag = Config.AAF_URL_HELLO; break;
393 tag = "aaf_url_" + u;
396 if((value=access.getProperty(tag,null))==null) {
397 String proto = "fs".equals(u)?"http://":"https://";
399 if("locate".equals(u)) {
400 lhost=rph.default_fqdn;
402 lhost=Config.AAF_LOCATE_URL_TAG;
404 value = rph.replacements(AGENT_LOAD_URLS,
405 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
411 value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le);
420 public static void fillMissing(PropAccess access, Map<String, String> map) {
421 for(Entry<String, String> es : map.entrySet()) {
422 if(access.getProperty(es.getKey())==null) {
423 access.setProperty(es.getKey(),es.getValue());
428 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
430 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
435 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
437 if ((value=pa.getProperty(tag))==null) {
439 value = new String(AAFSSO.cons.readPassword(prompt, def));
441 value = AAFSSO.cons.readLine(prompt,def).trim();
444 if (value.length()>0) {
445 pa.setProperty(tag,value);
446 env.setProperty(tag,value);
447 } else if (def.length==1) {
448 value=def[0].toString();
449 pa.setProperty(tag,value);
450 env.setProperty(tag,value);
457 private static String fqi(Deque<String> cmds) {
459 String alias = env.getProperty(Config.CADI_ALIAS);
461 alias = env.getProperty(Config.AAF_APPID);
463 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
465 return cmds.removeFirst();
468 private static String machine(Deque<String> cmds) throws UnknownHostException {
470 return cmds.removeFirst();
472 String mach = env.getProperty(Config.HOSTNAME);
473 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
477 private static String[] machines(Deque<String> cmds) {
480 machines = cmds.removeFirst();
482 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
484 return Split.split(',', machines);
487 private static int createArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
488 boolean success = false;
489 final String mechID = fqi(cmds);
490 final String machine = machine(cmds);
492 Artifacts artifacts = new Artifacts();
493 Artifact arti = new Artifact();
494 artifacts.getArtifact().add(arti);
495 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
496 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
497 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
499 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
500 for (String s : Split.splitTrim(',', resp)) {
501 arti.getType().add(s);
504 if (!resp.contains(SCRIPT)) {
505 arti.getType().add(SCRIPT);
508 // Note: Sponsor is set on Creation by CM
509 String configRootName = FQI.reverseDomain(arti.getMechid());
510 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
511 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
512 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
513 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
514 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
516 TimeTaken tt = transitiveInfo.start("Create Artifact", Env.REMOTE);
518 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
519 if (future.get(TIMEOUT)) {
520 transitiveInfo.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
523 transitiveInfo.error().printf("Call to AAF Certman failed, %s",
524 errMsg.toMsg(future));
529 return success ? 0 : 1;
532 private static String toNotification(String notification) {
533 if (notification==null) {
535 } else if (notification.length()>0) {
536 if (notification.indexOf(':')<0) {
537 notification = "mailto:" + notification;
545 * @param transitiveInfo
548 * @return exit cocde for shell
551 private static int readArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
552 String mechID = fqi(cmds);
553 String machine = machine(cmds);
554 boolean success = false;
556 TimeTaken tt = transitiveInfo.start("Read Artifact", Env.SUB);
558 Future<Artifacts> future = aafcon.client(CM_VER)
559 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + transitiveInfo.getProperty("oauth_token"));
561 if (future.get(TIMEOUT)) {
562 List<Artifact> artifacts = future.value.getArtifact();
563 for (Artifact a : artifacts) {
564 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
565 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
566 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
567 AAFSSO.cons.printf("CA: %s\n",a.getCa());
568 StringBuilder sb = new StringBuilder();
569 boolean first = true;
570 for (String t : a.getType()) {
571 if (first) {first=false;}
572 else{sb.append(',');}
575 AAFSSO.cons.printf("Types: %s\n",sb);
576 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
577 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
578 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
579 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
580 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
582 if (artifacts.isEmpty()) {
583 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
588 transitiveInfo.error().log(errMsg.toMsg(future));
593 return success ? 0 : 1;
598 * @param transitiveInfo
601 * @return exit code for shell
604 private static int copyArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
605 boolean success = false;
606 String mechID = fqi(cmds);
607 String machine = machine(cmds);
608 String[] newmachs = machines(cmds);
609 if (machine==null || newmachs == null) {
610 transitiveInfo.error().log("No machines listed to copy to");
612 TimeTaken tt = transitiveInfo.start("Copy Artifact", Env.REMOTE);
614 Future<Artifacts> future = aafcon.client(CM_VER)
615 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
617 if (future.get(TIMEOUT)) {
618 for (Artifact a : future.value.getArtifact()) {
619 for (String m : newmachs) {
621 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
622 if (fup.get(TIMEOUT)) {
623 transitiveInfo.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
626 transitiveInfo.error().printf("Call to AAF Certman failed, %s",
632 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
635 transitiveInfo.error().log(errMsg.toMsg(future));
641 return success ? 0 : 1;
646 * @param transitiveInfo
649 * @return exit code for shell
652 private static int updateArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
653 boolean success = false;
654 String mechID = fqi(cmds);
655 String machine = machine(cmds);
657 TimeTaken tt = transitiveInfo.start("Update Artifact", Env.REMOTE);
659 Future<Artifacts> fread = aafcon.client(CM_VER)
660 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
662 if (fread.get(TIMEOUT)) {
663 Artifacts artifacts = new Artifacts();
664 for (Artifact a : fread.value.getArtifact()) {
665 Artifact arti = new Artifact();
666 artifacts.getArtifact().add(arti);
668 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
669 arti.setMechid(a.getMechid());
670 arti.setMachine(a.getMachine());
671 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
672 StringBuilder sb = new StringBuilder();
673 boolean first = true;
674 for (String t : a.getType()) {
675 if (first) {first=false;}
676 else{sb.append(',');}
680 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
681 for (String s : Split.splitTrim(',', resp)) {
682 arti.getType().add(s);
685 if (!resp.contains(SCRIPT)) {
686 arti.getType().add(SCRIPT);
689 // Note: Sponsor is set on Creation by CM
690 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
691 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
692 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
693 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
694 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
697 if (artifacts.getArtifact().size()==0) {
698 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
700 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
701 if (fup.get(TIMEOUT)) {
702 transitiveInfo.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
705 transitiveInfo.error().printf("Call to AAF Certman failed, %s",
710 transitiveInfo.error().printf("Call to AAF Certman failed, %s %s, %s",
711 errMsg.toMsg(fread),mechID,machine);
716 return success ? 0 : 1;
721 * @param transitiveInfo
724 * @return exit code for shell
727 private static int deleteArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
728 boolean success = false;
729 String mechid = fqi(cmds);
730 String machine = machine(cmds);
732 TimeTaken tt = transitiveInfo.start("Delete Artifact", Env.REMOTE);
734 Future<Void> future = aafcon.client(CM_VER)
735 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
737 if (future.get(TIMEOUT)) {
738 transitiveInfo.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
741 transitiveInfo.error().printf("Call to AAF Certman failed, %s %s, %s",
742 errMsg.toMsg(future),mechid,machine);
747 return success ? 0 : 1;
753 * @param transitiveInfo
756 * @return exit code for shell
759 private static int placeCerts(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
760 boolean success = false;
761 String mechID = fqi(cmds);
762 String machine = machine(cmds);
763 String[] fqdns = Split.split(':', machine);
765 if (fqdns.length>1) {
771 fqdns = machines(cmds);
773 // make sure machine is also in SANS
774 fqdns = new String[] {machine};
778 TimeTaken tt = transitiveInfo.start("Place Artifact", Env.REMOTE);
780 Future<Artifacts> acf = aafcon.client(CM_VER)
781 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
782 if (acf.get(TIMEOUT)) {
783 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
784 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
786 for (Artifact a : acf.value.getArtifact()) {
787 String osID = System.getProperty("user.name");
788 if (a.getOsUser().equals(osID)) {
789 CertificateRequest cr = new CertificateRequest();
790 cr.setMechid(a.getMechid());
791 cr.setSponsor(a.getSponsor());
792 cr.getFqdns().add(machine);
793 for (int i=0;i<fqdns.length;++i) {
794 if(!machine.equals(fqdns[i])) {
795 cr.getFqdns().add(fqdns[i]);
798 Future<String> f = aafcon.client(CM_VER)
799 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
800 if (f.get(TIMEOUT)) {
801 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
802 for (String type : a.getType()) {
803 PlaceArtifact pa = placeArtifact.get(type);
805 pa.place(transitiveInfo, capi, a,machine);
809 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
811 transitiveInfo.error().log(errMsg.toMsg(f));
814 transitiveInfo.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
818 PropHolder.writeAll();
820 transitiveInfo.error().log(errMsg.toMsg(acf));
825 return success ? 0 : 1;
831 * @param transitiveInfo
834 * @return exit code for shell
837 private static int showPass(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
838 boolean success = false;
839 String mechID = fqi(cmds);
840 String machine = machine(cmds);
842 TimeTaken tt = transitiveInfo.start("Show Password", Env.REMOTE);
844 Future<Artifacts> acf = aafcon.client(CM_VER)
845 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
846 if (acf.get(TIMEOUT)) {
847 // Have to wait for JDK 1.7 source...
848 //switch(artifact.getType()) {
849 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
850 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
852 String id = aafcon.defID();
854 for (Artifact a : acf.value.getArtifact()) {
855 allowed = id!=null && (id.equals(a.getSponsor()) ||
856 (id.equals(a.getMechid())
857 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
859 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
860 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
861 if (pf.get(TIMEOUT)) {
864 transitiveInfo.error().log(errMsg.toMsg(pf));
868 File dir = new File(a.getDir());
869 Properties props = new Properties();
870 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
873 File chalFile = new File(dir,a.getNs()+".chal");
874 if(chalFile.exists()) {
876 fis = new FileInputStream(chalFile);
883 File f = new File(dir,a.getNs()+".keyfile");
885 Symm symm = ArtifactDir.getSymm(f);
887 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
888 Entry<Object,Object> en = iter.next();
889 if (en.getValue().toString().startsWith("enc:")) {
890 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
895 transitiveInfo.error().printf("%s.keyfile must exist to read passwords for %s on %s",
896 f.getAbsolutePath(),a.getMechid(), a.getMachine());
902 transitiveInfo.error().log(errMsg.toMsg(acf));
907 return success ? 0 : 1;
914 * @param transitiveInfo
917 * @return exit code for shell
918 * @throws IOException
920 private static int keypairGen(final Trans transitiveInfo, final PropAccess access, final Deque<String> cmds) throws IOException {
921 final String fqi = fqi(cmds);
922 final String ns = FQI.reverseDomain(fqi);
923 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
924 File f = new File(dir,ns+".key");
927 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
928 if (!"Y".equalsIgnoreCase(line)) {
929 System.out.println("Canceling...");
934 KeyPair kp = Factory.generateKeyPair(transitiveInfo);
935 ArtifactDir.write(f, Chmod.to400, Factory.toString(transitiveInfo, kp.getPrivate()));
936 System.out.printf("Wrote %s\n", f.getCanonicalFile());
938 f=new File(dir,ns+".pubkey");
939 ArtifactDir.write(f, Chmod.to644, Factory.toString(transitiveInfo, kp.getPublic()));
940 System.out.printf("Wrote %s\n", f.getCanonicalFile());
946 * @param transitiveInfo
950 * @return exit code for shell
953 private static int config(Trans transitiveInfo, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
954 boolean success = true;
955 TimeTaken tt = transitiveInfo.start("Get Configuration", Env.REMOTE);
957 final String fqi = fqi(cmds);
958 Artifact arti = new Artifact();
959 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir")));
960 arti.setNs(FQI.reverseDomain(fqi));
961 PropHolder loc = PropHolder.get(arti, "location.props");
962 PropHolder cred = PropHolder.get(arti,"cred.props");
963 PropHolder app= PropHolder.get(arti,"props");
964 for(String c : args) {
965 int idx = c.indexOf('=');
967 app.add(c.substring(0,idx), c.substring(idx+1));
970 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
972 for (String tag : LOC_TAGS) {
973 loc.add(tag, getProperty(propAccess, transitiveInfo, false, tag, "%s: ",tag));
976 String keyfile = cred.getKeyPath();
978 File fkeyfile = new File(keyfile);
979 if(!fkeyfile.exists()) {
980 ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen());
983 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
984 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
985 if(fqi!=null && fqi.equals(ssoAppID)) {
986 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
987 // only Ask for Password when starting scratch
988 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
989 if(!configNoPasswd) {
990 char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi);
992 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
997 // load all properties that are already setup.
998 Map<String, String> aaf_urls = loadURLs(propAccess);
999 for(Entry<String, String> es : aaf_urls.entrySet()) {
1000 app.add(es.getKey(), es.getValue());
1003 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
1004 app.add(Config.AAF_ENV,propAccess, "DEV");
1005 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
1007 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
1010 app.add(Config.AAF_DEPLOYED_VERSION, release);
1012 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
1013 String key = aaf_loc_prop.getKey().toString();
1014 if(key.startsWith("aaf_locator")) {
1015 app.add(key, aaf_loc_prop.getValue().toString());
1019 app.add(Config.AAF_APPID, fqi);
1021 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
1022 System.out.println("Passed in Truststore is " + cts);
1024 File origTruststore = new File(cts);
1025 File newTruststore = new File(app.getDir(),origTruststore.getName());
1026 if(!newTruststore.exists()) {
1027 if (!origTruststore.exists()) {
1028 // Try same directory as cadi_prop_files
1029 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
1031 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
1032 File fcpf = new File(f);
1033 if (fcpf.exists()) {
1034 int lastSep = cts.lastIndexOf(File.pathSeparator);
1035 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
1036 if (origTruststore.exists()) {
1041 if (!origTruststore.exists()) {
1042 throw new CadiException(cts + " does not exist");
1047 if (!newTruststore.exists() && origTruststore.exists()) {
1048 Files.copy(origTruststore.toPath(), newTruststore.toPath());
1052 System.out.println("New Truststore is " + newTruststore);
1053 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
1054 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
1056 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
1058 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
1059 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
1060 String f = propFiles[pfi];
1061 System.out.format("Reading %s\n",f);
1062 FileInputStream fis = new FileInputStream(f);
1064 Properties props = new Properties();
1066 for (Entry<Object, Object> prop : props.entrySet()) {
1067 boolean lower = true;
1068 String key = prop.getKey().toString();
1069 if(LOC_TAGS.contains(key)) {
1072 for(int i=0;lower && i<key.length();++i) {
1073 if(Character.isUpperCase(key.charAt(i))) {
1078 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
1079 if(key.endsWith("_password")) {
1080 ph.addEnc(key, prop.getValue().toString());
1082 ph.add(key, prop.getValue().toString());
1091 aafcon = aafcon(propAccess);
1092 if (aafcon!=null) { // get Properties from Remote AAF
1093 for (Props props : aafProps(transitiveInfo,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
1094 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
1095 if(props.getTag().endsWith("_password")) {
1096 ph.addEnc(props.getTag(), props.getValue());
1098 ph.add(props.getTag(), props.getValue());
1106 PropHolder.writeAll();
1110 return success ? 0 : 1;
1113 public static List<Props> aafProps(Trans transitiveInfo, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, LocatorException {
1114 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
1115 .read("/configure/"+fqi+"/aaf", configDF);
1116 if (acf.get(TIMEOUT)) {
1117 return acf.value.getProps();
1118 } else if (acf.code()==401){
1119 transitiveInfo.error().log("Bad Password sent to AAF");
1120 } else if (acf.code()==404){
1121 transitiveInfo.error().log("This version of AAF does not support remote Properties");
1123 transitiveInfo.error().log(errMsg.toMsg(acf));
1125 return new ArrayList<>();
1131 * @return exit code for shell
1132 * @throws LocatorException
1133 * @throws CadiException
1134 * @throws APIException
1136 private static int validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
1137 System.out.println("Validating Configuration...");
1138 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
1139 return aafcon.best(new Retryable<Integer>() {
1141 public Integer code(Rcli<?> client) throws CadiException, ConnectException, APIException {
1142 boolean success = false;
1143 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
1144 if (fc.get(aafcon.timeout)) {
1145 System.out.print("Success connecting to ");
1146 System.out.println(client.getURI());
1147 System.out.print(" Permissions for ");
1148 System.out.println(aafcon.defID());
1149 for (Perm p : fc.value.getPerm()) {
1150 System.out.print('\t');
1151 System.out.print(p.getType());
1152 System.out.print('|');
1153 System.out.print(p.getInstance());
1154 System.out.print('|');
1155 System.out.println(p.getAction());
1159 System.err.println("Error: " + fc.code() + ' ' + fc.body());
1161 return success ? 0 : 1;
1167 * Check returns Error Codes, so that Scripts can know what to do
1169 * <ul>0 - Check Complete, nothing to do</ul>
1170 * <ul>1 - General Error</ul>
1171 * <ul>2 - Error for specific Artifact - read check.msg</ul>
1172 * <ul>10 - Certificate Updated - check.msg is email content</ul>
1174 * @param transitiveInfo
1180 private static int check(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1182 String mechID = fqi(cmds);
1183 String machine = machine(cmds);
1185 TimeTaken tt = transitiveInfo.start("Check Certificate", Env.REMOTE);
1188 Future<Artifacts> acf = aafcon.client(CM_VER)
1189 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1190 if (acf.get(TIMEOUT)) {
1191 // Have to wait for JDK 1.7 source...
1192 //switch(artifact.getType()) {
1193 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1194 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1196 String id = aafcon.defID();
1197 GregorianCalendar now = new GregorianCalendar();
1198 for (Artifact a : acf.value.getArtifact()) {
1199 if (id.equals(a.getMechid())) {
1200 File dir = new File(a.getDir());
1201 Properties props = new Properties();
1202 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1212 if ((prop=transitiveInfo.getProperty(Config.CADI_KEYFILE))==null ||
1213 !(f=new File(prop)).exists()) {
1214 transitiveInfo.error().printf("Keyfile must exist to check Certificates for %s on %s",
1215 a.getMechid(), a.getMachine());
1217 String ksf = transitiveInfo.getProperty(Config.CADI_KEYSTORE);
1218 String ksps = transitiveInfo.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1219 if (ksf==null || ksps == null) {
1220 transitiveInfo.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1221 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1223 Symm symm = ArtifactDir.getSymm(f);
1225 KeyStore ks = KeyStore.getInstance("JKS");
1227 fis = new FileInputStream(ksf);
1229 ks.load(fis,symm.depass(ksps).toCharArray());
1233 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1237 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1238 a.getMechid(), a.getMachine(), ksf);
1239 transitiveInfo.error().log(msg);
1242 GregorianCalendar renew = new GregorianCalendar();
1243 renew.setTime(cert.getNotAfter());
1244 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1245 if (renew.after(now)) {
1246 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",
1247 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1248 transitiveInfo.info().log(msg);
1251 transitiveInfo.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1252 a.getMechid(), a.getMachine(),cert.getNotAfter());
1253 cmds.offerLast(mechID);
1254 cmds.offerLast(machine);
1255 if (placeCerts(transitiveInfo,aafcon,cmds) == 0) {
1256 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1257 a.getMechid(), a.getMachine());
1258 exitCode = 10; // Refreshed
1260 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1261 a.getMechid(), a.getMachine());
1262 exitCode = 1; // Error Renewing
1267 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1269 fos.write(msg.getBytes());
1281 transitiveInfo.error().log(errMsg.toMsg(acf));