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 HASHES = "################################################################";
90 private static final String PRINT = "print";
91 private static final String FILE = "file";
92 public static final String PKCS12 = "pkcs12";
93 public static final String JKS = "jks";
94 private static final String SCRIPT="script";
96 private static final String CM_VER = "1.0";
97 public static final int PASS_SIZE = 24;
98 private static int TIMEOUT;
100 private static RosettaDF<CertificateRequest> reqDF;
101 private static RosettaDF<CertInfo> certDF;
102 private static RosettaDF<Artifacts> artifactsDF;
103 private static RosettaDF<Configuration> configDF;
104 private static RosettaDF<Perms> permDF;
105 private static ErrMessage errMsg;
106 private static Map<String,PlaceArtifact> placeArtifact;
107 private static RosettaEnv env;
109 private static boolean doExit;
110 private static AAFCon<?> aafcon;
112 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
114 Config.AAF_APPID, Config.AAF_APPPASS,
115 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
116 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
117 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
119 private static List<String> LOC_TAGS = Arrays.asList(new String[] {
120 Config.CADI_LATITUDE, Config.CADI_LONGITUDE
122 // Note: This is set by loadURLs. Use that function as singleton, not directly.
123 private static Map<String,String> aaf_urls = null;
126 public static void main(String[] args) {
129 if (args.length>0 && "cadi".equals(args[0])) {
130 String[] newArgs = new String[args.length-1];
131 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
132 if (newArgs.length==0) {
133 System.out.println(HASHES);
134 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
135 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
136 System.out.println(HASHES);
138 CmdLine.main(newArgs);
144 if (args.length>1 && args[0].equals("validate") ) {
145 int idx = args[1].indexOf('=');
147 access = new PropAccess(
148 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
150 (idx<0?args[1]:args[1].substring(idx+1)));
152 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
154 public Properties process(String[] args, Properties props) {
156 if (!args[0].equals("keypairgen")) {
157 props.put(Config.AAF_APPID, args[1]);
163 access = aafsso.access();
166 if (aafsso!=null && aafsso.loginOnly()) {
167 aafsso.setLogDefault();
169 System.out.println("AAF SSO information created in ~/.aaf");
171 env = new RosettaEnv(access.getProperties());
172 Deque<String> cmds = new ArrayDeque<String>();
173 for (String p : args) {
175 if ("-noexit".equalsIgnoreCase(p)) {
177 } else if ((eq=p.indexOf('=')) < 0) {
180 access.setProperty(p.substring(0,eq), p.substring(eq+1));
184 if (cmds.size()==0) {
186 aafsso.setLogDefault();
188 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
189 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
190 System.out.println(" create <FQI> [<machine>]");
191 System.out.println(" read <FQI> [<machine>]");
192 System.out.println(" update <FQI> [<machine>]");
193 System.out.println(" delete <FQI> [<machine>]");
194 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
195 System.out.println(" place <FQI> [<machine>]");
196 System.out.println(" showpass <FQI> [<machine>]");
197 System.out.println(" check <FQI> [<machine>]");
198 System.out.println(" keypairgen <FQI>");
199 System.out.println(" config <FQI>");
200 System.out.println(" validate <NS>.props>");
201 System.out.println(" --- Additional Tool Access ---");
202 System.out.println(" ** Type with no params for Tool Help");
203 System.out.println(" ** If using with Agent, preface with \"cadi\"");
204 System.out.println(" cadi <cadi tool params, see -?>");
211 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
213 reqDF = env.newDataFactory(CertificateRequest.class);
214 artifactsDF = env.newDataFactory(Artifacts.class);
215 certDF = env.newDataFactory(CertInfo.class);
216 configDF = env.newDataFactory(Configuration.class);
217 permDF = env.newDataFactory(Perms.class);
218 errMsg = new ErrMessage(env);
220 placeArtifact = new HashMap<>();
221 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
222 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
223 placeArtifact.put(FILE, new PlaceArtifactInFiles());
224 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
225 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
227 Trans trans = env.newTrans();
229 if ((token=access.getProperty("oauth_token"))!=null) {
230 trans.setProperty("oauth_token", token);
234 // show Std out again
235 aafsso.setLogDefault();
236 aafsso.setStdErrDefault();
238 /*urls=*/loadURLs(access);
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"}) {
318 case "aaf": tag = Config.AAF_URL; break;
319 case "locate":tag = Config.AAF_LOCATE_URL; break;
320 case "oauth": tag = Config.AAF_URL_OAUTH; break;
321 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
322 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
323 case "cm": tag = Config.AAF_URL_CM; break;
324 case "gui": tag = Config.AAF_URL_GUI; break;
325 case "fs": tag = Config.AAF_URL_FS; break;
326 case "hello": tag = Config.AAF_URL_HELLO; break;
328 tag = "aaf_url_" + u;
331 if((value=access.getProperty(tag,null))==null) {
332 String proto = "fs".equals(u)?"http://":"https://";
334 if("locate".equals(u)) {
335 lhost=rph.default_fqdn;
337 lhost=Config.AAF_LOCATE_URL_TAG;
339 value = rph.replacements("Agent:loadURLs",
340 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
353 public static void fillMissing(PropAccess access, Map<String, String> map) {
354 for(Entry<String, String> es : map.entrySet()) {
355 if(access.getProperty(es.getKey())==null) {
356 access.setProperty(es.getKey(),es.getValue());
361 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
363 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
368 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
370 if ((value=pa.getProperty(tag))==null) {
372 value = new String(AAFSSO.cons.readPassword(prompt, def));
374 value = AAFSSO.cons.readLine(prompt,def).trim();
377 if (value.length()>0) {
378 pa.setProperty(tag,value);
379 env.setProperty(tag,value);
380 } else if (def.length==1) {
381 value=def[0].toString();
382 pa.setProperty(tag,value);
383 env.setProperty(tag,value);
390 private static String fqi(Deque<String> cmds) {
392 String alias = env.getProperty(Config.CADI_ALIAS);
393 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
395 return cmds.removeFirst();
398 private static String machine(Deque<String> cmds) throws UnknownHostException {
400 return cmds.removeFirst();
402 String mach = env.getProperty(Config.HOSTNAME);
403 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
407 private static String[] machines(Deque<String> cmds) {
410 machines = cmds.removeFirst();
412 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
414 return Split.split(',', machines);
417 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
418 final String mechID = fqi(cmds);
419 final String machine = machine(cmds);
421 Artifacts artifacts = new Artifacts();
422 Artifact arti = new Artifact();
423 artifacts.getArtifact().add(arti);
424 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
425 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
426 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
428 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
429 for (String s : Split.splitTrim(',', resp)) {
430 arti.getType().add(s);
433 if (!resp.contains(SCRIPT)) {
434 arti.getType().add(SCRIPT);
437 // Note: Sponsor is set on Creation by CM
438 String configRootName = FQI.reverseDomain(arti.getMechid());
439 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
440 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
441 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
442 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
443 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
445 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
447 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
448 if (future.get(TIMEOUT)) {
449 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
451 trans.error().printf("Call to AAF Certman failed, %s",
452 errMsg.toMsg(future));
459 private static String toNotification(String notification) {
460 if (notification==null) {
462 } else if (notification.length()>0) {
463 if (notification.indexOf(':')<0) {
464 notification = "mailto:" + notification;
471 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
472 String mechID = fqi(cmds);
473 String machine = machine(cmds);
475 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
477 Future<Artifacts> future = aafcon.client(CM_VER)
478 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
480 if (future.get(TIMEOUT)) {
481 boolean printed = false;
482 for (Artifact a : future.value.getArtifact()) {
483 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
484 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
485 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
486 AAFSSO.cons.printf("CA: %s\n",a.getCa());
487 StringBuilder sb = new StringBuilder();
488 boolean first = true;
489 for (String t : a.getType()) {
490 if (first) {first=false;}
491 else{sb.append(',');}
494 AAFSSO.cons.printf("Types: %s\n",sb);
495 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
496 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
497 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
498 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
499 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
503 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
506 trans.error().log(errMsg.toMsg(future));
513 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
514 String mechID = fqi(cmds);
515 String machine = machine(cmds);
516 String[] newmachs = machines(cmds);
517 if (machine==null || newmachs == null) {
518 trans.error().log("No machines listed to copy to");
520 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
522 Future<Artifacts> future = aafcon.client(CM_VER)
523 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
525 if (future.get(TIMEOUT)) {
526 boolean printed = false;
527 for (Artifact a : future.value.getArtifact()) {
528 for (String m : newmachs) {
530 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
531 if (fup.get(TIMEOUT)) {
532 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
534 trans.error().printf("Call to AAF Certman failed, %s",
542 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
545 trans.error().log(errMsg.toMsg(future));
553 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
554 String mechID = fqi(cmds);
555 String machine = machine(cmds);
557 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
559 Future<Artifacts> fread = aafcon.client(CM_VER)
560 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
562 if (fread.get(TIMEOUT)) {
563 Artifacts artifacts = new Artifacts();
564 for (Artifact a : fread.value.getArtifact()) {
565 Artifact arti = new Artifact();
566 artifacts.getArtifact().add(arti);
568 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
569 arti.setMechid(a.getMechid());
570 arti.setMachine(a.getMachine());
571 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
572 StringBuilder sb = new StringBuilder();
573 boolean first = true;
574 for (String t : a.getType()) {
575 if (first) {first=false;}
576 else{sb.append(',');}
580 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
581 for (String s : Split.splitTrim(',', resp)) {
582 arti.getType().add(s);
585 if (!resp.contains(SCRIPT)) {
586 arti.getType().add(SCRIPT);
589 // Note: Sponsor is set on Creation by CM
590 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
591 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
592 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
593 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
594 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
597 if (artifacts.getArtifact().size()==0) {
598 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
600 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
601 if (fup.get(TIMEOUT)) {
602 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
604 trans.error().printf("Call to AAF Certman failed, %s",
609 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
610 errMsg.toMsg(fread),mechID,machine);
617 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
618 String mechid = fqi(cmds);
619 String machine = machine(cmds);
621 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
623 Future<Void> future = aafcon.client(CM_VER)
624 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
626 if (future.get(TIMEOUT)) {
627 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
629 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
630 errMsg.toMsg(future),mechid,machine);
639 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
641 String mechID = fqi(cmds);
642 String machine = machine(cmds);
643 String[] fqdns = Split.split(':', machine);
645 if (fqdns.length>1) {
652 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
654 Future<Artifacts> acf = aafcon.client(CM_VER)
655 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
656 if (acf.get(TIMEOUT)) {
657 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
658 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
660 for (Artifact a : acf.value.getArtifact()) {
661 String osID = System.getProperty("user.name");
662 if (a.getOsUser().equals(osID)) {
663 CertificateRequest cr = new CertificateRequest();
664 cr.setMechid(a.getMechid());
665 cr.setSponsor(a.getSponsor());
666 for (int i=0;i<fqdns.length;++i) {
667 cr.getFqdns().add(fqdns[i]);
669 Future<String> f = aafcon.client(CM_VER)
670 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
671 if (f.get(TIMEOUT)) {
672 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
673 for (String type : a.getType()) {
674 PlaceArtifact pa = placeArtifact.get(type);
676 if (rv = pa.place(trans, capi, a,machine)) {
681 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
683 trans.error().log(errMsg.toMsg(f));
686 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
690 PropHolder.writeAll();
692 trans.error().log(errMsg.toMsg(acf));
700 private static void notifyPlaced(Artifact a, boolean rv) {
703 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
704 String mechID = fqi(cmds);
705 String machine = machine(cmds);
707 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
709 Future<Artifacts> acf = aafcon.client(CM_VER)
710 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
711 if (acf.get(TIMEOUT)) {
712 // Have to wait for JDK 1.7 source...
713 //switch(artifact.getType()) {
714 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
715 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
717 String id = aafcon.defID();
719 for (Artifact a : acf.value.getArtifact()) {
720 allowed = id!=null && (id.equals(a.getSponsor()) ||
721 (id.equals(a.getMechid())
722 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
724 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
725 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
726 if (pf.get(TIMEOUT)) {
729 trans.error().log(errMsg.toMsg(pf));
733 File dir = new File(a.getDir());
734 Properties props = new Properties();
735 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
738 File chalFile = new File(dir,a.getNs()+".chal");
739 if(chalFile.exists()) {
741 fis = new FileInputStream(chalFile);
748 File f = new File(dir,a.getNs()+".keyfile");
750 Symm symm = ArtifactDir.getSymm(f);
752 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
753 Entry<Object,Object> en = iter.next();
754 if (en.getValue().toString().startsWith("enc:")) {
755 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
759 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
760 f.getAbsolutePath(),a.getMechid(), a.getMachine());
766 trans.error().log(errMsg.toMsg(acf));
774 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
775 final String fqi = fqi(cmds);
776 final String ns = FQI.reverseDomain(fqi);
777 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
778 File f = new File(dir,ns+".key");
781 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
782 if (!"Y".equalsIgnoreCase(line)) {
783 System.out.println("Canceling...");
788 KeyPair kp = Factory.generateKeyPair(trans);
789 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
790 System.out.printf("Wrote %s\n", f.getCanonicalFile());
792 f=new File(dir,ns+".pubkey");
793 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
794 System.out.printf("Wrote %s\n", f.getCanonicalFile());
797 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
798 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
800 final String fqi = fqi(cmds);
801 Artifact arti = new Artifact();
802 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, "."));
803 arti.setNs(FQI.reverseDomain(fqi));
804 PropHolder loc = PropHolder.get(arti, "location.props");
805 PropHolder cred = PropHolder.get(arti,"cred.props");
806 PropHolder app= PropHolder.get(arti,"props");
807 for(String c : args) {
808 int idx = c.indexOf('=');
810 app.add(c.substring(0,idx), c.substring(idx+1));
813 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
815 for (String tag : LOC_TAGS) {
816 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
819 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
820 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
821 if(fqi!=null && fqi.equals(ssoAppID)) {
822 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
823 // only Ask for Password when starting scratch
824 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
825 char[] pwd = AAFSSO.cons.readPassword("Password for %s: ", fqi);
827 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
831 // load all properties that are already setup.
832 Map<String, String> aaf_urls = loadURLs(propAccess);
833 for(Entry<String, String> es : aaf_urls.entrySet()) {
834 app.add(es.getKey(), es.getValue());
837 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
838 app.add(Config.AAF_ENV,propAccess, "DEV");
839 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
841 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
844 app.add(Config.AAF_DEPLOYED_VERSION, release);
846 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
847 String key = aaf_loc_prop.getKey().toString();
848 if(key.startsWith("aaf_locator")) {
849 app.add(key, aaf_loc_prop.getValue().toString());
853 app.add(Config.AAF_APPID, fqi);
855 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
856 System.out.println("Passed in Truststore is " + cts);
858 File origTruststore = new File(cts);
859 File newTruststore = new File(app.getDir(),origTruststore.getName());
860 if(!newTruststore.exists()) {
861 if (!origTruststore.exists()) {
862 // Try same directory as cadi_prop_files
863 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
865 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
866 File fcpf = new File(f);
868 int lastSep = cts.lastIndexOf(File.pathSeparator);
869 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
870 if (origTruststore.exists()) {
875 if (!origTruststore.exists()) {
876 throw new CadiException(cts + " does not exist");
881 if (!newTruststore.exists() && origTruststore.exists()) {
882 Files.copy(origTruststore.toPath(), newTruststore.toPath());
886 System.out.println("New Truststore is " + newTruststore);
887 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
888 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
890 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
892 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
893 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
894 String f = propFiles[pfi];
895 System.out.format("Reading %s\n",f);
896 FileInputStream fis = new FileInputStream(f);
898 Properties props = new Properties();
900 for (Entry<Object, Object> prop : props.entrySet()) {
901 boolean lower = true;
902 String key = prop.getKey().toString();
903 if(LOC_TAGS.contains(key)) {
906 for(int i=0;lower && i<key.length();++i) {
907 if(Character.isUpperCase(key.charAt(i))) {
912 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
913 if(key.endsWith("_password")) {
914 ph.addEnc(key, prop.getValue().toString());
916 ph.add(key, prop.getValue().toString());
925 aafcon = aafcon(propAccess);
926 if (aafcon!=null) { // get Properties from Remote AAF
927 for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
928 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
929 if(props.getTag().endsWith("_password")) {
930 ph.addEnc(props.getTag(), props.getValue());
932 ph.add(props.getTag(), props.getValue());
940 PropHolder.writeAll();
946 public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, URISyntaxException {
947 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
948 .read("/configure/"+fqi+"/aaf", configDF);
949 if (acf.get(TIMEOUT)) {
950 return acf.value.getProps();
951 } else if (acf.code()==401){
952 trans.error().log("Bad Password sent to AAF");
953 } else if (acf.code()==404){
954 trans.error().log("This version of AAF does not support remote Properties");
956 trans.error().log(errMsg.toMsg(acf));
958 return new ArrayList<>();
961 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
962 System.out.println("Validating Configuration...");
963 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
964 aafcon.best(new Retryable<Void>() {
966 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
967 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
968 if (fc.get(aafcon.timeout)) {
969 System.out.print("Success connecting to ");
970 System.out.println(client.getURI());
971 System.out.print(" Permissions for ");
972 System.out.println(aafcon.defID());
973 for (Perm p : fc.value.getPerm()) {
974 System.out.print('\t');
975 System.out.print(p.getType());
976 System.out.print('|');
977 System.out.print(p.getInstance());
978 System.out.print('|');
979 System.out.println(p.getAction());
982 System.err.println("Error: " + fc.code() + ' ' + fc.body());
990 * Check returns Error Codes, so that Scripts can know what to do
992 * 0 - Check Complete, nothing to do
994 * 2 - Error for specific Artifact - read check.msg
995 * 10 - Certificate Updated - check.msg is email content
1003 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1005 String mechID = fqi(cmds);
1006 String machine = machine(cmds);
1008 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
1011 Future<Artifacts> acf = aafcon.client(CM_VER)
1012 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1013 if (acf.get(TIMEOUT)) {
1014 // Have to wait for JDK 1.7 source...
1015 //switch(artifact.getType()) {
1016 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1017 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1019 String id = aafcon.defID();
1020 GregorianCalendar now = new GregorianCalendar();
1021 for (Artifact a : acf.value.getArtifact()) {
1022 if (id.equals(a.getMechid())) {
1023 File dir = new File(a.getDir());
1024 Properties props = new Properties();
1025 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1035 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1036 !(f=new File(prop)).exists()) {
1037 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1038 a.getMechid(), a.getMachine());
1040 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1041 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1042 if (ksf==null || ksps == null) {
1043 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1044 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1046 Symm symm = ArtifactDir.getSymm(f);
1048 KeyStore ks = KeyStore.getInstance("JKS");
1050 fis = new FileInputStream(ksf);
1052 ks.load(fis,symm.depass(ksps).toCharArray());
1056 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1060 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1061 a.getMechid(), a.getMachine(), ksf);
1062 trans.error().log(msg);
1065 GregorianCalendar renew = new GregorianCalendar();
1066 renew.setTime(cert.getNotAfter());
1067 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1068 if (renew.after(now)) {
1069 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",
1070 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1071 trans.info().log(msg);
1074 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1075 a.getMechid(), a.getMachine(),cert.getNotAfter());
1076 cmds.offerLast(mechID);
1077 cmds.offerLast(machine);
1078 if (placeCerts(trans,aafcon,cmds)) {
1079 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1080 a.getMechid(), a.getMachine());
1081 exitCode = 10; // Refreshed
1083 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1084 a.getMechid(), a.getMachine());
1085 exitCode = 1; // Error Renewing
1090 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1092 fos.write(msg.getBytes());
1104 trans.error().log(errMsg.toMsg(acf));