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 for(Entry<Object, Object> es : System.getProperties().entrySet()) {
194 if(Config.CADI_PROP_FILES.equals(es.getKey())) {
195 access = new PropAccess();
200 // When using Config file, check if Cred Exists, and if not, work with Deployer.
201 if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) {
202 // not enough credentials to use Props. Use AAFSSO
207 if (args.length>1 && args[0].equals("validate") ) {
208 int idx = args[1].indexOf('=');
210 access = new PropAccess(
211 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
213 (idx<0?args[1]:args[1].substring(idx+1)));
215 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
217 public Properties process(String[] args, Properties props) {
219 if (!args[0].equals("keypairgen")) {
220 props.put(Config.AAF_APPID, args[1]);
226 access = aafsso.access();
231 if (aafsso!=null && aafsso.loginOnly()) {
232 aafsso.setLogDefault();
234 System.out.println("AAF SSO information created in ~/.aaf");
236 env = new RosettaEnv(access.getProperties());
237 Deque<String> cmds = new ArrayDeque<String>();
238 for (String p : args) {
240 if ((eq=p.indexOf('=')) < 0) {
243 access.setProperty(p.substring(0,eq), p.substring(eq+1));
247 if (cmds.size()==0) {
249 aafsso.setLogDefault();
251 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
252 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
253 System.out.println(" create <FQI> [<machine>]");
254 System.out.println(" read <FQI> [<machine>]");
255 System.out.println(" update <FQI> [<machine>]");
256 System.out.println(" delete <FQI> [<machine>]");
257 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
258 System.out.println(" place <FQI> [<machine>[,<san>]*");
259 System.out.println(" showpass <FQI> [<machine>]");
260 System.out.println(" check <FQI> [<machine>]");
261 System.out.println(" keypairgen <FQI>");
262 System.out.println(" config <FQI> [--nopasswd]");
263 System.out.println(" validate <NS>.props>");
264 System.out.println(" connectivity <NS>.props>");
265 System.out.println(" --- Additional Tool Access ---");
266 System.out.println(" ** Type with no params for Tool Help");
267 System.out.println(" ** If using with Agent, preface with \"cadi\"");
268 System.out.println(" cadi <cadi tool params, see -?>");
275 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
277 reqDF = env.newDataFactory(CertificateRequest.class);
278 artifactsDF = env.newDataFactory(Artifacts.class);
279 certDF = env.newDataFactory(CertInfo.class);
280 configDF = env.newDataFactory(Configuration.class);
281 permDF = env.newDataFactory(Perms.class);
282 errMsg = new ErrMessage(env);
284 placeArtifact = new HashMap<>();
285 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
286 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
287 placeArtifact.put(FILE, new PlaceArtifactInFiles());
288 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
289 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
291 Trans trans = env.newTrans();
293 if ((token=access.getProperty("oauth_token"))!=null) {
294 trans.setProperty("oauth_token", token);
298 // show Std out again
299 aafsso.setLogDefault();
300 aafsso.setStdErrDefault();
302 /*urls=*/loadURLs(access);
307 String cmd = cmds.removeFirst();
310 exitCode = placeCerts(trans,aafcon(access),cmds);
313 exitCode = createArtifact(trans, aafcon(access),cmds);
316 exitCode = readArtifact(trans, aafcon(access), cmds);
319 exitCode = copyArtifact(trans, aafcon(access), cmds);
322 exitCode = updateArtifact(trans, aafcon(access), cmds);
325 exitCode = deleteArtifact(trans, aafcon(access), cmds);
328 exitCode = showPass(trans, aafcon(access), cmds);
331 exitCode = keypairGen(trans, access, cmds);
334 exitCode = config(trans,access,args,cmds);
337 exitCode = validate(access);
340 exitCode = check(trans,aafcon(access),cmds);
343 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
347 StringBuilder sb = new StringBuilder();
348 trans.auditTrail(4, sb, Trans.REMOTE);
350 trans.info().log("Trans Info\n",sb);
357 } catch (Exception e) {
363 System.exit(exitCode);
367 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
369 Map<String,String> rv = new HashMap<>();
370 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
371 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
372 dot_le=dot_le==null?"":'.'+dot_le;
373 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
374 for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) {
378 case "aaf": tag = Config.AAF_URL; break;
379 case "locate":tag = Config.AAF_LOCATE_URL; break;
380 case "oauth": tag = Config.AAF_URL_OAUTH; break;
381 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
382 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
383 case "cm": tag = Config.AAF_URL_CM; break;
384 case "gui": tag = Config.AAF_URL_GUI; break;
385 case "fs": tag = Config.AAF_URL_FS; break;
386 case "hello": tag = Config.AAF_URL_HELLO; break;
388 tag = "aaf_url_" + u;
391 if((value=access.getProperty(tag,null))==null) {
392 String proto = "fs".equals(u)?"http://":"https://";
394 if("locate".equals(u)) {
395 lhost=rph.default_fqdn;
397 lhost=Config.AAF_LOCATE_URL_TAG;
399 value = rph.replacements(AGENT_LOAD_URLS,
400 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
406 value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le);
415 public static void fillMissing(PropAccess access, Map<String, String> map) {
416 for(Entry<String, String> es : map.entrySet()) {
417 if(access.getProperty(es.getKey())==null) {
418 access.setProperty(es.getKey(),es.getValue());
423 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
425 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
430 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
432 if ((value=pa.getProperty(tag))==null) {
434 value = new String(AAFSSO.cons.readPassword(prompt, def));
436 value = AAFSSO.cons.readLine(prompt,def).trim();
439 if (value.length()>0) {
440 pa.setProperty(tag,value);
441 env.setProperty(tag,value);
442 } else if (def.length==1) {
443 value=def[0].toString();
444 pa.setProperty(tag,value);
445 env.setProperty(tag,value);
452 private static String fqi(Deque<String> cmds) {
454 String alias = env.getProperty(Config.CADI_ALIAS);
456 alias = env.getProperty(Config.AAF_APPID);
458 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
460 return cmds.removeFirst();
463 private static String machine(Deque<String> cmds) throws UnknownHostException {
465 return cmds.removeFirst();
467 String mach = env.getProperty(Config.HOSTNAME);
468 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
472 private static String[] machines(Deque<String> cmds) {
475 machines = cmds.removeFirst();
477 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
479 return Split.split(',', machines);
482 private static int createArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
483 boolean success = false;
484 final String mechID = fqi(cmds);
485 final String machine = machine(cmds);
487 Artifacts artifacts = new Artifacts();
488 Artifact arti = new Artifact();
489 artifacts.getArtifact().add(arti);
490 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
491 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
492 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
494 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
495 for (String s : Split.splitTrim(',', resp)) {
496 arti.getType().add(s);
499 if (!resp.contains(SCRIPT)) {
500 arti.getType().add(SCRIPT);
503 // Note: Sponsor is set on Creation by CM
504 String configRootName = FQI.reverseDomain(arti.getMechid());
505 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
506 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
507 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
508 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
509 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
511 TimeTaken tt = transitiveInfo.start("Create Artifact", Env.REMOTE);
513 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
514 if (future.get(TIMEOUT)) {
515 transitiveInfo.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
518 transitiveInfo.error().printf("Call to AAF Certman failed, %s",
519 errMsg.toMsg(future));
524 return success ? 0 : 1;
527 private static String toNotification(String notification) {
528 if (notification==null) {
530 } else if (notification.length()>0) {
531 if (notification.indexOf(':')<0) {
532 notification = "mailto:" + notification;
540 * @param transitiveInfo
543 * @return exit cocde for shell
546 private static int readArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
547 String mechID = fqi(cmds);
548 String machine = machine(cmds);
549 boolean success = false;
551 TimeTaken tt = transitiveInfo.start("Read Artifact", Env.SUB);
553 Future<Artifacts> future = aafcon.client(CM_VER)
554 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + transitiveInfo.getProperty("oauth_token"));
556 if (future.get(TIMEOUT)) {
557 List<Artifact> artifacts = future.value.getArtifact();
558 for (Artifact a : artifacts) {
559 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
560 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
561 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
562 AAFSSO.cons.printf("CA: %s\n",a.getCa());
563 StringBuilder sb = new StringBuilder();
564 boolean first = true;
565 for (String t : a.getType()) {
566 if (first) {first=false;}
567 else{sb.append(',');}
570 AAFSSO.cons.printf("Types: %s\n",sb);
571 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
572 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
573 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
574 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
575 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
577 if (artifacts.isEmpty()) {
578 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
583 transitiveInfo.error().log(errMsg.toMsg(future));
588 return success ? 0 : 1;
593 * @param transitiveInfo
596 * @return exit code for shell
599 private static int copyArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
600 boolean success = false;
601 String mechID = fqi(cmds);
602 String machine = machine(cmds);
603 String[] newmachs = machines(cmds);
604 if (machine==null || newmachs == null) {
605 transitiveInfo.error().log("No machines listed to copy to");
607 TimeTaken tt = transitiveInfo.start("Copy Artifact", Env.REMOTE);
609 Future<Artifacts> future = aafcon.client(CM_VER)
610 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
612 if (future.get(TIMEOUT)) {
613 for (Artifact a : future.value.getArtifact()) {
614 for (String m : newmachs) {
616 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
617 if (fup.get(TIMEOUT)) {
618 transitiveInfo.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
621 transitiveInfo.error().printf("Call to AAF Certman failed, %s",
627 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
630 transitiveInfo.error().log(errMsg.toMsg(future));
636 return success ? 0 : 1;
641 * @param transitiveInfo
644 * @return exit code for shell
647 private static int updateArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
648 boolean success = false;
649 String mechID = fqi(cmds);
650 String machine = machine(cmds);
652 TimeTaken tt = transitiveInfo.start("Update Artifact", Env.REMOTE);
654 Future<Artifacts> fread = aafcon.client(CM_VER)
655 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
657 if (fread.get(TIMEOUT)) {
658 Artifacts artifacts = new Artifacts();
659 for (Artifact a : fread.value.getArtifact()) {
660 Artifact arti = new Artifact();
661 artifacts.getArtifact().add(arti);
663 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
664 arti.setMechid(a.getMechid());
665 arti.setMachine(a.getMachine());
666 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
667 StringBuilder sb = new StringBuilder();
668 boolean first = true;
669 for (String t : a.getType()) {
670 if (first) {first=false;}
671 else{sb.append(',');}
675 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
676 for (String s : Split.splitTrim(',', resp)) {
677 arti.getType().add(s);
680 if (!resp.contains(SCRIPT)) {
681 arti.getType().add(SCRIPT);
684 // Note: Sponsor is set on Creation by CM
685 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
686 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
687 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
688 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
689 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
692 if (artifacts.getArtifact().size()==0) {
693 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
695 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
696 if (fup.get(TIMEOUT)) {
697 transitiveInfo.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
700 transitiveInfo.error().printf("Call to AAF Certman failed, %s",
705 transitiveInfo.error().printf("Call to AAF Certman failed, %s %s, %s",
706 errMsg.toMsg(fread),mechID,machine);
711 return success ? 0 : 1;
716 * @param transitiveInfo
719 * @return exit code for shell
722 private static int deleteArtifact(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
723 boolean success = false;
724 String mechid = fqi(cmds);
725 String machine = machine(cmds);
727 TimeTaken tt = transitiveInfo.start("Delete Artifact", Env.REMOTE);
729 Future<Void> future = aafcon.client(CM_VER)
730 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
732 if (future.get(TIMEOUT)) {
733 transitiveInfo.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
736 transitiveInfo.error().printf("Call to AAF Certman failed, %s %s, %s",
737 errMsg.toMsg(future),mechid,machine);
742 return success ? 0 : 1;
748 * @param transitiveInfo
751 * @return exit code for shell
754 private static int placeCerts(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
755 boolean success = false;
756 String mechID = fqi(cmds);
757 String machine = machine(cmds);
758 String[] fqdns = Split.split(':', machine);
760 if (fqdns.length>1) {
765 fqdns = machines(cmds);
768 TimeTaken tt = transitiveInfo.start("Place Artifact", Env.REMOTE);
770 Future<Artifacts> acf = aafcon.client(CM_VER)
771 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
772 if (acf.get(TIMEOUT)) {
773 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
774 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
776 for (Artifact a : acf.value.getArtifact()) {
777 String osID = System.getProperty("user.name");
778 if (a.getOsUser().equals(osID)) {
779 CertificateRequest cr = new CertificateRequest();
780 cr.setMechid(a.getMechid());
781 cr.setSponsor(a.getSponsor());
782 cr.getFqdns().add(machine);
783 for (int i=0;i<fqdns.length;++i) {
784 if(!machine.equals(fqdns[i])) {
785 cr.getFqdns().add(fqdns[i]);
788 Future<String> f = aafcon.client(CM_VER)
789 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
790 if (f.get(TIMEOUT)) {
791 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
792 for (String type : a.getType()) {
793 PlaceArtifact pa = placeArtifact.get(type);
795 pa.place(transitiveInfo, capi, a,machine);
799 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
801 transitiveInfo.error().log(errMsg.toMsg(f));
804 transitiveInfo.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
808 PropHolder.writeAll();
810 transitiveInfo.error().log(errMsg.toMsg(acf));
815 return success ? 0 : 1;
821 * @param transitiveInfo
824 * @return exit code for shell
827 private static int showPass(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
828 boolean success = false;
829 String mechID = fqi(cmds);
830 String machine = machine(cmds);
832 TimeTaken tt = transitiveInfo.start("Show Password", Env.REMOTE);
834 Future<Artifacts> acf = aafcon.client(CM_VER)
835 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
836 if (acf.get(TIMEOUT)) {
837 // Have to wait for JDK 1.7 source...
838 //switch(artifact.getType()) {
839 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
840 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
842 String id = aafcon.defID();
844 for (Artifact a : acf.value.getArtifact()) {
845 allowed = id!=null && (id.equals(a.getSponsor()) ||
846 (id.equals(a.getMechid())
847 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
849 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
850 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
851 if (pf.get(TIMEOUT)) {
854 transitiveInfo.error().log(errMsg.toMsg(pf));
858 File dir = new File(a.getDir());
859 Properties props = new Properties();
860 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
863 File chalFile = new File(dir,a.getNs()+".chal");
864 if(chalFile.exists()) {
866 fis = new FileInputStream(chalFile);
873 File f = new File(dir,a.getNs()+".keyfile");
875 Symm symm = ArtifactDir.getSymm(f);
877 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
878 Entry<Object,Object> en = iter.next();
879 if (en.getValue().toString().startsWith("enc:")) {
880 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
885 transitiveInfo.error().printf("%s.keyfile must exist to read passwords for %s on %s",
886 f.getAbsolutePath(),a.getMechid(), a.getMachine());
892 transitiveInfo.error().log(errMsg.toMsg(acf));
897 return success ? 0 : 1;
904 * @param transitiveInfo
907 * @return exit code for shell
908 * @throws IOException
910 private static int keypairGen(final Trans transitiveInfo, final PropAccess access, final Deque<String> cmds) throws IOException {
911 final String fqi = fqi(cmds);
912 final String ns = FQI.reverseDomain(fqi);
913 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
914 File f = new File(dir,ns+".key");
917 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
918 if (!"Y".equalsIgnoreCase(line)) {
919 System.out.println("Canceling...");
924 KeyPair kp = Factory.generateKeyPair(transitiveInfo);
925 ArtifactDir.write(f, Chmod.to400, Factory.toString(transitiveInfo, kp.getPrivate()));
926 System.out.printf("Wrote %s\n", f.getCanonicalFile());
928 f=new File(dir,ns+".pubkey");
929 ArtifactDir.write(f, Chmod.to644, Factory.toString(transitiveInfo, kp.getPublic()));
930 System.out.printf("Wrote %s\n", f.getCanonicalFile());
936 * @param transitiveInfo
940 * @return exit code for shell
943 private static int config(Trans transitiveInfo, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
944 boolean success = true;
945 TimeTaken tt = transitiveInfo.start("Get Configuration", Env.REMOTE);
947 final String fqi = fqi(cmds);
948 Artifact arti = new Artifact();
949 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir")));
950 arti.setNs(FQI.reverseDomain(fqi));
951 PropHolder loc = PropHolder.get(arti, "location.props");
952 PropHolder cred = PropHolder.get(arti,"cred.props");
953 PropHolder app= PropHolder.get(arti,"props");
954 for(String c : args) {
955 int idx = c.indexOf('=');
957 app.add(c.substring(0,idx), c.substring(idx+1));
960 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
962 for (String tag : LOC_TAGS) {
963 loc.add(tag, getProperty(propAccess, transitiveInfo, false, tag, "%s: ",tag));
966 String keyfile = cred.getKeyPath();
968 File fkeyfile = new File(keyfile);
969 if(!fkeyfile.exists()) {
970 ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen());
973 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
974 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
975 if(fqi!=null && fqi.equals(ssoAppID)) {
976 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
977 // only Ask for Password when starting scratch
978 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
979 if(!configNoPasswd) {
980 char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi);
982 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
987 // load all properties that are already setup.
988 Map<String, String> aaf_urls = loadURLs(propAccess);
989 for(Entry<String, String> es : aaf_urls.entrySet()) {
990 app.add(es.getKey(), es.getValue());
993 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
994 app.add(Config.AAF_ENV,propAccess, "DEV");
995 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
997 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
1000 app.add(Config.AAF_DEPLOYED_VERSION, release);
1002 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
1003 String key = aaf_loc_prop.getKey().toString();
1004 if(key.startsWith("aaf_locator")) {
1005 app.add(key, aaf_loc_prop.getValue().toString());
1009 app.add(Config.AAF_APPID, fqi);
1011 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
1012 System.out.println("Passed in Truststore is " + cts);
1014 File origTruststore = new File(cts);
1015 File newTruststore = new File(app.getDir(),origTruststore.getName());
1016 if(!newTruststore.exists()) {
1017 if (!origTruststore.exists()) {
1018 // Try same directory as cadi_prop_files
1019 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
1021 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
1022 File fcpf = new File(f);
1023 if (fcpf.exists()) {
1024 int lastSep = cts.lastIndexOf(File.pathSeparator);
1025 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
1026 if (origTruststore.exists()) {
1031 if (!origTruststore.exists()) {
1032 throw new CadiException(cts + " does not exist");
1037 if (!newTruststore.exists() && origTruststore.exists()) {
1038 Files.copy(origTruststore.toPath(), newTruststore.toPath());
1042 System.out.println("New Truststore is " + newTruststore);
1043 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
1044 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
1046 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
1048 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
1049 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
1050 String f = propFiles[pfi];
1051 System.out.format("Reading %s\n",f);
1052 FileInputStream fis = new FileInputStream(f);
1054 Properties props = new Properties();
1056 for (Entry<Object, Object> prop : props.entrySet()) {
1057 boolean lower = true;
1058 String key = prop.getKey().toString();
1059 if(LOC_TAGS.contains(key)) {
1062 for(int i=0;lower && i<key.length();++i) {
1063 if(Character.isUpperCase(key.charAt(i))) {
1068 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
1069 if(key.endsWith("_password")) {
1070 ph.addEnc(key, prop.getValue().toString());
1072 ph.add(key, prop.getValue().toString());
1081 aafcon = aafcon(propAccess);
1082 if (aafcon!=null) { // get Properties from Remote AAF
1083 for (Props props : aafProps(transitiveInfo,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
1084 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
1085 if(props.getTag().endsWith("_password")) {
1086 ph.addEnc(props.getTag(), props.getValue());
1088 ph.add(props.getTag(), props.getValue());
1096 PropHolder.writeAll();
1100 return success ? 0 : 1;
1103 public static List<Props> aafProps(Trans transitiveInfo, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, LocatorException {
1104 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
1105 .read("/configure/"+fqi+"/aaf", configDF);
1106 if (acf.get(TIMEOUT)) {
1107 return acf.value.getProps();
1108 } else if (acf.code()==401){
1109 transitiveInfo.error().log("Bad Password sent to AAF");
1110 } else if (acf.code()==404){
1111 transitiveInfo.error().log("This version of AAF does not support remote Properties");
1113 transitiveInfo.error().log(errMsg.toMsg(acf));
1115 return new ArrayList<>();
1121 * @return exit code for shell
1122 * @throws LocatorException
1123 * @throws CadiException
1124 * @throws APIException
1126 private static int validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
1127 System.out.println("Validating Configuration...");
1128 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
1129 return aafcon.best(new Retryable<Integer>() {
1131 public Integer code(Rcli<?> client) throws CadiException, ConnectException, APIException {
1132 boolean success = false;
1133 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
1134 if (fc.get(aafcon.timeout)) {
1135 System.out.print("Success connecting to ");
1136 System.out.println(client.getURI());
1137 System.out.print(" Permissions for ");
1138 System.out.println(aafcon.defID());
1139 for (Perm p : fc.value.getPerm()) {
1140 System.out.print('\t');
1141 System.out.print(p.getType());
1142 System.out.print('|');
1143 System.out.print(p.getInstance());
1144 System.out.print('|');
1145 System.out.println(p.getAction());
1149 System.err.println("Error: " + fc.code() + ' ' + fc.body());
1151 return success ? 0 : 1;
1157 * Check returns Error Codes, so that Scripts can know what to do
1159 * <ul>0 - Check Complete, nothing to do</ul>
1160 * <ul>1 - General Error</ul>
1161 * <ul>2 - Error for specific Artifact - read check.msg</ul>
1162 * <ul>10 - Certificate Updated - check.msg is email content</ul>
1164 * @param transitiveInfo
1170 private static int check(Trans transitiveInfo, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1172 String mechID = fqi(cmds);
1173 String machine = machine(cmds);
1175 TimeTaken tt = transitiveInfo.start("Check Certificate", Env.REMOTE);
1178 Future<Artifacts> acf = aafcon.client(CM_VER)
1179 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1180 if (acf.get(TIMEOUT)) {
1181 // Have to wait for JDK 1.7 source...
1182 //switch(artifact.getType()) {
1183 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1184 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1186 String id = aafcon.defID();
1187 GregorianCalendar now = new GregorianCalendar();
1188 for (Artifact a : acf.value.getArtifact()) {
1189 if (id.equals(a.getMechid())) {
1190 File dir = new File(a.getDir());
1191 Properties props = new Properties();
1192 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1202 if ((prop=transitiveInfo.getProperty(Config.CADI_KEYFILE))==null ||
1203 !(f=new File(prop)).exists()) {
1204 transitiveInfo.error().printf("Keyfile must exist to check Certificates for %s on %s",
1205 a.getMechid(), a.getMachine());
1207 String ksf = transitiveInfo.getProperty(Config.CADI_KEYSTORE);
1208 String ksps = transitiveInfo.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1209 if (ksf==null || ksps == null) {
1210 transitiveInfo.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1211 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1213 Symm symm = ArtifactDir.getSymm(f);
1215 KeyStore ks = KeyStore.getInstance("JKS");
1217 fis = new FileInputStream(ksf);
1219 ks.load(fis,symm.depass(ksps).toCharArray());
1223 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1227 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1228 a.getMechid(), a.getMachine(), ksf);
1229 transitiveInfo.error().log(msg);
1232 GregorianCalendar renew = new GregorianCalendar();
1233 renew.setTime(cert.getNotAfter());
1234 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1235 if (renew.after(now)) {
1236 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",
1237 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1238 transitiveInfo.info().log(msg);
1241 transitiveInfo.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1242 a.getMechid(), a.getMachine(),cert.getNotAfter());
1243 cmds.offerLast(mechID);
1244 cmds.offerLast(machine);
1245 if (placeCerts(transitiveInfo,aafcon,cmds) == 0) {
1246 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1247 a.getMechid(), a.getMachine());
1248 exitCode = 10; // Refreshed
1250 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1251 a.getMechid(), a.getMachine());
1252 exitCode = 1; // Error Renewing
1257 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1259 fos.write(msg.getBytes());
1271 transitiveInfo.error().log(errMsg.toMsg(acf));