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.Access.Level;
54 import org.onap.aaf.cadi.aaf.client.ErrMessage;
55 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
56 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
57 import org.onap.aaf.cadi.client.Future;
58 import org.onap.aaf.cadi.client.Rcli;
59 import org.onap.aaf.cadi.client.Retryable;
60 import org.onap.aaf.cadi.config.Config;
61 import org.onap.aaf.cadi.config.RegistrationPropHolder;
62 import org.onap.aaf.cadi.config.SecurityInfoC;
63 import org.onap.aaf.cadi.http.HBasicAuthSS;
64 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
65 import org.onap.aaf.cadi.sso.AAFSSO;
66 import org.onap.aaf.cadi.util.Chmod;
67 import org.onap.aaf.cadi.util.FQI;
68 import org.onap.aaf.misc.env.APIException;
69 import org.onap.aaf.misc.env.Data.TYPE;
70 import org.onap.aaf.misc.env.Env;
71 import org.onap.aaf.misc.env.TimeTaken;
72 import org.onap.aaf.misc.env.Trans;
73 import org.onap.aaf.misc.env.util.Chrono;
74 import org.onap.aaf.misc.env.util.Split;
75 import org.onap.aaf.misc.rosetta.env.RosettaDF;
76 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
79 import aaf.v2_0.Perms;
80 import certman.v1_0.Artifacts;
81 import certman.v1_0.Artifacts.Artifact;
82 import certman.v1_0.CertInfo;
83 import certman.v1_0.CertificateRequest;
84 import locate.v1_1.Configuration;
85 import locate.v1_1.Configuration.Props;
88 private static final String HASHES = "################################################################";
89 private static final String PRINT = "print";
90 private static final String FILE = "file";
91 public static final String PKCS12 = "pkcs12";
92 public static final String JKS = "jks";
93 private static final String SCRIPT="script";
95 private static final String CM_VER = "1.0";
96 public static final int PASS_SIZE = 24;
97 private static int TIMEOUT;
99 private static RosettaDF<CertificateRequest> reqDF;
100 private static RosettaDF<CertInfo> certDF;
101 private static RosettaDF<Artifacts> artifactsDF;
102 private static RosettaDF<Configuration> configDF;
103 private static RosettaDF<Perms> permDF;
104 private static ErrMessage errMsg;
105 private static Map<String,PlaceArtifact> placeArtifact;
106 private static RosettaEnv env;
108 private static boolean doExit;
109 private static AAFCon<?> aafcon;
111 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
113 Config.AAF_APPID, Config.AAF_APPPASS,
114 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
115 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
116 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
118 private static List<String> LOC_TAGS = Arrays.asList(new String[] {
119 Config.CADI_LATITUDE, Config.CADI_LONGITUDE
121 // Note: This is set by loadURLs. Use that function as singleton, not directly.
122 private static Map<String,String> aaf_urls = null;
125 public static void main(String[] args) {
128 if (args.length>0 && "cadi".equals(args[0])) {
129 String[] newArgs = new String[args.length-1];
130 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
131 if (newArgs.length==0) {
132 System.out.println(HASHES);
133 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
134 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
135 System.out.println(HASHES);
137 CmdLine.main(newArgs);
143 if (args.length>1 && args[0].equals("validate") ) {
144 int idx = args[1].indexOf('=');
146 access = new PropAccess(
147 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
149 (idx<0?args[1]:args[1].substring(idx+1)));
151 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
153 public Properties process(String[] args, Properties props) {
155 if (!args[0].equals("keypairgen")) {
156 props.put(Config.AAF_APPID, args[1]);
162 access = aafsso.access();
165 if (aafsso!=null && aafsso.loginOnly()) {
166 aafsso.setLogDefault();
168 System.out.println("AAF SSO information created in ~/.aaf");
170 env = new RosettaEnv(access.getProperties());
171 Deque<String> cmds = new ArrayDeque<String>();
172 for (String p : args) {
174 if ("-noexit".equalsIgnoreCase(p)) {
176 } else if ((eq=p.indexOf('=')) < 0) {
179 access.setProperty(p.substring(0,eq), p.substring(eq+1));
183 if (cmds.size()==0) {
185 aafsso.setLogDefault();
187 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
188 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
189 System.out.println(" create <FQI> [<machine>]");
190 System.out.println(" read <FQI> [<machine>]");
191 System.out.println(" update <FQI> [<machine>]");
192 System.out.println(" delete <FQI> [<machine>]");
193 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
194 System.out.println(" place <FQI> [<machine>]");
195 System.out.println(" showpass <FQI> [<machine>]");
196 System.out.println(" check <FQI> [<machine>]");
197 System.out.println(" keypairgen <FQI>");
198 System.out.println(" config <FQI>");
199 System.out.println(" validate <NS>.props>");
200 System.out.println(" --- Additional Tool Access ---");
201 System.out.println(" ** Type with no params for Tool Help");
202 System.out.println(" ** If using with Agent, preface with \"cadi\"");
203 System.out.println(" cadi <cadi tool params, see -?>");
210 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
212 reqDF = env.newDataFactory(CertificateRequest.class);
213 artifactsDF = env.newDataFactory(Artifacts.class);
214 certDF = env.newDataFactory(CertInfo.class);
215 configDF = env.newDataFactory(Configuration.class);
216 permDF = env.newDataFactory(Perms.class);
217 errMsg = new ErrMessage(env);
219 placeArtifact = new HashMap<>();
220 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
221 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
222 placeArtifact.put(FILE, new PlaceArtifactInFiles());
223 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
224 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
226 Trans trans = env.newTrans();
228 if ((token=access.getProperty("oauth_token"))!=null) {
229 trans.setProperty("oauth_token", token);
233 // show Std out again
234 aafsso.setLogDefault();
235 aafsso.setStdErrDefault();
237 Map<String, String> aaf_urls = loadURLs(access);
238 aafsso.addProp(Config.AAF_URL_CM, aaf_urls.get(Config.AAF_URL_CM));
244 String cmd = cmds.removeFirst();
247 placeCerts(trans,aafcon(access),cmds);
250 createArtifact(trans, aafcon(access),cmds);
253 readArtifact(trans, aafcon(access), cmds);
256 copyArtifact(trans, aafcon(access), cmds);
259 updateArtifact(trans, aafcon(access), cmds);
262 deleteArtifact(trans, aafcon(access), cmds);
265 showPass(trans, aafcon(access), cmds);
268 keypairGen(trans, access, cmds);
271 config(trans,access,args,cmds);
278 exitCode = check(trans,aafcon(access),cmds);
279 } catch (Exception e) {
285 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
288 StringBuilder sb = new StringBuilder();
289 trans.auditTrail(4, sb, Trans.REMOTE);
291 trans.info().log("Trans Info\n",sb);
298 } catch (Exception e) {
302 if (exitCode != 0 && doExit) {
303 System.exit(exitCode);
307 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
309 Map<String,String> rv = new HashMap<>();
310 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
311 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
312 dot_le=dot_le==null?"":'.'+dot_le;
313 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
314 for(String u : new String[] {"aaf","locate","oauth","cm","gui","fs","hello","token","introspect"}) {
315 String proto = "fs".equals(u)?"http://":"https://";
317 if("locate".equals(u)) {
318 lhost=rph.default_fqdn;
320 lhost=Config.AAF_LOCATE_URL_TAG;
322 String value = rph.replacements("Agent:loadURLs",
323 proto + lhost + "/AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
326 case "aaf": rv.put(Config.AAF_URL, value); break;
327 case "locate": rv.put(Config.AAF_LOCATE_URL, value); break;
328 case "token": rv.put(Config.AAF_OAUTH2_TOKEN_URL, value); break;
329 case "introspect": rv.put(Config.AAF_OAUTH2_INTROSPECT_URL, value); break;
330 case "cm": rv.put(Config.AAF_URL_CM, value); break;
331 case "gui": rv.put(Config.AAF_URL_GUI, value); break;
332 case "fs": rv.put(Config.AAF_URL_FS, value); break;
333 case "hello": rv.put(Config.AAF_URL_HELLO, value); break;
335 rv.put("aaf_url_" + u, value);
343 public static void fillMissing(PropAccess access, Map<String, String> map) {
344 for(Entry<String, String> es : map.entrySet()) {
345 if(access.getProperty(es.getKey())==null) {
346 access.setProperty(es.getKey(),es.getValue());
351 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
353 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
358 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
360 if ((value=pa.getProperty(tag))==null) {
362 value = new String(AAFSSO.cons.readPassword(prompt, def));
364 value = AAFSSO.cons.readLine(prompt,def).trim();
367 if (value.length()>0) {
368 pa.setProperty(tag,value);
369 env.setProperty(tag,value);
370 } else if (def.length==1) {
371 value=def[0].toString();
372 pa.setProperty(tag,value);
373 env.setProperty(tag,value);
380 private static String fqi(Deque<String> cmds) {
382 String alias = env.getProperty(Config.CADI_ALIAS);
383 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
385 return cmds.removeFirst();
388 private static String machine(Deque<String> cmds) throws UnknownHostException {
390 return cmds.removeFirst();
392 String mach = env.getProperty(Config.HOSTNAME);
393 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
397 private static String[] machines(Deque<String> cmds) {
400 machines = cmds.removeFirst();
402 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
404 return Split.split(',', machines);
407 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
408 final String mechID = fqi(cmds);
409 final String machine = machine(cmds);
411 Artifacts artifacts = new Artifacts();
412 Artifact arti = new Artifact();
413 artifacts.getArtifact().add(arti);
414 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
415 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
416 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
418 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
419 for (String s : Split.splitTrim(',', resp)) {
420 arti.getType().add(s);
423 if (!resp.contains(SCRIPT)) {
424 arti.getType().add(SCRIPT);
427 // Note: Sponsor is set on Creation by CM
428 String configRootName = FQI.reverseDomain(arti.getMechid());
429 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
430 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
431 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
432 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
433 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
435 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
437 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
438 if (future.get(TIMEOUT)) {
439 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
441 trans.error().printf("Call to AAF Certman failed, %s",
442 errMsg.toMsg(future));
449 private static String toNotification(String notification) {
450 if (notification==null) {
452 } else if (notification.length()>0) {
453 if (notification.indexOf(':')<0) {
454 notification = "mailto:" + notification;
461 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
462 String mechID = fqi(cmds);
463 String machine = machine(cmds);
465 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
467 Future<Artifacts> future = aafcon.client(CM_VER)
468 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
470 if (future.get(TIMEOUT)) {
471 boolean printed = false;
472 for (Artifact a : future.value.getArtifact()) {
473 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
474 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
475 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
476 AAFSSO.cons.printf("CA: %s\n",a.getCa());
477 StringBuilder sb = new StringBuilder();
478 boolean first = true;
479 for (String t : a.getType()) {
480 if (first) {first=false;}
481 else{sb.append(',');}
484 AAFSSO.cons.printf("Types: %s\n",sb);
485 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
486 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
487 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
488 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
489 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
493 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
496 trans.error().log(errMsg.toMsg(future));
503 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
504 String mechID = fqi(cmds);
505 String machine = machine(cmds);
506 String[] newmachs = machines(cmds);
507 if (machine==null || newmachs == null) {
508 trans.error().log("No machines listed to copy to");
510 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
512 Future<Artifacts> future = aafcon.client(CM_VER)
513 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
515 if (future.get(TIMEOUT)) {
516 boolean printed = false;
517 for (Artifact a : future.value.getArtifact()) {
518 for (String m : newmachs) {
520 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
521 if (fup.get(TIMEOUT)) {
522 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
524 trans.error().printf("Call to AAF Certman failed, %s",
532 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
535 trans.error().log(errMsg.toMsg(future));
543 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
544 String mechID = fqi(cmds);
545 String machine = machine(cmds);
547 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
549 Future<Artifacts> fread = aafcon.client(CM_VER)
550 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
552 if (fread.get(TIMEOUT)) {
553 Artifacts artifacts = new Artifacts();
554 for (Artifact a : fread.value.getArtifact()) {
555 Artifact arti = new Artifact();
556 artifacts.getArtifact().add(arti);
558 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
559 arti.setMechid(a.getMechid());
560 arti.setMachine(a.getMachine());
561 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
562 StringBuilder sb = new StringBuilder();
563 boolean first = true;
564 for (String t : a.getType()) {
565 if (first) {first=false;}
566 else{sb.append(',');}
570 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
571 for (String s : Split.splitTrim(',', resp)) {
572 arti.getType().add(s);
575 if (!resp.contains(SCRIPT)) {
576 arti.getType().add(SCRIPT);
579 // Note: Sponsor is set on Creation by CM
580 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
581 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
582 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
583 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
584 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
587 if (artifacts.getArtifact().size()==0) {
588 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
590 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
591 if (fup.get(TIMEOUT)) {
592 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
594 trans.error().printf("Call to AAF Certman failed, %s",
599 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
600 errMsg.toMsg(fread),mechID,machine);
607 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
608 String mechid = fqi(cmds);
609 String machine = machine(cmds);
611 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
613 Future<Void> future = aafcon.client(CM_VER)
614 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
616 if (future.get(TIMEOUT)) {
617 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
619 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
620 errMsg.toMsg(future),mechid,machine);
629 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
631 String mechID = fqi(cmds);
632 String machine = machine(cmds);
633 String[] fqdns = Split.split(':', machine);
635 if (fqdns.length>1) {
642 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
644 Future<Artifacts> acf = aafcon.client(CM_VER)
645 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
646 if (acf.get(TIMEOUT)) {
647 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
648 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
650 for (Artifact a : acf.value.getArtifact()) {
651 String osID = System.getProperty("user.name");
652 if (a.getOsUser().equals(osID)) {
653 CertificateRequest cr = new CertificateRequest();
654 cr.setMechid(a.getMechid());
655 cr.setSponsor(a.getSponsor());
656 for (int i=0;i<fqdns.length;++i) {
657 cr.getFqdns().add(fqdns[i]);
659 Future<String> f = aafcon.client(CM_VER)
660 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
661 if (f.get(TIMEOUT)) {
662 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
663 for (String type : a.getType()) {
664 PlaceArtifact pa = placeArtifact.get(type);
666 if (rv = pa.place(trans, capi, a,machine)) {
671 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
673 trans.error().log(errMsg.toMsg(f));
676 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
680 PropHolder.writeAll();
682 trans.error().log(errMsg.toMsg(acf));
690 private static void notifyPlaced(Artifact a, boolean rv) {
693 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
694 String mechID = fqi(cmds);
695 String machine = machine(cmds);
697 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
699 Future<Artifacts> acf = aafcon.client(CM_VER)
700 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
701 if (acf.get(TIMEOUT)) {
702 // Have to wait for JDK 1.7 source...
703 //switch(artifact.getType()) {
704 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
705 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
707 String id = aafcon.defID();
709 for (Artifact a : acf.value.getArtifact()) {
710 allowed = id!=null && (id.equals(a.getSponsor()) ||
711 (id.equals(a.getMechid())
712 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
714 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
715 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
716 if (pf.get(TIMEOUT)) {
719 trans.error().log(errMsg.toMsg(pf));
723 File dir = new File(a.getDir());
724 Properties props = new Properties();
725 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
728 File chalFile = new File(dir,a.getNs()+".chal");
729 if(chalFile.exists()) {
731 fis = new FileInputStream(chalFile);
738 File f = new File(dir,a.getNs()+".keyfile");
740 Symm symm = ArtifactDir.getSymm(f);
742 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
743 Entry<Object,Object> en = iter.next();
744 if (en.getValue().toString().startsWith("enc:")) {
745 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
749 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
750 f.getAbsolutePath(),a.getMechid(), a.getMachine());
756 trans.error().log(errMsg.toMsg(acf));
764 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
765 final String fqi = fqi(cmds);
766 final String ns = FQI.reverseDomain(fqi);
767 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
768 File f = new File(dir,ns+".key");
771 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
772 if (!"Y".equalsIgnoreCase(line)) {
773 System.out.println("Canceling...");
778 KeyPair kp = Factory.generateKeyPair(trans);
779 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
780 System.out.printf("Wrote %s\n", f.getCanonicalFile());
782 f=new File(dir,ns+".pubkey");
783 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
784 System.out.printf("Wrote %s\n", f.getCanonicalFile());
787 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
788 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
790 final String fqi = fqi(cmds);
791 Artifact arti = new Artifact();
792 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, "."));
793 arti.setNs(FQI.reverseDomain(fqi));
794 PropHolder loc = PropHolder.get(arti, "location.props");
795 PropHolder cred = PropHolder.get(arti,"cred.props");
796 PropHolder app= PropHolder.get(arti,"props");
797 for(String c : args) {
798 int idx = c.indexOf('=');
800 app.add(c.substring(0,idx), c.substring(idx+1));
803 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
805 for (String tag : LOC_TAGS) {
806 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
809 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
810 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
811 if(fqi.equals(ssoAppID)) {
812 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
813 // only Ask for Password when starting scratch
814 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
815 char[] pwd = AAFSSO.cons.readPassword("Password for %s: ", fqi);
817 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
821 // load all properties that are already setup.
822 Map<String, String> aaf_urls = loadURLs(propAccess);
823 for(Entry<String, String> es : aaf_urls.entrySet()) {
824 app.add(es.getKey(), es.getValue());
827 app.add(Config.AAF_LOCATE_URL, propAccess, null);
828 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
829 String key = aaf_loc_prop.getKey().toString();
830 if("aaf_env".equals(key) || key.startsWith("aaf_locator")) {
831 app.add(key, aaf_loc_prop.getValue().toString());
835 app.add(Config.AAF_APPID, fqi);
837 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
838 System.out.println("Passed in Truststore is " + cts);
840 File origTruststore = new File(cts);
841 File newTruststore = new File(app.getDir(),origTruststore.getName());
842 if(!newTruststore.exists()) {
843 if (!origTruststore.exists()) {
844 // Try same directory as cadi_prop_files
845 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
847 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
848 File fcpf = new File(f);
850 int lastSep = cts.lastIndexOf(File.pathSeparator);
851 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
852 if (origTruststore.exists()) {
857 if (!origTruststore.exists()) {
858 throw new CadiException(cts + " does not exist");
863 if (!newTruststore.exists() && origTruststore.exists()) {
864 Files.copy(origTruststore.toPath(), newTruststore.toPath());
868 System.out.println("New Truststore is " + newTruststore);
869 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
870 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
872 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
874 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
875 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
876 String f = propFiles[pfi];
877 System.out.format("Reading %s\n",f);
878 FileInputStream fis = new FileInputStream(f);
880 Properties props = new Properties();
882 for (Entry<Object, Object> prop : props.entrySet()) {
883 boolean lower = true;
884 String key = prop.getKey().toString();
885 if(LOC_TAGS.contains(key)) {
888 for(int i=0;lower && i<key.length();++i) {
889 if(Character.isUpperCase(key.charAt(i))) {
894 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
895 if(key.endsWith("_password")) {
896 ph.addEnc(key, prop.getValue().toString());
898 ph.add(key, prop.getValue().toString());
907 aafcon = aafcon(propAccess);
908 if (aafcon!=null) { // get Properties from Remote AAF
909 final String locator = getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
911 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
912 .read("/configure/"+fqi+"/aaf", configDF);
913 if (acf.get(TIMEOUT)) {
914 for (Props props : acf.value.getProps()) {
915 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
916 if(props.getTag().endsWith("_password")) {
917 ph.addEnc(props.getTag(), props.getValue());
919 ph.add(props.getTag(), props.getValue());
922 } else if (acf.code()==401){
923 trans.error().log("Bad Password sent to AAF");
924 } else if (acf.code()==404){
925 trans.error().log("This version of AAF does not support remote Properties");
927 trans.error().log(errMsg.toMsg(acf));
933 PropHolder.writeAll();
940 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
941 System.out.println("Validating Configuration...");
942 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
943 aafcon.best(new Retryable<Void>() {
945 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
946 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
947 if (fc.get(aafcon.timeout)) {
948 System.out.print("Success connecting to ");
949 System.out.println(client.getURI());
950 System.out.print(" Permissions for ");
951 System.out.println(aafcon.defID());
952 for (Perm p : fc.value.getPerm()) {
953 System.out.print('\t');
954 System.out.print(p.getType());
955 System.out.print('|');
956 System.out.print(p.getInstance());
957 System.out.print('|');
958 System.out.println(p.getAction());
961 System.err.println("Error: " + fc.code() + ' ' + fc.body());
969 * Check returns Error Codes, so that Scripts can know what to do
971 * 0 - Check Complete, nothing to do
973 * 2 - Error for specific Artifact - read check.msg
974 * 10 - Certificate Updated - check.msg is email content
982 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
984 String mechID = fqi(cmds);
985 String machine = machine(cmds);
987 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
990 Future<Artifacts> acf = aafcon.client(CM_VER)
991 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
992 if (acf.get(TIMEOUT)) {
993 // Have to wait for JDK 1.7 source...
994 //switch(artifact.getType()) {
995 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
996 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
998 String id = aafcon.defID();
999 GregorianCalendar now = new GregorianCalendar();
1000 for (Artifact a : acf.value.getArtifact()) {
1001 if (id.equals(a.getMechid())) {
1002 File dir = new File(a.getDir());
1003 Properties props = new Properties();
1004 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1014 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1015 !(f=new File(prop)).exists()) {
1016 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1017 a.getMechid(), a.getMachine());
1019 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1020 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1021 if (ksf==null || ksps == null) {
1022 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1023 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1025 Symm symm = ArtifactDir.getSymm(f);
1027 KeyStore ks = KeyStore.getInstance("JKS");
1029 fis = new FileInputStream(ksf);
1031 ks.load(fis,symm.depass(ksps).toCharArray());
1035 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1039 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1040 a.getMechid(), a.getMachine(), ksf);
1041 trans.error().log(msg);
1044 GregorianCalendar renew = new GregorianCalendar();
1045 renew.setTime(cert.getNotAfter());
1046 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1047 if (renew.after(now)) {
1048 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",
1049 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1050 trans.info().log(msg);
1053 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1054 a.getMechid(), a.getMachine(),cert.getNotAfter());
1055 cmds.offerLast(mechID);
1056 cmds.offerLast(machine);
1057 if (placeCerts(trans,aafcon,cmds)) {
1058 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1059 a.getMechid(), a.getMachine());
1060 exitCode = 10; // Refreshed
1062 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1063 a.getMechid(), a.getMachine());
1064 exitCode = 1; // Error Renewing
1069 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1071 fos.write(msg.getBytes());
1083 trans.error().log(errMsg.toMsg(acf));