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);
397 alias = env.getProperty(Config.AAF_APPID);
399 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
401 return cmds.removeFirst();
404 private static String machine(Deque<String> cmds) throws UnknownHostException {
406 return cmds.removeFirst();
408 String mach = env.getProperty(Config.HOSTNAME);
409 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
413 private static String[] machines(Deque<String> cmds) {
416 machines = cmds.removeFirst();
418 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
420 return Split.split(',', machines);
423 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
424 final String mechID = fqi(cmds);
425 final String machine = machine(cmds);
427 Artifacts artifacts = new Artifacts();
428 Artifact arti = new Artifact();
429 artifacts.getArtifact().add(arti);
430 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
431 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
432 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
434 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
435 for (String s : Split.splitTrim(',', resp)) {
436 arti.getType().add(s);
439 if (!resp.contains(SCRIPT)) {
440 arti.getType().add(SCRIPT);
443 // Note: Sponsor is set on Creation by CM
444 String configRootName = FQI.reverseDomain(arti.getMechid());
445 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
446 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
447 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
448 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
449 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
451 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
453 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
454 if (future.get(TIMEOUT)) {
455 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
457 trans.error().printf("Call to AAF Certman failed, %s",
458 errMsg.toMsg(future));
465 private static String toNotification(String notification) {
466 if (notification==null) {
468 } else if (notification.length()>0) {
469 if (notification.indexOf(':')<0) {
470 notification = "mailto:" + notification;
477 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
478 String mechID = fqi(cmds);
479 String machine = machine(cmds);
481 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
483 Future<Artifacts> future = aafcon.client(CM_VER)
484 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
486 if (future.get(TIMEOUT)) {
487 boolean printed = false;
488 for (Artifact a : future.value.getArtifact()) {
489 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
490 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
491 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
492 AAFSSO.cons.printf("CA: %s\n",a.getCa());
493 StringBuilder sb = new StringBuilder();
494 boolean first = true;
495 for (String t : a.getType()) {
496 if (first) {first=false;}
497 else{sb.append(',');}
500 AAFSSO.cons.printf("Types: %s\n",sb);
501 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
502 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
503 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
504 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
505 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
509 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
512 trans.error().log(errMsg.toMsg(future));
519 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
520 String mechID = fqi(cmds);
521 String machine = machine(cmds);
522 String[] newmachs = machines(cmds);
523 if (machine==null || newmachs == null) {
524 trans.error().log("No machines listed to copy to");
526 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
528 Future<Artifacts> future = aafcon.client(CM_VER)
529 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
531 if (future.get(TIMEOUT)) {
532 boolean printed = false;
533 for (Artifact a : future.value.getArtifact()) {
534 for (String m : newmachs) {
536 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
537 if (fup.get(TIMEOUT)) {
538 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
540 trans.error().printf("Call to AAF Certman failed, %s",
548 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
551 trans.error().log(errMsg.toMsg(future));
559 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
560 String mechID = fqi(cmds);
561 String machine = machine(cmds);
563 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
565 Future<Artifacts> fread = aafcon.client(CM_VER)
566 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
568 if (fread.get(TIMEOUT)) {
569 Artifacts artifacts = new Artifacts();
570 for (Artifact a : fread.value.getArtifact()) {
571 Artifact arti = new Artifact();
572 artifacts.getArtifact().add(arti);
574 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
575 arti.setMechid(a.getMechid());
576 arti.setMachine(a.getMachine());
577 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
578 StringBuilder sb = new StringBuilder();
579 boolean first = true;
580 for (String t : a.getType()) {
581 if (first) {first=false;}
582 else{sb.append(',');}
586 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
587 for (String s : Split.splitTrim(',', resp)) {
588 arti.getType().add(s);
591 if (!resp.contains(SCRIPT)) {
592 arti.getType().add(SCRIPT);
595 // Note: Sponsor is set on Creation by CM
596 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
597 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
598 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
599 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
600 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
603 if (artifacts.getArtifact().size()==0) {
604 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
606 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
607 if (fup.get(TIMEOUT)) {
608 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
610 trans.error().printf("Call to AAF Certman failed, %s",
615 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
616 errMsg.toMsg(fread),mechID,machine);
623 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
624 String mechid = fqi(cmds);
625 String machine = machine(cmds);
627 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
629 Future<Void> future = aafcon.client(CM_VER)
630 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
632 if (future.get(TIMEOUT)) {
633 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
635 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
636 errMsg.toMsg(future),mechid,machine);
645 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
647 String mechID = fqi(cmds);
648 String machine = machine(cmds);
649 String[] fqdns = Split.split(':', machine);
651 if (fqdns.length>1) {
658 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
660 Future<Artifacts> acf = aafcon.client(CM_VER)
661 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
662 if (acf.get(TIMEOUT)) {
663 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
664 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
666 for (Artifact a : acf.value.getArtifact()) {
667 String osID = System.getProperty("user.name");
668 if (a.getOsUser().equals(osID)) {
669 CertificateRequest cr = new CertificateRequest();
670 cr.setMechid(a.getMechid());
671 cr.setSponsor(a.getSponsor());
672 for (int i=0;i<fqdns.length;++i) {
673 cr.getFqdns().add(fqdns[i]);
675 Future<String> f = aafcon.client(CM_VER)
676 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
677 if (f.get(TIMEOUT)) {
678 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
679 for (String type : a.getType()) {
680 PlaceArtifact pa = placeArtifact.get(type);
682 if (rv = pa.place(trans, capi, a,machine)) {
687 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
689 trans.error().log(errMsg.toMsg(f));
692 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
696 PropHolder.writeAll();
698 trans.error().log(errMsg.toMsg(acf));
706 private static void notifyPlaced(Artifact a, boolean rv) {
709 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
710 String mechID = fqi(cmds);
711 String machine = machine(cmds);
713 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
715 Future<Artifacts> acf = aafcon.client(CM_VER)
716 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
717 if (acf.get(TIMEOUT)) {
718 // Have to wait for JDK 1.7 source...
719 //switch(artifact.getType()) {
720 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
721 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
723 String id = aafcon.defID();
725 for (Artifact a : acf.value.getArtifact()) {
726 allowed = id!=null && (id.equals(a.getSponsor()) ||
727 (id.equals(a.getMechid())
728 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
730 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
731 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
732 if (pf.get(TIMEOUT)) {
735 trans.error().log(errMsg.toMsg(pf));
739 File dir = new File(a.getDir());
740 Properties props = new Properties();
741 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
744 File chalFile = new File(dir,a.getNs()+".chal");
745 if(chalFile.exists()) {
747 fis = new FileInputStream(chalFile);
754 File f = new File(dir,a.getNs()+".keyfile");
756 Symm symm = ArtifactDir.getSymm(f);
758 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
759 Entry<Object,Object> en = iter.next();
760 if (en.getValue().toString().startsWith("enc:")) {
761 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
765 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
766 f.getAbsolutePath(),a.getMechid(), a.getMachine());
772 trans.error().log(errMsg.toMsg(acf));
780 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
781 final String fqi = fqi(cmds);
782 final String ns = FQI.reverseDomain(fqi);
783 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
784 File f = new File(dir,ns+".key");
787 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
788 if (!"Y".equalsIgnoreCase(line)) {
789 System.out.println("Canceling...");
794 KeyPair kp = Factory.generateKeyPair(trans);
795 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
796 System.out.printf("Wrote %s\n", f.getCanonicalFile());
798 f=new File(dir,ns+".pubkey");
799 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
800 System.out.printf("Wrote %s\n", f.getCanonicalFile());
803 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
804 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
806 final String fqi = fqi(cmds);
807 Artifact arti = new Artifact();
808 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, "."));
809 arti.setNs(FQI.reverseDomain(fqi));
810 PropHolder loc = PropHolder.get(arti, "location.props");
811 PropHolder cred = PropHolder.get(arti,"cred.props");
812 PropHolder app= PropHolder.get(arti,"props");
813 for(String c : args) {
814 int idx = c.indexOf('=');
816 app.add(c.substring(0,idx), c.substring(idx+1));
819 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
821 for (String tag : LOC_TAGS) {
822 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
825 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
826 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
827 if(fqi!=null && fqi.equals(ssoAppID)) {
828 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
829 // only Ask for Password when starting scratch
830 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
831 char[] pwd = AAFSSO.cons.readPassword("Password for %s: ", fqi);
833 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
837 // load all properties that are already setup.
838 Map<String, String> aaf_urls = loadURLs(propAccess);
839 for(Entry<String, String> es : aaf_urls.entrySet()) {
840 app.add(es.getKey(), es.getValue());
843 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
844 app.add(Config.AAF_ENV,propAccess, "DEV");
845 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
847 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
850 app.add(Config.AAF_DEPLOYED_VERSION, release);
852 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
853 String key = aaf_loc_prop.getKey().toString();
854 if(key.startsWith("aaf_locator")) {
855 app.add(key, aaf_loc_prop.getValue().toString());
859 app.add(Config.AAF_APPID, fqi);
861 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
862 System.out.println("Passed in Truststore is " + cts);
864 File origTruststore = new File(cts);
865 File newTruststore = new File(app.getDir(),origTruststore.getName());
866 if(!newTruststore.exists()) {
867 if (!origTruststore.exists()) {
868 // Try same directory as cadi_prop_files
869 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
871 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
872 File fcpf = new File(f);
874 int lastSep = cts.lastIndexOf(File.pathSeparator);
875 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
876 if (origTruststore.exists()) {
881 if (!origTruststore.exists()) {
882 throw new CadiException(cts + " does not exist");
887 if (!newTruststore.exists() && origTruststore.exists()) {
888 Files.copy(origTruststore.toPath(), newTruststore.toPath());
892 System.out.println("New Truststore is " + newTruststore);
893 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
894 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
896 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
898 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
899 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
900 String f = propFiles[pfi];
901 System.out.format("Reading %s\n",f);
902 FileInputStream fis = new FileInputStream(f);
904 Properties props = new Properties();
906 for (Entry<Object, Object> prop : props.entrySet()) {
907 boolean lower = true;
908 String key = prop.getKey().toString();
909 if(LOC_TAGS.contains(key)) {
912 for(int i=0;lower && i<key.length();++i) {
913 if(Character.isUpperCase(key.charAt(i))) {
918 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
919 if(key.endsWith("_password")) {
920 ph.addEnc(key, prop.getValue().toString());
922 ph.add(key, prop.getValue().toString());
931 aafcon = aafcon(propAccess);
932 if (aafcon!=null) { // get Properties from Remote AAF
933 for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
934 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
935 if(props.getTag().endsWith("_password")) {
936 ph.addEnc(props.getTag(), props.getValue());
938 ph.add(props.getTag(), props.getValue());
946 PropHolder.writeAll();
952 public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, URISyntaxException {
953 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
954 .read("/configure/"+fqi+"/aaf", configDF);
955 if (acf.get(TIMEOUT)) {
956 return acf.value.getProps();
957 } else if (acf.code()==401){
958 trans.error().log("Bad Password sent to AAF");
959 } else if (acf.code()==404){
960 trans.error().log("This version of AAF does not support remote Properties");
962 trans.error().log(errMsg.toMsg(acf));
964 return new ArrayList<>();
967 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
968 System.out.println("Validating Configuration...");
969 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
970 aafcon.best(new Retryable<Void>() {
972 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
973 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
974 if (fc.get(aafcon.timeout)) {
975 System.out.print("Success connecting to ");
976 System.out.println(client.getURI());
977 System.out.print(" Permissions for ");
978 System.out.println(aafcon.defID());
979 for (Perm p : fc.value.getPerm()) {
980 System.out.print('\t');
981 System.out.print(p.getType());
982 System.out.print('|');
983 System.out.print(p.getInstance());
984 System.out.print('|');
985 System.out.println(p.getAction());
988 System.err.println("Error: " + fc.code() + ' ' + fc.body());
996 * Check returns Error Codes, so that Scripts can know what to do
998 * 0 - Check Complete, nothing to do
1000 * 2 - Error for specific Artifact - read check.msg
1001 * 10 - Certificate Updated - check.msg is email content
1009 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1011 String mechID = fqi(cmds);
1012 String machine = machine(cmds);
1014 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
1017 Future<Artifacts> acf = aafcon.client(CM_VER)
1018 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1019 if (acf.get(TIMEOUT)) {
1020 // Have to wait for JDK 1.7 source...
1021 //switch(artifact.getType()) {
1022 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1023 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1025 String id = aafcon.defID();
1026 GregorianCalendar now = new GregorianCalendar();
1027 for (Artifact a : acf.value.getArtifact()) {
1028 if (id.equals(a.getMechid())) {
1029 File dir = new File(a.getDir());
1030 Properties props = new Properties();
1031 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1041 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1042 !(f=new File(prop)).exists()) {
1043 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1044 a.getMechid(), a.getMachine());
1046 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1047 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1048 if (ksf==null || ksps == null) {
1049 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1050 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1052 Symm symm = ArtifactDir.getSymm(f);
1054 KeyStore ks = KeyStore.getInstance("JKS");
1056 fis = new FileInputStream(ksf);
1058 ks.load(fis,symm.depass(ksps).toCharArray());
1062 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1066 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1067 a.getMechid(), a.getMachine(), ksf);
1068 trans.error().log(msg);
1071 GregorianCalendar renew = new GregorianCalendar();
1072 renew.setTime(cert.getNotAfter());
1073 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1074 if (renew.after(now)) {
1075 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",
1076 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1077 trans.info().log(msg);
1080 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1081 a.getMechid(), a.getMachine(),cert.getNotAfter());
1082 cmds.offerLast(mechID);
1083 cmds.offerLast(machine);
1084 if (placeCerts(trans,aafcon,cmds)) {
1085 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1086 a.getMechid(), a.getMachine());
1087 exitCode = 10; // Refreshed
1089 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1090 a.getMechid(), a.getMachine());
1091 exitCode = 1; // Error Renewing
1096 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1098 fos.write(msg.getBytes());
1110 trans.error().log(errMsg.toMsg(acf));