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.URISyntaxException;
32 import java.net.UnknownHostException;
33 import java.nio.file.Files;
34 import java.security.KeyPair;
35 import java.security.KeyStore;
36 import java.security.cert.X509Certificate;
37 import java.util.ArrayDeque;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Deque;
41 import java.util.GregorianCalendar;
42 import java.util.HashMap;
43 import java.util.Iterator;
44 import java.util.List;
46 import java.util.Map.Entry;
47 import java.util.Properties;
49 import org.onap.aaf.cadi.Access;
50 import org.onap.aaf.cadi.CadiException;
51 import org.onap.aaf.cadi.CmdLine;
52 import org.onap.aaf.cadi.LocatorException;
53 import org.onap.aaf.cadi.PropAccess;
54 import org.onap.aaf.cadi.Symm;
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;
127 public static void main(String[] args) {
130 if (args.length>0 && "cadi".equals(args[0])) {
131 String[] newArgs = new String[args.length-1];
132 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
133 if (newArgs.length==0) {
134 System.out.println(HASHES);
135 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
136 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
137 System.out.println(HASHES);
139 CmdLine.main(newArgs);
143 PropAccess access=null;
145 String hasEtc = null;
146 for(String a : args) {
147 if(a.startsWith(Config.CADI_PROP_FILES)) {
148 access = new PropAccess(args);
150 } else if(a.startsWith(Config.CADI_ETCDIR)) {
151 int idx = a.indexOf('=');
152 if(idx>=0 && idx<a.length()) {
153 hasEtc = a.substring(idx+1);
159 if(args.length>1 && args[1].contains("@")) {
160 String domain = FQI.reverseDomain(args[1]);
165 File etc = new File(hasEtc);
167 File nsprops = new File(etc,domain+".props");
168 if(nsprops.exists()) {
169 access = new PropAccess(new String[] {Config.CADI_PROP_FILES+'='+nsprops.getAbsolutePath()});
177 for(Entry<Object, Object> es : System.getProperties().entrySet()) {
178 if(Config.CADI_PROP_FILES.equals(es.getKey())) {
179 access = new PropAccess();
184 // When using Config file, check if Cred Exists, and if not, work with Deployer.
185 if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) {
186 // not enough credentials to use Props. Use AAFSSO
191 if (args.length>1 && args[0].equals("validate") ) {
192 int idx = args[1].indexOf('=');
194 access = new PropAccess(
195 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
197 (idx<0?args[1]:args[1].substring(idx+1)));
199 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
201 public Properties process(String[] args, Properties props) {
203 if (!args[0].equals("keypairgen")) {
204 props.put(Config.AAF_APPID, args[1]);
210 access = aafsso.access();
214 if (aafsso!=null && aafsso.loginOnly()) {
215 aafsso.setLogDefault();
217 System.out.println("AAF SSO information created in ~/.aaf");
219 env = new RosettaEnv(access.getProperties());
220 Deque<String> cmds = new ArrayDeque<String>();
221 for (String p : args) {
223 if ("-noexit".equalsIgnoreCase(p)) {
225 } else if ((eq=p.indexOf('=')) < 0) {
228 access.setProperty(p.substring(0,eq), p.substring(eq+1));
232 if (cmds.size()==0) {
234 aafsso.setLogDefault();
236 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
237 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
238 System.out.println(" create <FQI> [<machine>]");
239 System.out.println(" read <FQI> [<machine>]");
240 System.out.println(" update <FQI> [<machine>]");
241 System.out.println(" delete <FQI> [<machine>]");
242 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
243 System.out.println(" place <FQI> [<machine>]");
244 System.out.println(" showpass <FQI> [<machine>]");
245 System.out.println(" check <FQI> [<machine>]");
246 System.out.println(" keypairgen <FQI>");
247 System.out.println(" config <FQI>");
248 System.out.println(" validate <NS>.props>");
249 System.out.println(" --- Additional Tool Access ---");
250 System.out.println(" ** Type with no params for Tool Help");
251 System.out.println(" ** If using with Agent, preface with \"cadi\"");
252 System.out.println(" cadi <cadi tool params, see -?>");
259 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
261 reqDF = env.newDataFactory(CertificateRequest.class);
262 artifactsDF = env.newDataFactory(Artifacts.class);
263 certDF = env.newDataFactory(CertInfo.class);
264 configDF = env.newDataFactory(Configuration.class);
265 permDF = env.newDataFactory(Perms.class);
266 errMsg = new ErrMessage(env);
268 placeArtifact = new HashMap<>();
269 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
270 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
271 placeArtifact.put(FILE, new PlaceArtifactInFiles());
272 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
273 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
275 Trans trans = env.newTrans();
277 if ((token=access.getProperty("oauth_token"))!=null) {
278 trans.setProperty("oauth_token", token);
282 // show Std out again
283 aafsso.setLogDefault();
284 aafsso.setStdErrDefault();
286 /*urls=*/loadURLs(access);
292 String cmd = cmds.removeFirst();
295 placeCerts(trans,aafcon(access),cmds);
298 createArtifact(trans, aafcon(access),cmds);
301 readArtifact(trans, aafcon(access), cmds);
304 copyArtifact(trans, aafcon(access), cmds);
307 updateArtifact(trans, aafcon(access), cmds);
310 deleteArtifact(trans, aafcon(access), cmds);
313 showPass(trans, aafcon(access), cmds);
316 keypairGen(trans, access, cmds);
319 config(trans,access,args,cmds);
326 exitCode = check(trans,aafcon(access),cmds);
327 } catch (Exception e) {
333 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
336 StringBuilder sb = new StringBuilder();
337 trans.auditTrail(4, sb, Trans.REMOTE);
339 trans.info().log("Trans Info\n",sb);
346 } catch (Exception e) {
350 if (exitCode != 0 && doExit) {
351 System.exit(exitCode);
355 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
357 Map<String,String> rv = new HashMap<>();
358 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
359 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
360 dot_le=dot_le==null?"":'.'+dot_le;
361 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
362 for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) {
366 case "aaf": tag = Config.AAF_URL; break;
367 case "locate":tag = Config.AAF_LOCATE_URL; break;
368 case "oauth": tag = Config.AAF_URL_OAUTH; break;
369 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
370 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
371 case "cm": tag = Config.AAF_URL_CM; break;
372 case "gui": tag = Config.AAF_URL_GUI; break;
373 case "fs": tag = Config.AAF_URL_FS; break;
374 case "hello": tag = Config.AAF_URL_HELLO; break;
376 tag = "aaf_url_" + u;
379 if((value=access.getProperty(tag,null))==null) {
380 String proto = "fs".equals(u)?"http://":"https://";
382 if("locate".equals(u)) {
383 lhost=rph.default_fqdn;
385 lhost=Config.AAF_LOCATE_URL_TAG;
387 value = rph.replacements(AGENT_LOAD_URLS,
388 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
394 value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le);
403 public static void fillMissing(PropAccess access, Map<String, String> map) {
404 for(Entry<String, String> es : map.entrySet()) {
405 if(access.getProperty(es.getKey())==null) {
406 access.setProperty(es.getKey(),es.getValue());
411 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
413 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
418 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
420 if ((value=pa.getProperty(tag))==null) {
422 value = new String(AAFSSO.cons.readPassword(prompt, def));
424 value = AAFSSO.cons.readLine(prompt,def).trim();
427 if (value.length()>0) {
428 pa.setProperty(tag,value);
429 env.setProperty(tag,value);
430 } else if (def.length==1) {
431 value=def[0].toString();
432 pa.setProperty(tag,value);
433 env.setProperty(tag,value);
440 private static String fqi(Deque<String> cmds) {
442 String alias = env.getProperty(Config.CADI_ALIAS);
444 alias = env.getProperty(Config.AAF_APPID);
446 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
448 return cmds.removeFirst();
451 private static String machine(Deque<String> cmds) throws UnknownHostException {
453 return cmds.removeFirst();
455 String mach = env.getProperty(Config.HOSTNAME);
456 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
460 private static String[] machines(Deque<String> cmds) {
463 machines = cmds.removeFirst();
465 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
467 return Split.split(',', machines);
470 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
471 final String mechID = fqi(cmds);
472 final String machine = machine(cmds);
474 Artifacts artifacts = new Artifacts();
475 Artifact arti = new Artifact();
476 artifacts.getArtifact().add(arti);
477 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
478 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
479 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
481 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
482 for (String s : Split.splitTrim(',', resp)) {
483 arti.getType().add(s);
486 if (!resp.contains(SCRIPT)) {
487 arti.getType().add(SCRIPT);
490 // Note: Sponsor is set on Creation by CM
491 String configRootName = FQI.reverseDomain(arti.getMechid());
492 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
493 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
494 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
495 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
496 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
498 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
500 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
501 if (future.get(TIMEOUT)) {
502 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
504 trans.error().printf("Call to AAF Certman failed, %s",
505 errMsg.toMsg(future));
512 private static String toNotification(String notification) {
513 if (notification==null) {
515 } else if (notification.length()>0) {
516 if (notification.indexOf(':')<0) {
517 notification = "mailto:" + notification;
524 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
525 String mechID = fqi(cmds);
526 String machine = machine(cmds);
528 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
530 Future<Artifacts> future = aafcon.client(CM_VER)
531 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
533 if (future.get(TIMEOUT)) {
534 boolean printed = false;
535 for (Artifact a : future.value.getArtifact()) {
536 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
537 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
538 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
539 AAFSSO.cons.printf("CA: %s\n",a.getCa());
540 StringBuilder sb = new StringBuilder();
541 boolean first = true;
542 for (String t : a.getType()) {
543 if (first) {first=false;}
544 else{sb.append(',');}
547 AAFSSO.cons.printf("Types: %s\n",sb);
548 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
549 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
550 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
551 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
552 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
556 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
559 trans.error().log(errMsg.toMsg(future));
566 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
567 String mechID = fqi(cmds);
568 String machine = machine(cmds);
569 String[] newmachs = machines(cmds);
570 if (machine==null || newmachs == null) {
571 trans.error().log("No machines listed to copy to");
573 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
575 Future<Artifacts> future = aafcon.client(CM_VER)
576 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
578 if (future.get(TIMEOUT)) {
579 boolean printed = false;
580 for (Artifact a : future.value.getArtifact()) {
581 for (String m : newmachs) {
583 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
584 if (fup.get(TIMEOUT)) {
585 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
587 trans.error().printf("Call to AAF Certman failed, %s",
595 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
598 trans.error().log(errMsg.toMsg(future));
606 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
607 String mechID = fqi(cmds);
608 String machine = machine(cmds);
610 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
612 Future<Artifacts> fread = aafcon.client(CM_VER)
613 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
615 if (fread.get(TIMEOUT)) {
616 Artifacts artifacts = new Artifacts();
617 for (Artifact a : fread.value.getArtifact()) {
618 Artifact arti = new Artifact();
619 artifacts.getArtifact().add(arti);
621 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
622 arti.setMechid(a.getMechid());
623 arti.setMachine(a.getMachine());
624 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
625 StringBuilder sb = new StringBuilder();
626 boolean first = true;
627 for (String t : a.getType()) {
628 if (first) {first=false;}
629 else{sb.append(',');}
633 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
634 for (String s : Split.splitTrim(',', resp)) {
635 arti.getType().add(s);
638 if (!resp.contains(SCRIPT)) {
639 arti.getType().add(SCRIPT);
642 // Note: Sponsor is set on Creation by CM
643 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
644 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
645 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
646 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
647 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
650 if (artifacts.getArtifact().size()==0) {
651 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
653 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
654 if (fup.get(TIMEOUT)) {
655 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
657 trans.error().printf("Call to AAF Certman failed, %s",
662 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
663 errMsg.toMsg(fread),mechID,machine);
670 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
671 String mechid = fqi(cmds);
672 String machine = machine(cmds);
674 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
676 Future<Void> future = aafcon.client(CM_VER)
677 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
679 if (future.get(TIMEOUT)) {
680 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
682 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
683 errMsg.toMsg(future),mechid,machine);
692 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
694 String mechID = fqi(cmds);
695 String machine = machine(cmds);
696 String[] fqdns = Split.split(':', machine);
698 if (fqdns.length>1) {
705 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
707 Future<Artifacts> acf = aafcon.client(CM_VER)
708 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
709 if (acf.get(TIMEOUT)) {
710 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
711 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
713 for (Artifact a : acf.value.getArtifact()) {
714 String osID = System.getProperty("user.name");
715 if (a.getOsUser().equals(osID)) {
716 CertificateRequest cr = new CertificateRequest();
717 cr.setMechid(a.getMechid());
718 cr.setSponsor(a.getSponsor());
719 for (int i=0;i<fqdns.length;++i) {
720 cr.getFqdns().add(fqdns[i]);
722 Future<String> f = aafcon.client(CM_VER)
723 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
724 if (f.get(TIMEOUT)) {
725 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
726 for (String type : a.getType()) {
727 PlaceArtifact pa = placeArtifact.get(type);
729 if (rv = pa.place(trans, capi, a,machine)) {
734 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
736 trans.error().log(errMsg.toMsg(f));
739 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
743 PropHolder.writeAll();
745 trans.error().log(errMsg.toMsg(acf));
753 private static void notifyPlaced(Artifact a, boolean rv) {
756 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
757 String mechID = fqi(cmds);
758 String machine = machine(cmds);
760 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
762 Future<Artifacts> acf = aafcon.client(CM_VER)
763 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
764 if (acf.get(TIMEOUT)) {
765 // Have to wait for JDK 1.7 source...
766 //switch(artifact.getType()) {
767 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
768 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
770 String id = aafcon.defID();
772 for (Artifact a : acf.value.getArtifact()) {
773 allowed = id!=null && (id.equals(a.getSponsor()) ||
774 (id.equals(a.getMechid())
775 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
777 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
778 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
779 if (pf.get(TIMEOUT)) {
782 trans.error().log(errMsg.toMsg(pf));
786 File dir = new File(a.getDir());
787 Properties props = new Properties();
788 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
791 File chalFile = new File(dir,a.getNs()+".chal");
792 if(chalFile.exists()) {
794 fis = new FileInputStream(chalFile);
801 File f = new File(dir,a.getNs()+".keyfile");
803 Symm symm = ArtifactDir.getSymm(f);
805 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
806 Entry<Object,Object> en = iter.next();
807 if (en.getValue().toString().startsWith("enc:")) {
808 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
812 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
813 f.getAbsolutePath(),a.getMechid(), a.getMachine());
819 trans.error().log(errMsg.toMsg(acf));
827 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
828 final String fqi = fqi(cmds);
829 final String ns = FQI.reverseDomain(fqi);
830 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
831 File f = new File(dir,ns+".key");
834 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
835 if (!"Y".equalsIgnoreCase(line)) {
836 System.out.println("Canceling...");
841 KeyPair kp = Factory.generateKeyPair(trans);
842 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
843 System.out.printf("Wrote %s\n", f.getCanonicalFile());
845 f=new File(dir,ns+".pubkey");
846 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
847 System.out.printf("Wrote %s\n", f.getCanonicalFile());
850 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
851 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
853 final String fqi = fqi(cmds);
854 Artifact arti = new Artifact();
855 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir")));
856 arti.setNs(FQI.reverseDomain(fqi));
857 PropHolder loc = PropHolder.get(arti, "location.props");
858 PropHolder cred = PropHolder.get(arti,"cred.props");
859 PropHolder app= PropHolder.get(arti,"props");
860 for(String c : args) {
861 int idx = c.indexOf('=');
863 app.add(c.substring(0,idx), c.substring(idx+1));
866 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
868 for (String tag : LOC_TAGS) {
869 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
872 String keyfile = cred.getKeyPath();
874 File fkeyfile = new File(keyfile);
875 if(!fkeyfile.exists()) {
876 ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen());
879 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
880 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
881 if(fqi!=null && fqi.equals(ssoAppID)) {
882 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
883 // only Ask for Password when starting scratch
884 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
885 char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi);
887 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
891 // load all properties that are already setup.
892 Map<String, String> aaf_urls = loadURLs(propAccess);
893 for(Entry<String, String> es : aaf_urls.entrySet()) {
894 app.add(es.getKey(), es.getValue());
897 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
898 app.add(Config.AAF_ENV,propAccess, "DEV");
899 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
901 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
904 app.add(Config.AAF_DEPLOYED_VERSION, release);
906 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
907 String key = aaf_loc_prop.getKey().toString();
908 if(key.startsWith("aaf_locator")) {
909 app.add(key, aaf_loc_prop.getValue().toString());
913 app.add(Config.AAF_APPID, fqi);
915 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
916 System.out.println("Passed in Truststore is " + cts);
918 File origTruststore = new File(cts);
919 File newTruststore = new File(app.getDir(),origTruststore.getName());
920 if(!newTruststore.exists()) {
921 if (!origTruststore.exists()) {
922 // Try same directory as cadi_prop_files
923 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
925 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
926 File fcpf = new File(f);
928 int lastSep = cts.lastIndexOf(File.pathSeparator);
929 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
930 if (origTruststore.exists()) {
935 if (!origTruststore.exists()) {
936 throw new CadiException(cts + " does not exist");
941 if (!newTruststore.exists() && origTruststore.exists()) {
942 Files.copy(origTruststore.toPath(), newTruststore.toPath());
946 System.out.println("New Truststore is " + newTruststore);
947 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
948 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
950 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
952 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
953 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
954 String f = propFiles[pfi];
955 System.out.format("Reading %s\n",f);
956 FileInputStream fis = new FileInputStream(f);
958 Properties props = new Properties();
960 for (Entry<Object, Object> prop : props.entrySet()) {
961 boolean lower = true;
962 String key = prop.getKey().toString();
963 if(LOC_TAGS.contains(key)) {
966 for(int i=0;lower && i<key.length();++i) {
967 if(Character.isUpperCase(key.charAt(i))) {
972 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
973 if(key.endsWith("_password")) {
974 ph.addEnc(key, prop.getValue().toString());
976 ph.add(key, prop.getValue().toString());
985 aafcon = aafcon(propAccess);
986 if (aafcon!=null) { // get Properties from Remote AAF
987 for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
988 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
989 if(props.getTag().endsWith("_password")) {
990 ph.addEnc(props.getTag(), props.getValue());
992 ph.add(props.getTag(), props.getValue());
1000 PropHolder.writeAll();
1006 public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, URISyntaxException {
1007 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
1008 .read("/configure/"+fqi+"/aaf", configDF);
1009 if (acf.get(TIMEOUT)) {
1010 return acf.value.getProps();
1011 } else if (acf.code()==401){
1012 trans.error().log("Bad Password sent to AAF");
1013 } else if (acf.code()==404){
1014 trans.error().log("This version of AAF does not support remote Properties");
1016 trans.error().log(errMsg.toMsg(acf));
1018 return new ArrayList<>();
1021 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
1022 System.out.println("Validating Configuration...");
1023 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
1024 aafcon.best(new Retryable<Void>() {
1026 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
1027 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
1028 if (fc.get(aafcon.timeout)) {
1029 System.out.print("Success connecting to ");
1030 System.out.println(client.getURI());
1031 System.out.print(" Permissions for ");
1032 System.out.println(aafcon.defID());
1033 for (Perm p : fc.value.getPerm()) {
1034 System.out.print('\t');
1035 System.out.print(p.getType());
1036 System.out.print('|');
1037 System.out.print(p.getInstance());
1038 System.out.print('|');
1039 System.out.println(p.getAction());
1042 System.err.println("Error: " + fc.code() + ' ' + fc.body());
1050 * Check returns Error Codes, so that Scripts can know what to do
1052 * 0 - Check Complete, nothing to do
1054 * 2 - Error for specific Artifact - read check.msg
1055 * 10 - Certificate Updated - check.msg is email content
1063 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1065 String mechID = fqi(cmds);
1066 String machine = machine(cmds);
1068 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
1071 Future<Artifacts> acf = aafcon.client(CM_VER)
1072 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1073 if (acf.get(TIMEOUT)) {
1074 // Have to wait for JDK 1.7 source...
1075 //switch(artifact.getType()) {
1076 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1077 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1079 String id = aafcon.defID();
1080 GregorianCalendar now = new GregorianCalendar();
1081 for (Artifact a : acf.value.getArtifact()) {
1082 if (id.equals(a.getMechid())) {
1083 File dir = new File(a.getDir());
1084 Properties props = new Properties();
1085 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1095 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1096 !(f=new File(prop)).exists()) {
1097 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1098 a.getMechid(), a.getMachine());
1100 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1101 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1102 if (ksf==null || ksps == null) {
1103 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1104 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1106 Symm symm = ArtifactDir.getSymm(f);
1108 KeyStore ks = KeyStore.getInstance("JKS");
1110 fis = new FileInputStream(ksf);
1112 ks.load(fis,symm.depass(ksps).toCharArray());
1116 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1120 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1121 a.getMechid(), a.getMachine(), ksf);
1122 trans.error().log(msg);
1125 GregorianCalendar renew = new GregorianCalendar();
1126 renew.setTime(cert.getNotAfter());
1127 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1128 if (renew.after(now)) {
1129 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",
1130 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1131 trans.info().log(msg);
1134 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1135 a.getMechid(), a.getMachine(),cert.getNotAfter());
1136 cmds.offerLast(mechID);
1137 cmds.offerLast(machine);
1138 if (placeCerts(trans,aafcon,cmds)) {
1139 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1140 a.getMechid(), a.getMachine());
1141 exitCode = 10; // Refreshed
1143 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1144 a.getMechid(), a.getMachine());
1145 exitCode = 1; // Error Renewing
1150 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1152 fos.write(msg.getBytes());
1164 trans.error().log(errMsg.toMsg(acf));