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.ArrayList;
38 import java.util.Arrays;
39 import java.util.Deque;
40 import java.util.GregorianCalendar;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
45 import java.util.Map.Entry;
46 import java.util.Properties;
48 import org.onap.aaf.cadi.Access;
49 import org.onap.aaf.cadi.CadiException;
50 import org.onap.aaf.cadi.CmdLine;
51 import org.onap.aaf.cadi.LocatorException;
52 import org.onap.aaf.cadi.PropAccess;
53 import org.onap.aaf.cadi.Symm;
54 import org.onap.aaf.cadi.aaf.TestConnectivity;
55 import org.onap.aaf.cadi.aaf.client.ErrMessage;
56 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
57 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
58 import org.onap.aaf.cadi.client.Future;
59 import org.onap.aaf.cadi.client.Rcli;
60 import org.onap.aaf.cadi.client.Retryable;
61 import org.onap.aaf.cadi.config.Config;
62 import org.onap.aaf.cadi.config.RegistrationPropHolder;
63 import org.onap.aaf.cadi.config.SecurityInfoC;
64 import org.onap.aaf.cadi.http.HBasicAuthSS;
65 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
66 import org.onap.aaf.cadi.sso.AAFSSO;
67 import org.onap.aaf.cadi.util.Chmod;
68 import org.onap.aaf.cadi.util.FQI;
69 import org.onap.aaf.misc.env.APIException;
70 import org.onap.aaf.misc.env.Data.TYPE;
71 import org.onap.aaf.misc.env.Env;
72 import org.onap.aaf.misc.env.TimeTaken;
73 import org.onap.aaf.misc.env.Trans;
74 import org.onap.aaf.misc.env.util.Chrono;
75 import org.onap.aaf.misc.env.util.Split;
76 import org.onap.aaf.misc.rosetta.env.RosettaDF;
77 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
80 import aaf.v2_0.Perms;
81 import certman.v1_0.Artifacts;
82 import certman.v1_0.Artifacts.Artifact;
83 import certman.v1_0.CertInfo;
84 import certman.v1_0.CertificateRequest;
85 import locate.v1_1.Configuration;
86 import locate.v1_1.Configuration.Props;
89 private static final String AGENT_LOAD_URLS = "Agent:loadURLs";
90 private static final String HASHES = "################################################################";
91 private static final String PRINT = "print";
92 private static final String FILE = "file";
93 public static final String PKCS12 = "pkcs12";
94 public static final String JKS = "jks";
95 private static final String SCRIPT="script";
97 private static final String CM_VER = "1.0";
98 public static final int PASS_SIZE = 24;
99 private static int TIMEOUT;
101 private static RosettaDF<CertificateRequest> reqDF;
102 private static RosettaDF<CertInfo> certDF;
103 private static RosettaDF<Artifacts> artifactsDF;
104 private static RosettaDF<Configuration> configDF;
105 private static RosettaDF<Perms> permDF;
106 private static ErrMessage errMsg;
107 private static Map<String,PlaceArtifact> placeArtifact;
108 private static RosettaEnv env;
110 private static boolean doExit;
111 private static AAFCon<?> aafcon;
113 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
115 Config.AAF_APPID, Config.AAF_APPPASS,
116 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
117 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
118 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
120 private static List<String> LOC_TAGS = Arrays.asList(new String[] {
121 Config.CADI_LATITUDE, Config.CADI_LONGITUDE
123 // Note: This is set by loadURLs. Use that function as singleton, not directly.
124 private static Map<String,String> aaf_urls = null;
125 private static boolean configNoPasswd = false;
128 public static void main(String[] args) {
131 if (args.length>0 && "cadi".equals(args[0])) {
132 String[] newArgs = new String[args.length-1];
133 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
134 if (newArgs.length==0) {
135 System.out.println(HASHES);
136 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
137 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
138 System.out.println(HASHES);
140 CmdLine.main(newArgs);
141 } else if(args.length>0 && "connectivity".equals(args[0])) {
142 String[] newArgs = new String[args.length-1];
143 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
144 if(newArgs.length>0 && newArgs[0].indexOf('@')>=0) {
145 newArgs[0]=FQI.reverseDomain(newArgs[0])+".props";
147 TestConnectivity.main(newArgs);
151 PropAccess access=null;
153 String hasEtc = null;
154 for(String a : args) {
155 if(a.startsWith(Config.CADI_PROP_FILES)) {
156 access = new PropAccess(args);
158 } else if(a.startsWith(Config.CADI_ETCDIR)) {
159 int idx = a.indexOf('=');
160 if(idx>=0 && idx<a.length()) {
161 hasEtc = a.substring(idx+1);
163 } else if(a.equals("--nopasswd")) {
169 if(args.length>1 && args[1].contains("@")) {
170 String domain = FQI.reverseDomain(args[1]);
175 File etc = new File(hasEtc);
177 File nsprops = new File(etc,domain+".props");
178 if(nsprops.exists()) {
179 access = new PropAccess(new String[] {Config.CADI_PROP_FILES+'='+nsprops.getAbsolutePath()});
187 for(Entry<Object, Object> es : System.getProperties().entrySet()) {
188 if(Config.CADI_PROP_FILES.equals(es.getKey())) {
189 access = new PropAccess();
194 // When using Config file, check if Cred Exists, and if not, work with Deployer.
195 if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) {
196 // not enough credentials to use Props. Use AAFSSO
201 if (args.length>1 && args[0].equals("validate") ) {
202 int idx = args[1].indexOf('=');
204 access = new PropAccess(
205 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
207 (idx<0?args[1]:args[1].substring(idx+1)));
209 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
211 public Properties process(String[] args, Properties props) {
213 if (!args[0].equals("keypairgen")) {
214 props.put(Config.AAF_APPID, args[1]);
220 access = aafsso.access();
224 if (aafsso!=null && aafsso.loginOnly()) {
225 aafsso.setLogDefault();
227 System.out.println("AAF SSO information created in ~/.aaf");
229 env = new RosettaEnv(access.getProperties());
230 Deque<String> cmds = new ArrayDeque<String>();
231 for (String p : args) {
233 if ("-noexit".equalsIgnoreCase(p)) {
235 } else if ((eq=p.indexOf('=')) < 0) {
238 access.setProperty(p.substring(0,eq), p.substring(eq+1));
242 if (cmds.size()==0) {
244 aafsso.setLogDefault();
246 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
247 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
248 System.out.println(" create <FQI> [<machine>]");
249 System.out.println(" read <FQI> [<machine>]");
250 System.out.println(" update <FQI> [<machine>]");
251 System.out.println(" delete <FQI> [<machine>]");
252 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
253 System.out.println(" place <FQI> [<machine>[,<san>]*");
254 System.out.println(" showpass <FQI> [<machine>]");
255 System.out.println(" check <FQI> [<machine>]");
256 System.out.println(" keypairgen <FQI>");
257 System.out.println(" config <FQI> [--nopasswd]");
258 System.out.println(" validate <NS>.props>");
259 System.out.println(" connectivity <NS>.props>");
260 System.out.println(" --- Additional Tool Access ---");
261 System.out.println(" ** Type with no params for Tool Help");
262 System.out.println(" ** If using with Agent, preface with \"cadi\"");
263 System.out.println(" cadi <cadi tool params, see -?>");
270 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
272 reqDF = env.newDataFactory(CertificateRequest.class);
273 artifactsDF = env.newDataFactory(Artifacts.class);
274 certDF = env.newDataFactory(CertInfo.class);
275 configDF = env.newDataFactory(Configuration.class);
276 permDF = env.newDataFactory(Perms.class);
277 errMsg = new ErrMessage(env);
279 placeArtifact = new HashMap<>();
280 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
281 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
282 placeArtifact.put(FILE, new PlaceArtifactInFiles());
283 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
284 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
286 Trans trans = env.newTrans();
288 if ((token=access.getProperty("oauth_token"))!=null) {
289 trans.setProperty("oauth_token", token);
293 // show Std out again
294 aafsso.setLogDefault();
295 aafsso.setStdErrDefault();
297 /*urls=*/loadURLs(access);
303 String cmd = cmds.removeFirst();
306 placeCerts(trans,aafcon(access),cmds);
309 createArtifact(trans, aafcon(access),cmds);
312 readArtifact(trans, aafcon(access), cmds);
315 copyArtifact(trans, aafcon(access), cmds);
318 updateArtifact(trans, aafcon(access), cmds);
321 deleteArtifact(trans, aafcon(access), cmds);
324 showPass(trans, aafcon(access), cmds);
327 keypairGen(trans, access, cmds);
330 config(trans,access,args,cmds);
337 exitCode = check(trans,aafcon(access),cmds);
338 } catch (Exception e) {
344 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
347 StringBuilder sb = new StringBuilder();
348 trans.auditTrail(4, sb, Trans.REMOTE);
350 trans.info().log("Trans Info\n",sb);
357 } catch (Exception e) {
361 if (exitCode != 0 && doExit) {
362 System.exit(exitCode);
366 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
368 Map<String,String> rv = new HashMap<>();
369 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
370 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
371 dot_le=dot_le==null?"":'.'+dot_le;
372 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
373 for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) {
377 case "aaf": tag = Config.AAF_URL; break;
378 case "locate":tag = Config.AAF_LOCATE_URL; break;
379 case "oauth": tag = Config.AAF_URL_OAUTH; break;
380 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
381 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
382 case "cm": tag = Config.AAF_URL_CM; break;
383 case "gui": tag = Config.AAF_URL_GUI; break;
384 case "fs": tag = Config.AAF_URL_FS; break;
385 case "hello": tag = Config.AAF_URL_HELLO; break;
387 tag = "aaf_url_" + u;
390 if((value=access.getProperty(tag,null))==null) {
391 String proto = "fs".equals(u)?"http://":"https://";
393 if("locate".equals(u)) {
394 lhost=rph.default_fqdn;
396 lhost=Config.AAF_LOCATE_URL_TAG;
398 value = rph.replacements(AGENT_LOAD_URLS,
399 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
405 value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le);
414 public static void fillMissing(PropAccess access, Map<String, String> map) {
415 for(Entry<String, String> es : map.entrySet()) {
416 if(access.getProperty(es.getKey())==null) {
417 access.setProperty(es.getKey(),es.getValue());
422 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
424 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
429 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
431 if ((value=pa.getProperty(tag))==null) {
433 value = new String(AAFSSO.cons.readPassword(prompt, def));
435 value = AAFSSO.cons.readLine(prompt,def).trim();
438 if (value.length()>0) {
439 pa.setProperty(tag,value);
440 env.setProperty(tag,value);
441 } else if (def.length==1) {
442 value=def[0].toString();
443 pa.setProperty(tag,value);
444 env.setProperty(tag,value);
451 private static String fqi(Deque<String> cmds) {
453 String alias = env.getProperty(Config.CADI_ALIAS);
455 alias = env.getProperty(Config.AAF_APPID);
457 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
459 return cmds.removeFirst();
462 private static String machine(Deque<String> cmds) throws UnknownHostException {
464 return cmds.removeFirst();
466 String mach = env.getProperty(Config.HOSTNAME);
467 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
471 private static String[] machines(Deque<String> cmds) {
474 machines = cmds.removeFirst();
476 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
478 return Split.split(',', machines);
481 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
482 final String mechID = fqi(cmds);
483 final String machine = machine(cmds);
485 Artifacts artifacts = new Artifacts();
486 Artifact arti = new Artifact();
487 artifacts.getArtifact().add(arti);
488 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
489 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
490 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
492 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
493 for (String s : Split.splitTrim(',', resp)) {
494 arti.getType().add(s);
497 if (!resp.contains(SCRIPT)) {
498 arti.getType().add(SCRIPT);
501 // Note: Sponsor is set on Creation by CM
502 String configRootName = FQI.reverseDomain(arti.getMechid());
503 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
504 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
505 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
506 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
507 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
509 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
511 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
512 if (future.get(TIMEOUT)) {
513 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
515 trans.error().printf("Call to AAF Certman failed, %s",
516 errMsg.toMsg(future));
523 private static String toNotification(String notification) {
524 if (notification==null) {
526 } else if (notification.length()>0) {
527 if (notification.indexOf(':')<0) {
528 notification = "mailto:" + notification;
535 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
536 String mechID = fqi(cmds);
537 String machine = machine(cmds);
539 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
541 Future<Artifacts> future = aafcon.client(CM_VER)
542 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
544 if (future.get(TIMEOUT)) {
545 boolean printed = false;
546 for (Artifact a : future.value.getArtifact()) {
547 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
548 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
549 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
550 AAFSSO.cons.printf("CA: %s\n",a.getCa());
551 StringBuilder sb = new StringBuilder();
552 boolean first = true;
553 for (String t : a.getType()) {
554 if (first) {first=false;}
555 else{sb.append(',');}
558 AAFSSO.cons.printf("Types: %s\n",sb);
559 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
560 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
561 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
562 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
563 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
567 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
570 trans.error().log(errMsg.toMsg(future));
577 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
578 String mechID = fqi(cmds);
579 String machine = machine(cmds);
580 String[] newmachs = machines(cmds);
581 if (machine==null || newmachs == null) {
582 trans.error().log("No machines listed to copy to");
584 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
586 Future<Artifacts> future = aafcon.client(CM_VER)
587 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
589 if (future.get(TIMEOUT)) {
590 boolean printed = false;
591 for (Artifact a : future.value.getArtifact()) {
592 for (String m : newmachs) {
594 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
595 if (fup.get(TIMEOUT)) {
596 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
598 trans.error().printf("Call to AAF Certman failed, %s",
606 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
609 trans.error().log(errMsg.toMsg(future));
617 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
618 String mechID = fqi(cmds);
619 String machine = machine(cmds);
621 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
623 Future<Artifacts> fread = aafcon.client(CM_VER)
624 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
626 if (fread.get(TIMEOUT)) {
627 Artifacts artifacts = new Artifacts();
628 for (Artifact a : fread.value.getArtifact()) {
629 Artifact arti = new Artifact();
630 artifacts.getArtifact().add(arti);
632 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
633 arti.setMechid(a.getMechid());
634 arti.setMachine(a.getMachine());
635 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
636 StringBuilder sb = new StringBuilder();
637 boolean first = true;
638 for (String t : a.getType()) {
639 if (first) {first=false;}
640 else{sb.append(',');}
644 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
645 for (String s : Split.splitTrim(',', resp)) {
646 arti.getType().add(s);
649 if (!resp.contains(SCRIPT)) {
650 arti.getType().add(SCRIPT);
653 // Note: Sponsor is set on Creation by CM
654 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
655 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
656 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
657 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
658 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
661 if (artifacts.getArtifact().size()==0) {
662 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
664 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
665 if (fup.get(TIMEOUT)) {
666 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
668 trans.error().printf("Call to AAF Certman failed, %s",
673 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
674 errMsg.toMsg(fread),mechID,machine);
681 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
682 String mechid = fqi(cmds);
683 String machine = machine(cmds);
685 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
687 Future<Void> future = aafcon.client(CM_VER)
688 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
690 if (future.get(TIMEOUT)) {
691 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
693 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
694 errMsg.toMsg(future),mechid,machine);
703 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
705 String mechID = fqi(cmds);
706 String machine = machine(cmds);
707 String[] fqdns = Split.split(':', machine);
709 if (fqdns.length>1) {
714 fqdns = machines(cmds);
717 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
719 Future<Artifacts> acf = aafcon.client(CM_VER)
720 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
721 if (acf.get(TIMEOUT)) {
722 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
723 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
725 for (Artifact a : acf.value.getArtifact()) {
726 String osID = System.getProperty("user.name");
727 if (a.getOsUser().equals(osID)) {
728 CertificateRequest cr = new CertificateRequest();
729 cr.setMechid(a.getMechid());
730 cr.setSponsor(a.getSponsor());
731 cr.getFqdns().add(machine);
732 for (int i=0;i<fqdns.length;++i) {
733 if(!machine.equals(fqdns[i])) {
734 cr.getFqdns().add(fqdns[i]);
737 Future<String> f = aafcon.client(CM_VER)
738 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
739 if (f.get(TIMEOUT)) {
740 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
741 for (String type : a.getType()) {
742 PlaceArtifact pa = placeArtifact.get(type);
744 if (rv = pa.place(trans, capi, a,machine)) {
749 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
751 trans.error().log(errMsg.toMsg(f));
754 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
758 PropHolder.writeAll();
760 trans.error().log(errMsg.toMsg(acf));
768 private static void notifyPlaced(Artifact a, boolean rv) {
771 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
772 String mechID = fqi(cmds);
773 String machine = machine(cmds);
775 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
777 Future<Artifacts> acf = aafcon.client(CM_VER)
778 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
779 if (acf.get(TIMEOUT)) {
780 // Have to wait for JDK 1.7 source...
781 //switch(artifact.getType()) {
782 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
783 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
785 String id = aafcon.defID();
787 for (Artifact a : acf.value.getArtifact()) {
788 allowed = id!=null && (id.equals(a.getSponsor()) ||
789 (id.equals(a.getMechid())
790 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
792 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
793 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
794 if (pf.get(TIMEOUT)) {
797 trans.error().log(errMsg.toMsg(pf));
801 File dir = new File(a.getDir());
802 Properties props = new Properties();
803 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
806 File chalFile = new File(dir,a.getNs()+".chal");
807 if(chalFile.exists()) {
809 fis = new FileInputStream(chalFile);
816 File f = new File(dir,a.getNs()+".keyfile");
818 Symm symm = ArtifactDir.getSymm(f);
820 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
821 Entry<Object,Object> en = iter.next();
822 if (en.getValue().toString().startsWith("enc:")) {
823 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
827 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
828 f.getAbsolutePath(),a.getMechid(), a.getMachine());
834 trans.error().log(errMsg.toMsg(acf));
842 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
843 final String fqi = fqi(cmds);
844 final String ns = FQI.reverseDomain(fqi);
845 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
846 File f = new File(dir,ns+".key");
849 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
850 if (!"Y".equalsIgnoreCase(line)) {
851 System.out.println("Canceling...");
856 KeyPair kp = Factory.generateKeyPair(trans);
857 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
858 System.out.printf("Wrote %s\n", f.getCanonicalFile());
860 f=new File(dir,ns+".pubkey");
861 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
862 System.out.printf("Wrote %s\n", f.getCanonicalFile());
865 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
866 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
868 final String fqi = fqi(cmds);
869 Artifact arti = new Artifact();
870 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir")));
871 arti.setNs(FQI.reverseDomain(fqi));
872 PropHolder loc = PropHolder.get(arti, "location.props");
873 PropHolder cred = PropHolder.get(arti,"cred.props");
874 PropHolder app= PropHolder.get(arti,"props");
875 for(String c : args) {
876 int idx = c.indexOf('=');
878 app.add(c.substring(0,idx), c.substring(idx+1));
881 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
883 for (String tag : LOC_TAGS) {
884 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
887 String keyfile = cred.getKeyPath();
889 File fkeyfile = new File(keyfile);
890 if(!fkeyfile.exists()) {
891 ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen());
894 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
895 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
896 if(fqi!=null && fqi.equals(ssoAppID)) {
897 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
898 // only Ask for Password when starting scratch
899 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
900 if(!configNoPasswd) {
901 char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi);
903 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
908 // load all properties that are already setup.
909 Map<String, String> aaf_urls = loadURLs(propAccess);
910 for(Entry<String, String> es : aaf_urls.entrySet()) {
911 app.add(es.getKey(), es.getValue());
914 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
915 app.add(Config.AAF_ENV,propAccess, "DEV");
916 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
918 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
921 app.add(Config.AAF_DEPLOYED_VERSION, release);
923 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
924 String key = aaf_loc_prop.getKey().toString();
925 if(key.startsWith("aaf_locator")) {
926 app.add(key, aaf_loc_prop.getValue().toString());
930 app.add(Config.AAF_APPID, fqi);
932 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
933 System.out.println("Passed in Truststore is " + cts);
935 File origTruststore = new File(cts);
936 File newTruststore = new File(app.getDir(),origTruststore.getName());
937 if(!newTruststore.exists()) {
938 if (!origTruststore.exists()) {
939 // Try same directory as cadi_prop_files
940 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
942 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
943 File fcpf = new File(f);
945 int lastSep = cts.lastIndexOf(File.pathSeparator);
946 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
947 if (origTruststore.exists()) {
952 if (!origTruststore.exists()) {
953 throw new CadiException(cts + " does not exist");
958 if (!newTruststore.exists() && origTruststore.exists()) {
959 Files.copy(origTruststore.toPath(), newTruststore.toPath());
963 System.out.println("New Truststore is " + newTruststore);
964 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
965 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
967 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
969 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
970 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
971 String f = propFiles[pfi];
972 System.out.format("Reading %s\n",f);
973 FileInputStream fis = new FileInputStream(f);
975 Properties props = new Properties();
977 for (Entry<Object, Object> prop : props.entrySet()) {
978 boolean lower = true;
979 String key = prop.getKey().toString();
980 if(LOC_TAGS.contains(key)) {
983 for(int i=0;lower && i<key.length();++i) {
984 if(Character.isUpperCase(key.charAt(i))) {
989 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
990 if(key.endsWith("_password")) {
991 ph.addEnc(key, prop.getValue().toString());
993 ph.add(key, prop.getValue().toString());
1002 aafcon = aafcon(propAccess);
1003 if (aafcon!=null) { // get Properties from Remote AAF
1004 for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
1005 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
1006 if(props.getTag().endsWith("_password")) {
1007 ph.addEnc(props.getTag(), props.getValue());
1009 ph.add(props.getTag(), props.getValue());
1017 PropHolder.writeAll();
1023 public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, LocatorException {
1024 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
1025 .read("/configure/"+fqi+"/aaf", configDF);
1026 if (acf.get(TIMEOUT)) {
1027 return acf.value.getProps();
1028 } else if (acf.code()==401){
1029 trans.error().log("Bad Password sent to AAF");
1030 } else if (acf.code()==404){
1031 trans.error().log("This version of AAF does not support remote Properties");
1033 trans.error().log(errMsg.toMsg(acf));
1035 return new ArrayList<>();
1038 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
1039 System.out.println("Validating Configuration...");
1040 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
1041 aafcon.best(new Retryable<Void>() {
1043 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
1044 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
1045 if (fc.get(aafcon.timeout)) {
1046 System.out.print("Success connecting to ");
1047 System.out.println(client.getURI());
1048 System.out.print(" Permissions for ");
1049 System.out.println(aafcon.defID());
1050 for (Perm p : fc.value.getPerm()) {
1051 System.out.print('\t');
1052 System.out.print(p.getType());
1053 System.out.print('|');
1054 System.out.print(p.getInstance());
1055 System.out.print('|');
1056 System.out.println(p.getAction());
1059 System.err.println("Error: " + fc.code() + ' ' + fc.body());
1067 * Check returns Error Codes, so that Scripts can know what to do
1069 * 0 - Check Complete, nothing to do
1071 * 2 - Error for specific Artifact - read check.msg
1072 * 10 - Certificate Updated - check.msg is email content
1080 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1082 String mechID = fqi(cmds);
1083 String machine = machine(cmds);
1085 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
1088 Future<Artifacts> acf = aafcon.client(CM_VER)
1089 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1090 if (acf.get(TIMEOUT)) {
1091 // Have to wait for JDK 1.7 source...
1092 //switch(artifact.getType()) {
1093 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1094 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1096 String id = aafcon.defID();
1097 GregorianCalendar now = new GregorianCalendar();
1098 for (Artifact a : acf.value.getArtifact()) {
1099 if (id.equals(a.getMechid())) {
1100 File dir = new File(a.getDir());
1101 Properties props = new Properties();
1102 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1112 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1113 !(f=new File(prop)).exists()) {
1114 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1115 a.getMechid(), a.getMachine());
1117 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1118 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1119 if (ksf==null || ksps == null) {
1120 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1121 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1123 Symm symm = ArtifactDir.getSymm(f);
1125 KeyStore ks = KeyStore.getInstance("JKS");
1127 fis = new FileInputStream(ksf);
1129 ks.load(fis,symm.depass(ksps).toCharArray());
1133 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1137 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1138 a.getMechid(), a.getMachine(), ksf);
1139 trans.error().log(msg);
1142 GregorianCalendar renew = new GregorianCalendar();
1143 renew.setTime(cert.getNotAfter());
1144 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1145 if (renew.after(now)) {
1146 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",
1147 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1148 trans.info().log(msg);
1151 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1152 a.getMechid(), a.getMachine(),cert.getNotAfter());
1153 cmds.offerLast(mechID);
1154 cmds.offerLast(machine);
1155 if (placeCerts(trans,aafcon,cmds)) {
1156 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1157 a.getMechid(), a.getMachine());
1158 exitCode = 10; // Refreshed
1160 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1161 a.getMechid(), a.getMachine());
1162 exitCode = 1; // Error Renewing
1167 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1169 fos.write(msg.getBytes());
1181 trans.error().log(errMsg.toMsg(acf));