2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.cadi.configure;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.net.ConnectException;
29 import java.net.HttpURLConnection;
30 import java.net.InetAddress;
31 import java.net.UnknownHostException;
32 import java.nio.file.Files;
33 import java.security.KeyPair;
34 import java.security.KeyStore;
35 import java.security.cert.X509Certificate;
36 import java.util.ArrayDeque;
37 import java.util.Arrays;
38 import java.util.Deque;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
44 import java.util.Map.Entry;
45 import java.util.Properties;
47 import org.onap.aaf.cadi.Access;
48 import org.onap.aaf.cadi.CadiException;
49 import org.onap.aaf.cadi.CmdLine;
50 import org.onap.aaf.cadi.LocatorException;
51 import org.onap.aaf.cadi.PropAccess;
52 import org.onap.aaf.cadi.Symm;
53 import org.onap.aaf.cadi.aaf.client.ErrMessage;
54 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
55 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
56 import org.onap.aaf.cadi.client.Future;
57 import org.onap.aaf.cadi.client.Rcli;
58 import org.onap.aaf.cadi.client.Retryable;
59 import org.onap.aaf.cadi.config.Config;
60 import org.onap.aaf.cadi.config.RegistrationPropHolder;
61 import org.onap.aaf.cadi.config.SecurityInfoC;
62 import org.onap.aaf.cadi.http.HBasicAuthSS;
63 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
64 import org.onap.aaf.cadi.sso.AAFSSO;
65 import org.onap.aaf.cadi.util.Chmod;
66 import org.onap.aaf.cadi.util.FQI;
67 import org.onap.aaf.misc.env.APIException;
68 import org.onap.aaf.misc.env.Data.TYPE;
69 import org.onap.aaf.misc.env.Env;
70 import org.onap.aaf.misc.env.TimeTaken;
71 import org.onap.aaf.misc.env.Trans;
72 import org.onap.aaf.misc.env.util.Chrono;
73 import org.onap.aaf.misc.env.util.Split;
74 import org.onap.aaf.misc.rosetta.env.RosettaDF;
75 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
78 import aaf.v2_0.Perms;
79 import certman.v1_0.Artifacts;
80 import certman.v1_0.Artifacts.Artifact;
81 import certman.v1_0.CertInfo;
82 import certman.v1_0.CertificateRequest;
83 import locate.v1_1.Configuration;
84 import locate.v1_1.Configuration.Props;
87 private static final String HASHES = "################################################################";
88 private static final String PRINT = "print";
89 private static final String FILE = "file";
90 public static final String PKCS12 = "pkcs12";
91 public static final String JKS = "jks";
92 private static final String SCRIPT="script";
94 private static final String CM_VER = "1.0";
95 public static final int PASS_SIZE = 24;
96 private static int TIMEOUT;
98 private static RosettaDF<CertificateRequest> reqDF;
99 private static RosettaDF<CertInfo> certDF;
100 private static RosettaDF<Artifacts> artifactsDF;
101 private static RosettaDF<Configuration> configDF;
102 private static RosettaDF<Perms> permDF;
103 private static ErrMessage errMsg;
104 private static Map<String,PlaceArtifact> placeArtifact;
105 private static RosettaEnv env;
107 private static boolean doExit;
108 private static AAFCon<?> aafcon;
110 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
112 Config.AAF_APPID, Config.AAF_APPPASS,
113 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
114 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
115 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
117 private static List<String> LOC_TAGS = Arrays.asList(new String[] {
118 Config.CADI_LATITUDE, Config.CADI_LONGITUDE
120 // Note: This is set by loadURLs. Use that function as singleton, not directly.
121 private static Map<String,String> aaf_urls = null;
124 public static void main(String[] args) {
127 if (args.length>0 && "cadi".equals(args[0])) {
128 String[] newArgs = new String[args.length-1];
129 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
130 if (newArgs.length==0) {
131 System.out.println(HASHES);
132 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
133 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
134 System.out.println(HASHES);
136 CmdLine.main(newArgs);
142 if (args.length>1 && args[0].equals("validate") ) {
143 int idx = args[1].indexOf('=');
145 access = new PropAccess(
146 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
148 (idx<0?args[1]:args[1].substring(idx+1)));
150 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
152 public Properties process(String[] args, Properties props) {
154 if (!args[0].equals("keypairgen")) {
155 props.put(Config.AAF_APPID, args[1]);
161 access = aafsso.access();
164 if (aafsso!=null && aafsso.loginOnly()) {
165 aafsso.setLogDefault();
167 System.out.println("AAF SSO information created in ~/.aaf");
169 env = new RosettaEnv(access.getProperties());
170 Deque<String> cmds = new ArrayDeque<String>();
171 for (String p : args) {
173 if ("-noexit".equalsIgnoreCase(p)) {
175 } else if ((eq=p.indexOf('=')) < 0) {
178 access.setProperty(p.substring(0,eq), p.substring(eq+1));
182 if (cmds.size()==0) {
184 aafsso.setLogDefault();
186 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
187 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
188 System.out.println(" create <FQI> [<machine>]");
189 System.out.println(" read <FQI> [<machine>]");
190 System.out.println(" update <FQI> [<machine>]");
191 System.out.println(" delete <FQI> [<machine>]");
192 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
193 System.out.println(" place <FQI> [<machine>]");
194 System.out.println(" showpass <FQI> [<machine>]");
195 System.out.println(" check <FQI> [<machine>]");
196 System.out.println(" keypairgen <FQI>");
197 System.out.println(" config <FQI>");
198 System.out.println(" validate <NS>.props>");
199 System.out.println(" --- Additional Tool Access ---");
200 System.out.println(" ** Type with no params for Tool Help");
201 System.out.println(" ** If using with Agent, preface with \"cadi\"");
202 System.out.println(" cadi <cadi tool params, see -?>");
209 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
211 reqDF = env.newDataFactory(CertificateRequest.class);
212 artifactsDF = env.newDataFactory(Artifacts.class);
213 certDF = env.newDataFactory(CertInfo.class);
214 configDF = env.newDataFactory(Configuration.class);
215 permDF = env.newDataFactory(Perms.class);
216 errMsg = new ErrMessage(env);
218 placeArtifact = new HashMap<>();
219 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
220 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
221 placeArtifact.put(FILE, new PlaceArtifactInFiles());
222 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
223 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
225 Trans trans = env.newTrans();
227 if ((token=access.getProperty("oauth_token"))!=null) {
228 trans.setProperty("oauth_token", token);
232 // show Std out again
233 aafsso.setLogDefault();
234 aafsso.setStdErrDefault();
236 Map<String, String> aaf_urls = loadURLs(access);
237 aafsso.addProp(Config.AAF_URL_CM, aaf_urls.get(Config.AAF_URL_CM));
243 String cmd = cmds.removeFirst();
246 placeCerts(trans,aafcon(access),cmds);
249 createArtifact(trans, aafcon(access),cmds);
252 readArtifact(trans, aafcon(access), cmds);
255 copyArtifact(trans, aafcon(access), cmds);
258 updateArtifact(trans, aafcon(access), cmds);
261 deleteArtifact(trans, aafcon(access), cmds);
264 showPass(trans, aafcon(access), cmds);
267 keypairGen(trans, access, cmds);
270 config(trans,access,args,cmds);
277 exitCode = check(trans,aafcon(access),cmds);
278 } catch (Exception e) {
284 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
287 StringBuilder sb = new StringBuilder();
288 trans.auditTrail(4, sb, Trans.REMOTE);
290 trans.info().log("Trans Info\n",sb);
297 } catch (Exception e) {
301 if (exitCode != 0 && doExit) {
302 System.exit(exitCode);
306 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
308 Map<String,String> rv = new HashMap<>();
309 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
310 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
311 dot_le=dot_le==null?"":'.'+dot_le;
312 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
313 for(String u : new String[] {"aaf","locate","oauth","cm","gui","fs","hello","token","introspect"}) {
314 String proto = "fs".equals(u)?"http://":"https://";
316 if("locate".equals(u)) {
317 lhost=rph.default_fqdn;
319 lhost=Config.AAF_LOCATE_URL_TAG;
321 String value = rph.replacements("Agent:loadURLs",
322 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
325 case "aaf": rv.put(Config.AAF_URL, value); break;
326 case "locate": rv.put(Config.getAAFLocateUrl(access), value); break;
327 case "token": rv.put(Config.AAF_OAUTH2_TOKEN_URL, value); break;
328 case "introspect": rv.put(Config.AAF_OAUTH2_INTROSPECT_URL, value); break;
329 case "cm": rv.put(Config.AAF_URL_CM, value); break;
330 case "gui": rv.put(Config.AAF_URL_GUI, value); break;
331 case "fs": rv.put(Config.AAF_URL_FS, value); break;
332 case "hello": rv.put(Config.AAF_URL_HELLO, value); break;
334 rv.put("aaf_url_" + u, value);
342 public static void fillMissing(PropAccess access, Map<String, String> map) {
343 for(Entry<String, String> es : map.entrySet()) {
344 if(access.getProperty(es.getKey())==null) {
345 access.setProperty(es.getKey(),es.getValue());
350 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
352 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
357 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
359 if ((value=pa.getProperty(tag))==null) {
361 value = new String(AAFSSO.cons.readPassword(prompt, def));
363 value = AAFSSO.cons.readLine(prompt,def).trim();
366 if (value.length()>0) {
367 pa.setProperty(tag,value);
368 env.setProperty(tag,value);
369 } else if (def.length==1) {
370 value=def[0].toString();
371 pa.setProperty(tag,value);
372 env.setProperty(tag,value);
379 private static String fqi(Deque<String> cmds) {
381 String alias = env.getProperty(Config.CADI_ALIAS);
382 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
384 return cmds.removeFirst();
387 private static String machine(Deque<String> cmds) throws UnknownHostException {
389 return cmds.removeFirst();
391 String mach = env.getProperty(Config.HOSTNAME);
392 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
396 private static String[] machines(Deque<String> cmds) {
399 machines = cmds.removeFirst();
401 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
403 return Split.split(',', machines);
406 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
407 final String mechID = fqi(cmds);
408 final String machine = machine(cmds);
410 Artifacts artifacts = new Artifacts();
411 Artifact arti = new Artifact();
412 artifacts.getArtifact().add(arti);
413 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
414 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
415 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
417 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
418 for (String s : Split.splitTrim(',', resp)) {
419 arti.getType().add(s);
422 if (!resp.contains(SCRIPT)) {
423 arti.getType().add(SCRIPT);
426 // Note: Sponsor is set on Creation by CM
427 String configRootName = FQI.reverseDomain(arti.getMechid());
428 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
429 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
430 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
431 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
432 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
434 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
436 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
437 if (future.get(TIMEOUT)) {
438 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
440 trans.error().printf("Call to AAF Certman failed, %s",
441 errMsg.toMsg(future));
448 private static String toNotification(String notification) {
449 if (notification==null) {
451 } else if (notification.length()>0) {
452 if (notification.indexOf(':')<0) {
453 notification = "mailto:" + notification;
460 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
461 String mechID = fqi(cmds);
462 String machine = machine(cmds);
464 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
466 Future<Artifacts> future = aafcon.client(CM_VER)
467 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
469 if (future.get(TIMEOUT)) {
470 boolean printed = false;
471 for (Artifact a : future.value.getArtifact()) {
472 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
473 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
474 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
475 AAFSSO.cons.printf("CA: %s\n",a.getCa());
476 StringBuilder sb = new StringBuilder();
477 boolean first = true;
478 for (String t : a.getType()) {
479 if (first) {first=false;}
480 else{sb.append(',');}
483 AAFSSO.cons.printf("Types: %s\n",sb);
484 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
485 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
486 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
487 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
488 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
492 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
495 trans.error().log(errMsg.toMsg(future));
502 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
503 String mechID = fqi(cmds);
504 String machine = machine(cmds);
505 String[] newmachs = machines(cmds);
506 if (machine==null || newmachs == null) {
507 trans.error().log("No machines listed to copy to");
509 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
511 Future<Artifacts> future = aafcon.client(CM_VER)
512 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
514 if (future.get(TIMEOUT)) {
515 boolean printed = false;
516 for (Artifact a : future.value.getArtifact()) {
517 for (String m : newmachs) {
519 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
520 if (fup.get(TIMEOUT)) {
521 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
523 trans.error().printf("Call to AAF Certman failed, %s",
531 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
534 trans.error().log(errMsg.toMsg(future));
542 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
543 String mechID = fqi(cmds);
544 String machine = machine(cmds);
546 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
548 Future<Artifacts> fread = aafcon.client(CM_VER)
549 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
551 if (fread.get(TIMEOUT)) {
552 Artifacts artifacts = new Artifacts();
553 for (Artifact a : fread.value.getArtifact()) {
554 Artifact arti = new Artifact();
555 artifacts.getArtifact().add(arti);
557 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
558 arti.setMechid(a.getMechid());
559 arti.setMachine(a.getMachine());
560 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
561 StringBuilder sb = new StringBuilder();
562 boolean first = true;
563 for (String t : a.getType()) {
564 if (first) {first=false;}
565 else{sb.append(',');}
569 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
570 for (String s : Split.splitTrim(',', resp)) {
571 arti.getType().add(s);
574 if (!resp.contains(SCRIPT)) {
575 arti.getType().add(SCRIPT);
578 // Note: Sponsor is set on Creation by CM
579 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
580 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
581 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
582 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
583 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
586 if (artifacts.getArtifact().size()==0) {
587 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
589 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
590 if (fup.get(TIMEOUT)) {
591 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
593 trans.error().printf("Call to AAF Certman failed, %s",
598 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
599 errMsg.toMsg(fread),mechID,machine);
606 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
607 String mechid = fqi(cmds);
608 String machine = machine(cmds);
610 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
612 Future<Void> future = aafcon.client(CM_VER)
613 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
615 if (future.get(TIMEOUT)) {
616 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
618 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
619 errMsg.toMsg(future),mechid,machine);
628 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
630 String mechID = fqi(cmds);
631 String machine = machine(cmds);
632 String[] fqdns = Split.split(':', machine);
634 if (fqdns.length>1) {
641 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
643 Future<Artifacts> acf = aafcon.client(CM_VER)
644 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
645 if (acf.get(TIMEOUT)) {
646 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
647 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
649 for (Artifact a : acf.value.getArtifact()) {
650 String osID = System.getProperty("user.name");
651 if (a.getOsUser().equals(osID)) {
652 CertificateRequest cr = new CertificateRequest();
653 cr.setMechid(a.getMechid());
654 cr.setSponsor(a.getSponsor());
655 for (int i=0;i<fqdns.length;++i) {
656 cr.getFqdns().add(fqdns[i]);
658 Future<String> f = aafcon.client(CM_VER)
659 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
660 if (f.get(TIMEOUT)) {
661 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
662 for (String type : a.getType()) {
663 PlaceArtifact pa = placeArtifact.get(type);
665 if (rv = pa.place(trans, capi, a,machine)) {
670 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
672 trans.error().log(errMsg.toMsg(f));
675 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
679 PropHolder.writeAll();
681 trans.error().log(errMsg.toMsg(acf));
689 private static void notifyPlaced(Artifact a, boolean rv) {
692 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
693 String mechID = fqi(cmds);
694 String machine = machine(cmds);
696 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
698 Future<Artifacts> acf = aafcon.client(CM_VER)
699 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
700 if (acf.get(TIMEOUT)) {
701 // Have to wait for JDK 1.7 source...
702 //switch(artifact.getType()) {
703 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
704 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
706 String id = aafcon.defID();
708 for (Artifact a : acf.value.getArtifact()) {
709 allowed = id!=null && (id.equals(a.getSponsor()) ||
710 (id.equals(a.getMechid())
711 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
713 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
714 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
715 if (pf.get(TIMEOUT)) {
718 trans.error().log(errMsg.toMsg(pf));
722 File dir = new File(a.getDir());
723 Properties props = new Properties();
724 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
727 File chalFile = new File(dir,a.getNs()+".chal");
728 if(chalFile.exists()) {
730 fis = new FileInputStream(chalFile);
737 File f = new File(dir,a.getNs()+".keyfile");
739 Symm symm = ArtifactDir.getSymm(f);
741 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
742 Entry<Object,Object> en = iter.next();
743 if (en.getValue().toString().startsWith("enc:")) {
744 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
748 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
749 f.getAbsolutePath(),a.getMechid(), a.getMachine());
755 trans.error().log(errMsg.toMsg(acf));
763 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
764 final String fqi = fqi(cmds);
765 final String ns = FQI.reverseDomain(fqi);
766 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
767 File f = new File(dir,ns+".key");
770 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
771 if (!"Y".equalsIgnoreCase(line)) {
772 System.out.println("Canceling...");
777 KeyPair kp = Factory.generateKeyPair(trans);
778 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
779 System.out.printf("Wrote %s\n", f.getCanonicalFile());
781 f=new File(dir,ns+".pubkey");
782 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
783 System.out.printf("Wrote %s\n", f.getCanonicalFile());
786 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
787 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
789 final String fqi = fqi(cmds);
790 Artifact arti = new Artifact();
791 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, "."));
792 arti.setNs(FQI.reverseDomain(fqi));
793 PropHolder loc = PropHolder.get(arti, "location.props");
794 PropHolder cred = PropHolder.get(arti,"cred.props");
795 PropHolder app= PropHolder.get(arti,"props");
796 for(String c : args) {
797 int idx = c.indexOf('=');
799 app.add(c.substring(0,idx), c.substring(idx+1));
802 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
804 for (String tag : LOC_TAGS) {
805 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
808 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
809 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
810 if(fqi!=null && fqi.equals(ssoAppID)) {
811 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
812 // only Ask for Password when starting scratch
813 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
814 char[] pwd = AAFSSO.cons.readPassword("Password for %s: ", fqi);
816 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
820 // load all properties that are already setup.
821 Map<String, String> aaf_urls = loadURLs(propAccess);
822 for(Entry<String, String> es : aaf_urls.entrySet()) {
823 app.add(es.getKey(), es.getValue());
826 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
827 app.add(Config.AAF_ENV,propAccess, "DEV");
828 String release = propAccess.getProperty(Config.AAF_RELEASE);
830 app.add(Config.AAF_RELEASE, release);
832 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
833 String key = aaf_loc_prop.getKey().toString();
834 if(key.startsWith("aaf_locator")) {
835 app.add(key, aaf_loc_prop.getValue().toString());
839 app.add(Config.AAF_APPID, fqi);
841 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
842 System.out.println("Passed in Truststore is " + cts);
844 File origTruststore = new File(cts);
845 File newTruststore = new File(app.getDir(),origTruststore.getName());
846 if(!newTruststore.exists()) {
847 if (!origTruststore.exists()) {
848 // Try same directory as cadi_prop_files
849 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
851 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
852 File fcpf = new File(f);
854 int lastSep = cts.lastIndexOf(File.pathSeparator);
855 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
856 if (origTruststore.exists()) {
861 if (!origTruststore.exists()) {
862 throw new CadiException(cts + " does not exist");
867 if (!newTruststore.exists() && origTruststore.exists()) {
868 Files.copy(origTruststore.toPath(), newTruststore.toPath());
872 System.out.println("New Truststore is " + newTruststore);
873 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
874 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
876 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
878 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
879 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
880 String f = propFiles[pfi];
881 System.out.format("Reading %s\n",f);
882 FileInputStream fis = new FileInputStream(f);
884 Properties props = new Properties();
886 for (Entry<Object, Object> prop : props.entrySet()) {
887 boolean lower = true;
888 String key = prop.getKey().toString();
889 if(LOC_TAGS.contains(key)) {
892 for(int i=0;lower && i<key.length();++i) {
893 if(Character.isUpperCase(key.charAt(i))) {
898 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
899 if(key.endsWith("_password")) {
900 ph.addEnc(key, prop.getValue().toString());
902 ph.add(key, prop.getValue().toString());
911 aafcon = aafcon(propAccess);
912 if (aafcon!=null) { // get Properties from Remote AAF
913 final String locator = getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
915 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
916 .read("/configure/"+fqi+"/aaf", configDF);
917 if (acf.get(TIMEOUT)) {
918 for (Props props : acf.value.getProps()) {
919 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
920 if(props.getTag().endsWith("_password")) {
921 ph.addEnc(props.getTag(), props.getValue());
923 ph.add(props.getTag(), props.getValue());
926 } else if (acf.code()==401){
927 trans.error().log("Bad Password sent to AAF");
928 } else if (acf.code()==404){
929 trans.error().log("This version of AAF does not support remote Properties");
931 trans.error().log(errMsg.toMsg(acf));
937 PropHolder.writeAll();
944 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
945 System.out.println("Validating Configuration...");
946 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
947 aafcon.best(new Retryable<Void>() {
949 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
950 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
951 if (fc.get(aafcon.timeout)) {
952 System.out.print("Success connecting to ");
953 System.out.println(client.getURI());
954 System.out.print(" Permissions for ");
955 System.out.println(aafcon.defID());
956 for (Perm p : fc.value.getPerm()) {
957 System.out.print('\t');
958 System.out.print(p.getType());
959 System.out.print('|');
960 System.out.print(p.getInstance());
961 System.out.print('|');
962 System.out.println(p.getAction());
965 System.err.println("Error: " + fc.code() + ' ' + fc.body());
973 * Check returns Error Codes, so that Scripts can know what to do
975 * 0 - Check Complete, nothing to do
977 * 2 - Error for specific Artifact - read check.msg
978 * 10 - Certificate Updated - check.msg is email content
986 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
988 String mechID = fqi(cmds);
989 String machine = machine(cmds);
991 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
994 Future<Artifacts> acf = aafcon.client(CM_VER)
995 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
996 if (acf.get(TIMEOUT)) {
997 // Have to wait for JDK 1.7 source...
998 //switch(artifact.getType()) {
999 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1000 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1002 String id = aafcon.defID();
1003 GregorianCalendar now = new GregorianCalendar();
1004 for (Artifact a : acf.value.getArtifact()) {
1005 if (id.equals(a.getMechid())) {
1006 File dir = new File(a.getDir());
1007 Properties props = new Properties();
1008 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1018 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1019 !(f=new File(prop)).exists()) {
1020 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1021 a.getMechid(), a.getMachine());
1023 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1024 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1025 if (ksf==null || ksps == null) {
1026 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1027 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1029 Symm symm = ArtifactDir.getSymm(f);
1031 KeyStore ks = KeyStore.getInstance("JKS");
1033 fis = new FileInputStream(ksf);
1035 ks.load(fis,symm.depass(ksps).toCharArray());
1039 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1043 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1044 a.getMechid(), a.getMachine(), ksf);
1045 trans.error().log(msg);
1048 GregorianCalendar renew = new GregorianCalendar();
1049 renew.setTime(cert.getNotAfter());
1050 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1051 if (renew.after(now)) {
1052 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",
1053 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1054 trans.info().log(msg);
1057 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1058 a.getMechid(), a.getMachine(),cert.getNotAfter());
1059 cmds.offerLast(mechID);
1060 cmds.offerLast(machine);
1061 if (placeCerts(trans,aafcon,cmds)) {
1062 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1063 a.getMechid(), a.getMachine());
1064 exitCode = 10; // Refreshed
1066 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1067 a.getMechid(), a.getMachine());
1068 exitCode = 1; // Error Renewing
1073 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1075 fos.write(msg.getBytes());
1087 trans.error().log(errMsg.toMsg(acf));