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);
145 if (args.length>1 && args[0].equals("validate") ) {
146 int idx = args[1].indexOf('=');
148 access = new PropAccess(
149 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
151 (idx<0?args[1]:args[1].substring(idx+1)));
153 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
155 public Properties process(String[] args, Properties props) {
157 if (!args[0].equals("keypairgen")) {
158 props.put(Config.AAF_APPID, args[1]);
164 access = aafsso.access();
167 if (aafsso!=null && aafsso.loginOnly()) {
168 aafsso.setLogDefault();
170 System.out.println("AAF SSO information created in ~/.aaf");
172 env = new RosettaEnv(access.getProperties());
173 Deque<String> cmds = new ArrayDeque<String>();
174 for (String p : args) {
176 if ("-noexit".equalsIgnoreCase(p)) {
178 } else if ((eq=p.indexOf('=')) < 0) {
181 access.setProperty(p.substring(0,eq), p.substring(eq+1));
185 if (cmds.size()==0) {
187 aafsso.setLogDefault();
189 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
190 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
191 System.out.println(" create <FQI> [<machine>]");
192 System.out.println(" read <FQI> [<machine>]");
193 System.out.println(" update <FQI> [<machine>]");
194 System.out.println(" delete <FQI> [<machine>]");
195 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
196 System.out.println(" place <FQI> [<machine>]");
197 System.out.println(" showpass <FQI> [<machine>]");
198 System.out.println(" check <FQI> [<machine>]");
199 System.out.println(" keypairgen <FQI>");
200 System.out.println(" config <FQI>");
201 System.out.println(" validate <NS>.props>");
202 System.out.println(" --- Additional Tool Access ---");
203 System.out.println(" ** Type with no params for Tool Help");
204 System.out.println(" ** If using with Agent, preface with \"cadi\"");
205 System.out.println(" cadi <cadi tool params, see -?>");
212 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
214 reqDF = env.newDataFactory(CertificateRequest.class);
215 artifactsDF = env.newDataFactory(Artifacts.class);
216 certDF = env.newDataFactory(CertInfo.class);
217 configDF = env.newDataFactory(Configuration.class);
218 permDF = env.newDataFactory(Perms.class);
219 errMsg = new ErrMessage(env);
221 placeArtifact = new HashMap<>();
222 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
223 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
224 placeArtifact.put(FILE, new PlaceArtifactInFiles());
225 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
226 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
228 Trans trans = env.newTrans();
230 if ((token=access.getProperty("oauth_token"))!=null) {
231 trans.setProperty("oauth_token", token);
235 // show Std out again
236 aafsso.setLogDefault();
237 aafsso.setStdErrDefault();
239 /*urls=*/loadURLs(access);
245 String cmd = cmds.removeFirst();
248 placeCerts(trans,aafcon(access),cmds);
251 createArtifact(trans, aafcon(access),cmds);
254 readArtifact(trans, aafcon(access), cmds);
257 copyArtifact(trans, aafcon(access), cmds);
260 updateArtifact(trans, aafcon(access), cmds);
263 deleteArtifact(trans, aafcon(access), cmds);
266 showPass(trans, aafcon(access), cmds);
269 keypairGen(trans, access, cmds);
272 config(trans,access,args,cmds);
279 exitCode = check(trans,aafcon(access),cmds);
280 } catch (Exception e) {
286 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
289 StringBuilder sb = new StringBuilder();
290 trans.auditTrail(4, sb, Trans.REMOTE);
292 trans.info().log("Trans Info\n",sb);
299 } catch (Exception e) {
303 if (exitCode != 0 && doExit) {
304 System.exit(exitCode);
308 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
310 Map<String,String> rv = new HashMap<>();
311 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
312 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
313 dot_le=dot_le==null?"":'.'+dot_le;
314 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
315 for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) {
319 case "aaf": tag = Config.AAF_URL; break;
320 case "locate":tag = Config.AAF_LOCATE_URL; break;
321 case "oauth": tag = Config.AAF_URL_OAUTH; break;
322 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
323 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
324 case "cm": tag = Config.AAF_URL_CM; break;
325 case "gui": tag = Config.AAF_URL_GUI; break;
326 case "fs": tag = Config.AAF_URL_FS; break;
327 case "hello": tag = Config.AAF_URL_HELLO; break;
329 tag = "aaf_url_" + u;
332 if((value=access.getProperty(tag,null))==null) {
333 String proto = "fs".equals(u)?"http://":"https://";
335 if("locate".equals(u)) {
336 lhost=rph.default_fqdn;
338 lhost=Config.AAF_LOCATE_URL_TAG;
340 value = rph.replacements(AGENT_LOAD_URLS,
341 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
347 value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le);
356 public static void fillMissing(PropAccess access, Map<String, String> map) {
357 for(Entry<String, String> es : map.entrySet()) {
358 if(access.getProperty(es.getKey())==null) {
359 access.setProperty(es.getKey(),es.getValue());
364 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
366 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
371 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
373 if ((value=pa.getProperty(tag))==null) {
375 value = new String(AAFSSO.cons.readPassword(prompt, def));
377 value = AAFSSO.cons.readLine(prompt,def).trim();
380 if (value.length()>0) {
381 pa.setProperty(tag,value);
382 env.setProperty(tag,value);
383 } else if (def.length==1) {
384 value=def[0].toString();
385 pa.setProperty(tag,value);
386 env.setProperty(tag,value);
393 private static String fqi(Deque<String> cmds) {
395 String alias = env.getProperty(Config.CADI_ALIAS);
396 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
398 return cmds.removeFirst();
401 private static String machine(Deque<String> cmds) throws UnknownHostException {
403 return cmds.removeFirst();
405 String mach = env.getProperty(Config.HOSTNAME);
406 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
410 private static String[] machines(Deque<String> cmds) {
413 machines = cmds.removeFirst();
415 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
417 return Split.split(',', machines);
420 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
421 final String mechID = fqi(cmds);
422 final String machine = machine(cmds);
424 Artifacts artifacts = new Artifacts();
425 Artifact arti = new Artifact();
426 artifacts.getArtifact().add(arti);
427 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
428 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
429 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
431 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
432 for (String s : Split.splitTrim(',', resp)) {
433 arti.getType().add(s);
436 if (!resp.contains(SCRIPT)) {
437 arti.getType().add(SCRIPT);
440 // Note: Sponsor is set on Creation by CM
441 String configRootName = FQI.reverseDomain(arti.getMechid());
442 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
443 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
444 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
445 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
446 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
448 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
450 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
451 if (future.get(TIMEOUT)) {
452 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
454 trans.error().printf("Call to AAF Certman failed, %s",
455 errMsg.toMsg(future));
462 private static String toNotification(String notification) {
463 if (notification==null) {
465 } else if (notification.length()>0) {
466 if (notification.indexOf(':')<0) {
467 notification = "mailto:" + notification;
474 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
475 String mechID = fqi(cmds);
476 String machine = machine(cmds);
478 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
480 Future<Artifacts> future = aafcon.client(CM_VER)
481 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
483 if (future.get(TIMEOUT)) {
484 boolean printed = false;
485 for (Artifact a : future.value.getArtifact()) {
486 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
487 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
488 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
489 AAFSSO.cons.printf("CA: %s\n",a.getCa());
490 StringBuilder sb = new StringBuilder();
491 boolean first = true;
492 for (String t : a.getType()) {
493 if (first) {first=false;}
494 else{sb.append(',');}
497 AAFSSO.cons.printf("Types: %s\n",sb);
498 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
499 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
500 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
501 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
502 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
506 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
509 trans.error().log(errMsg.toMsg(future));
516 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
517 String mechID = fqi(cmds);
518 String machine = machine(cmds);
519 String[] newmachs = machines(cmds);
520 if (machine==null || newmachs == null) {
521 trans.error().log("No machines listed to copy to");
523 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
525 Future<Artifacts> future = aafcon.client(CM_VER)
526 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
528 if (future.get(TIMEOUT)) {
529 boolean printed = false;
530 for (Artifact a : future.value.getArtifact()) {
531 for (String m : newmachs) {
533 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
534 if (fup.get(TIMEOUT)) {
535 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
537 trans.error().printf("Call to AAF Certman failed, %s",
545 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
548 trans.error().log(errMsg.toMsg(future));
556 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
557 String mechID = fqi(cmds);
558 String machine = machine(cmds);
560 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
562 Future<Artifacts> fread = aafcon.client(CM_VER)
563 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
565 if (fread.get(TIMEOUT)) {
566 Artifacts artifacts = new Artifacts();
567 for (Artifact a : fread.value.getArtifact()) {
568 Artifact arti = new Artifact();
569 artifacts.getArtifact().add(arti);
571 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
572 arti.setMechid(a.getMechid());
573 arti.setMachine(a.getMachine());
574 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
575 StringBuilder sb = new StringBuilder();
576 boolean first = true;
577 for (String t : a.getType()) {
578 if (first) {first=false;}
579 else{sb.append(',');}
583 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
584 for (String s : Split.splitTrim(',', resp)) {
585 arti.getType().add(s);
588 if (!resp.contains(SCRIPT)) {
589 arti.getType().add(SCRIPT);
592 // Note: Sponsor is set on Creation by CM
593 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
594 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
595 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
596 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
597 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
600 if (artifacts.getArtifact().size()==0) {
601 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
603 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
604 if (fup.get(TIMEOUT)) {
605 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
607 trans.error().printf("Call to AAF Certman failed, %s",
612 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
613 errMsg.toMsg(fread),mechID,machine);
620 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
621 String mechid = fqi(cmds);
622 String machine = machine(cmds);
624 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
626 Future<Void> future = aafcon.client(CM_VER)
627 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
629 if (future.get(TIMEOUT)) {
630 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
632 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
633 errMsg.toMsg(future),mechid,machine);
642 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
644 String mechID = fqi(cmds);
645 String machine = machine(cmds);
646 String[] fqdns = Split.split(':', machine);
648 if (fqdns.length>1) {
655 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
657 Future<Artifacts> acf = aafcon.client(CM_VER)
658 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
659 if (acf.get(TIMEOUT)) {
660 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
661 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
663 for (Artifact a : acf.value.getArtifact()) {
664 String osID = System.getProperty("user.name");
665 if (a.getOsUser().equals(osID)) {
666 CertificateRequest cr = new CertificateRequest();
667 cr.setMechid(a.getMechid());
668 cr.setSponsor(a.getSponsor());
669 for (int i=0;i<fqdns.length;++i) {
670 cr.getFqdns().add(fqdns[i]);
672 Future<String> f = aafcon.client(CM_VER)
673 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
674 if (f.get(TIMEOUT)) {
675 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
676 for (String type : a.getType()) {
677 PlaceArtifact pa = placeArtifact.get(type);
679 if (rv = pa.place(trans, capi, a,machine)) {
684 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
686 trans.error().log(errMsg.toMsg(f));
689 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
693 PropHolder.writeAll();
695 trans.error().log(errMsg.toMsg(acf));
703 private static void notifyPlaced(Artifact a, boolean rv) {
706 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
707 String mechID = fqi(cmds);
708 String machine = machine(cmds);
710 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
712 Future<Artifacts> acf = aafcon.client(CM_VER)
713 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
714 if (acf.get(TIMEOUT)) {
715 // Have to wait for JDK 1.7 source...
716 //switch(artifact.getType()) {
717 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
718 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
720 String id = aafcon.defID();
722 for (Artifact a : acf.value.getArtifact()) {
723 allowed = id!=null && (id.equals(a.getSponsor()) ||
724 (id.equals(a.getMechid())
725 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
727 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
728 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
729 if (pf.get(TIMEOUT)) {
732 trans.error().log(errMsg.toMsg(pf));
736 File dir = new File(a.getDir());
737 Properties props = new Properties();
738 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
741 File chalFile = new File(dir,a.getNs()+".chal");
742 if(chalFile.exists()) {
744 fis = new FileInputStream(chalFile);
751 File f = new File(dir,a.getNs()+".keyfile");
753 Symm symm = ArtifactDir.getSymm(f);
755 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
756 Entry<Object,Object> en = iter.next();
757 if (en.getValue().toString().startsWith("enc:")) {
758 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
762 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
763 f.getAbsolutePath(),a.getMechid(), a.getMachine());
769 trans.error().log(errMsg.toMsg(acf));
777 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
778 final String fqi = fqi(cmds);
779 final String ns = FQI.reverseDomain(fqi);
780 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
781 File f = new File(dir,ns+".key");
784 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
785 if (!"Y".equalsIgnoreCase(line)) {
786 System.out.println("Canceling...");
791 KeyPair kp = Factory.generateKeyPair(trans);
792 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
793 System.out.printf("Wrote %s\n", f.getCanonicalFile());
795 f=new File(dir,ns+".pubkey");
796 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
797 System.out.printf("Wrote %s\n", f.getCanonicalFile());
800 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
801 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
803 final String fqi = fqi(cmds);
804 Artifact arti = new Artifact();
805 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, "."));
806 arti.setNs(FQI.reverseDomain(fqi));
807 PropHolder loc = PropHolder.get(arti, "location.props");
808 PropHolder cred = PropHolder.get(arti,"cred.props");
809 PropHolder app= PropHolder.get(arti,"props");
810 for(String c : args) {
811 int idx = c.indexOf('=');
813 app.add(c.substring(0,idx), c.substring(idx+1));
816 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
818 for (String tag : LOC_TAGS) {
819 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
822 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
823 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
824 if(fqi!=null && fqi.equals(ssoAppID)) {
825 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
826 // only Ask for Password when starting scratch
827 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
828 char[] pwd = AAFSSO.cons.readPassword("Password for %s: ", fqi);
830 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
834 // load all properties that are already setup.
835 Map<String, String> aaf_urls = loadURLs(propAccess);
836 for(Entry<String, String> es : aaf_urls.entrySet()) {
837 app.add(es.getKey(), es.getValue());
840 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
841 app.add(Config.AAF_ENV,propAccess, "DEV");
842 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
844 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
847 app.add(Config.AAF_DEPLOYED_VERSION, release);
849 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
850 String key = aaf_loc_prop.getKey().toString();
851 if(key.startsWith("aaf_locator")) {
852 app.add(key, aaf_loc_prop.getValue().toString());
856 app.add(Config.AAF_APPID, fqi);
858 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
859 System.out.println("Passed in Truststore is " + cts);
861 File origTruststore = new File(cts);
862 File newTruststore = new File(app.getDir(),origTruststore.getName());
863 if(!newTruststore.exists()) {
864 if (!origTruststore.exists()) {
865 // Try same directory as cadi_prop_files
866 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
868 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
869 File fcpf = new File(f);
871 int lastSep = cts.lastIndexOf(File.pathSeparator);
872 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
873 if (origTruststore.exists()) {
878 if (!origTruststore.exists()) {
879 throw new CadiException(cts + " does not exist");
884 if (!newTruststore.exists() && origTruststore.exists()) {
885 Files.copy(origTruststore.toPath(), newTruststore.toPath());
889 System.out.println("New Truststore is " + newTruststore);
890 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
891 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
893 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
895 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
896 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
897 String f = propFiles[pfi];
898 System.out.format("Reading %s\n",f);
899 FileInputStream fis = new FileInputStream(f);
901 Properties props = new Properties();
903 for (Entry<Object, Object> prop : props.entrySet()) {
904 boolean lower = true;
905 String key = prop.getKey().toString();
906 if(LOC_TAGS.contains(key)) {
909 for(int i=0;lower && i<key.length();++i) {
910 if(Character.isUpperCase(key.charAt(i))) {
915 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
916 if(key.endsWith("_password")) {
917 ph.addEnc(key, prop.getValue().toString());
919 ph.add(key, prop.getValue().toString());
928 aafcon = aafcon(propAccess);
929 if (aafcon!=null) { // get Properties from Remote AAF
930 for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
931 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
932 if(props.getTag().endsWith("_password")) {
933 ph.addEnc(props.getTag(), props.getValue());
935 ph.add(props.getTag(), props.getValue());
943 PropHolder.writeAll();
949 public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, URISyntaxException {
950 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
951 .read("/configure/"+fqi+"/aaf", configDF);
952 if (acf.get(TIMEOUT)) {
953 return acf.value.getProps();
954 } else if (acf.code()==401){
955 trans.error().log("Bad Password sent to AAF");
956 } else if (acf.code()==404){
957 trans.error().log("This version of AAF does not support remote Properties");
959 trans.error().log(errMsg.toMsg(acf));
961 return new ArrayList<>();
964 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
965 System.out.println("Validating Configuration...");
966 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
967 aafcon.best(new Retryable<Void>() {
969 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
970 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
971 if (fc.get(aafcon.timeout)) {
972 System.out.print("Success connecting to ");
973 System.out.println(client.getURI());
974 System.out.print(" Permissions for ");
975 System.out.println(aafcon.defID());
976 for (Perm p : fc.value.getPerm()) {
977 System.out.print('\t');
978 System.out.print(p.getType());
979 System.out.print('|');
980 System.out.print(p.getInstance());
981 System.out.print('|');
982 System.out.println(p.getAction());
985 System.err.println("Error: " + fc.code() + ' ' + fc.body());
993 * Check returns Error Codes, so that Scripts can know what to do
995 * 0 - Check Complete, nothing to do
997 * 2 - Error for specific Artifact - read check.msg
998 * 10 - Certificate Updated - check.msg is email content
1006 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1008 String mechID = fqi(cmds);
1009 String machine = machine(cmds);
1011 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
1014 Future<Artifacts> acf = aafcon.client(CM_VER)
1015 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1016 if (acf.get(TIMEOUT)) {
1017 // Have to wait for JDK 1.7 source...
1018 //switch(artifact.getType()) {
1019 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1020 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1022 String id = aafcon.defID();
1023 GregorianCalendar now = new GregorianCalendar();
1024 for (Artifact a : acf.value.getArtifact()) {
1025 if (id.equals(a.getMechid())) {
1026 File dir = new File(a.getDir());
1027 Properties props = new Properties();
1028 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1038 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1039 !(f=new File(prop)).exists()) {
1040 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1041 a.getMechid(), a.getMachine());
1043 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1044 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1045 if (ksf==null || ksps == null) {
1046 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1047 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1049 Symm symm = ArtifactDir.getSymm(f);
1051 KeyStore ks = KeyStore.getInstance("JKS");
1053 fis = new FileInputStream(ksf);
1055 ks.load(fis,symm.depass(ksps).toCharArray());
1059 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1063 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1064 a.getMechid(), a.getMachine(), ksf);
1065 trans.error().log(msg);
1068 GregorianCalendar renew = new GregorianCalendar();
1069 renew.setTime(cert.getNotAfter());
1070 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1071 if (renew.after(now)) {
1072 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",
1073 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1074 trans.info().log(msg);
1077 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1078 a.getMechid(), a.getMachine(),cert.getNotAfter());
1079 cmds.offerLast(mechID);
1080 cmds.offerLast(machine);
1081 if (placeCerts(trans,aafcon,cmds)) {
1082 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1083 a.getMechid(), a.getMachine());
1084 exitCode = 10; // Refreshed
1086 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1087 a.getMechid(), a.getMachine());
1088 exitCode = 1; // Error Renewing
1093 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1095 fos.write(msg.getBytes());
1107 trans.error().log(errMsg.toMsg(acf));