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.TestConnectivity;
56 import org.onap.aaf.cadi.aaf.client.ErrMessage;
57 import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
58 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
59 import org.onap.aaf.cadi.client.Future;
60 import org.onap.aaf.cadi.client.Rcli;
61 import org.onap.aaf.cadi.client.Retryable;
62 import org.onap.aaf.cadi.config.Config;
63 import org.onap.aaf.cadi.config.RegistrationPropHolder;
64 import org.onap.aaf.cadi.config.SecurityInfoC;
65 import org.onap.aaf.cadi.http.HBasicAuthSS;
66 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
67 import org.onap.aaf.cadi.sso.AAFSSO;
68 import org.onap.aaf.cadi.util.Chmod;
69 import org.onap.aaf.cadi.util.FQI;
70 import org.onap.aaf.misc.env.APIException;
71 import org.onap.aaf.misc.env.Data.TYPE;
72 import org.onap.aaf.misc.env.Env;
73 import org.onap.aaf.misc.env.TimeTaken;
74 import org.onap.aaf.misc.env.Trans;
75 import org.onap.aaf.misc.env.util.Chrono;
76 import org.onap.aaf.misc.env.util.Split;
77 import org.onap.aaf.misc.rosetta.env.RosettaDF;
78 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
81 import aaf.v2_0.Perms;
82 import certman.v1_0.Artifacts;
83 import certman.v1_0.Artifacts.Artifact;
84 import certman.v1_0.CertInfo;
85 import certman.v1_0.CertificateRequest;
86 import locate.v1_1.Configuration;
87 import locate.v1_1.Configuration.Props;
90 private static final String AGENT_LOAD_URLS = "Agent:loadURLs";
91 private static final String HASHES = "################################################################";
92 private static final String PRINT = "print";
93 private static final String FILE = "file";
94 public static final String PKCS12 = "pkcs12";
95 public static final String JKS = "jks";
96 private static final String SCRIPT="script";
98 private static final String CM_VER = "1.0";
99 public static final int PASS_SIZE = 24;
100 private static int TIMEOUT;
102 private static RosettaDF<CertificateRequest> reqDF;
103 private static RosettaDF<CertInfo> certDF;
104 private static RosettaDF<Artifacts> artifactsDF;
105 private static RosettaDF<Configuration> configDF;
106 private static RosettaDF<Perms> permDF;
107 private static ErrMessage errMsg;
108 private static Map<String,PlaceArtifact> placeArtifact;
109 private static RosettaEnv env;
111 private static boolean doExit;
112 private static AAFCon<?> aafcon;
114 private static List<String> CRED_TAGS = Arrays.asList(new String[] {
116 Config.AAF_APPID, Config.AAF_APPPASS,
117 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
118 Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
119 Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
121 private static List<String> LOC_TAGS = Arrays.asList(new String[] {
122 Config.CADI_LATITUDE, Config.CADI_LONGITUDE
124 // Note: This is set by loadURLs. Use that function as singleton, not directly.
125 private static Map<String,String> aaf_urls = null;
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);
167 if(args.length>1 && args[1].contains("@")) {
168 String domain = FQI.reverseDomain(args[1]);
173 File etc = new File(hasEtc);
175 File nsprops = new File(etc,domain+".props");
176 if(nsprops.exists()) {
177 access = new PropAccess(new String[] {Config.CADI_PROP_FILES+'='+nsprops.getAbsolutePath()});
185 for(Entry<Object, Object> es : System.getProperties().entrySet()) {
186 if(Config.CADI_PROP_FILES.equals(es.getKey())) {
187 access = new PropAccess();
192 // When using Config file, check if Cred Exists, and if not, work with Deployer.
193 if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) {
194 // not enough credentials to use Props. Use AAFSSO
199 if (args.length>1 && args[0].equals("validate") ) {
200 int idx = args[1].indexOf('=');
202 access = new PropAccess(
203 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
205 (idx<0?args[1]:args[1].substring(idx+1)));
207 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
209 public Properties process(String[] args, Properties props) {
211 if (!args[0].equals("keypairgen")) {
212 props.put(Config.AAF_APPID, args[1]);
218 access = aafsso.access();
222 if (aafsso!=null && aafsso.loginOnly()) {
223 aafsso.setLogDefault();
225 System.out.println("AAF SSO information created in ~/.aaf");
227 env = new RosettaEnv(access.getProperties());
228 Deque<String> cmds = new ArrayDeque<String>();
229 for (String p : args) {
231 if ("-noexit".equalsIgnoreCase(p)) {
233 } else if ((eq=p.indexOf('=')) < 0) {
236 access.setProperty(p.substring(0,eq), p.substring(eq+1));
240 if (cmds.size()==0) {
242 aafsso.setLogDefault();
244 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
245 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
246 System.out.println(" create <FQI> [<machine>]");
247 System.out.println(" read <FQI> [<machine>]");
248 System.out.println(" update <FQI> [<machine>]");
249 System.out.println(" delete <FQI> [<machine>]");
250 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
251 System.out.println(" place <FQI> [<machine>]");
252 System.out.println(" showpass <FQI> [<machine>]");
253 System.out.println(" check <FQI> [<machine>]");
254 System.out.println(" keypairgen <FQI>");
255 System.out.println(" config <FQI>");
256 System.out.println(" validate <NS>.props>");
257 System.out.println(" connectivity <NS>.props>");
258 System.out.println(" --- Additional Tool Access ---");
259 System.out.println(" ** Type with no params for Tool Help");
260 System.out.println(" ** If using with Agent, preface with \"cadi\"");
261 System.out.println(" cadi <cadi tool params, see -?>");
268 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
270 reqDF = env.newDataFactory(CertificateRequest.class);
271 artifactsDF = env.newDataFactory(Artifacts.class);
272 certDF = env.newDataFactory(CertInfo.class);
273 configDF = env.newDataFactory(Configuration.class);
274 permDF = env.newDataFactory(Perms.class);
275 errMsg = new ErrMessage(env);
277 placeArtifact = new HashMap<>();
278 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
279 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
280 placeArtifact.put(FILE, new PlaceArtifactInFiles());
281 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
282 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
284 Trans trans = env.newTrans();
286 if ((token=access.getProperty("oauth_token"))!=null) {
287 trans.setProperty("oauth_token", token);
291 // show Std out again
292 aafsso.setLogDefault();
293 aafsso.setStdErrDefault();
295 /*urls=*/loadURLs(access);
301 String cmd = cmds.removeFirst();
304 placeCerts(trans,aafcon(access),cmds);
307 createArtifact(trans, aafcon(access),cmds);
310 readArtifact(trans, aafcon(access), cmds);
313 copyArtifact(trans, aafcon(access), cmds);
316 updateArtifact(trans, aafcon(access), cmds);
319 deleteArtifact(trans, aafcon(access), cmds);
322 showPass(trans, aafcon(access), cmds);
325 keypairGen(trans, access, cmds);
328 config(trans,access,args,cmds);
335 exitCode = check(trans,aafcon(access),cmds);
336 } catch (Exception e) {
342 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
345 StringBuilder sb = new StringBuilder();
346 trans.auditTrail(4, sb, Trans.REMOTE);
348 trans.info().log("Trans Info\n",sb);
355 } catch (Exception e) {
359 if (exitCode != 0 && doExit) {
360 System.exit(exitCode);
364 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
366 Map<String,String> rv = new HashMap<>();
367 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
368 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
369 dot_le=dot_le==null?"":'.'+dot_le;
370 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
371 for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) {
375 case "aaf": tag = Config.AAF_URL; break;
376 case "locate":tag = Config.AAF_LOCATE_URL; break;
377 case "oauth": tag = Config.AAF_URL_OAUTH; break;
378 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
379 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
380 case "cm": tag = Config.AAF_URL_CM; break;
381 case "gui": tag = Config.AAF_URL_GUI; break;
382 case "fs": tag = Config.AAF_URL_FS; break;
383 case "hello": tag = Config.AAF_URL_HELLO; break;
385 tag = "aaf_url_" + u;
388 if((value=access.getProperty(tag,null))==null) {
389 String proto = "fs".equals(u)?"http://":"https://";
391 if("locate".equals(u)) {
392 lhost=rph.default_fqdn;
394 lhost=Config.AAF_LOCATE_URL_TAG;
396 value = rph.replacements(AGENT_LOAD_URLS,
397 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
403 value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le);
412 public static void fillMissing(PropAccess access, Map<String, String> map) {
413 for(Entry<String, String> es : map.entrySet()) {
414 if(access.getProperty(es.getKey())==null) {
415 access.setProperty(es.getKey(),es.getValue());
420 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
422 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
427 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
429 if ((value=pa.getProperty(tag))==null) {
431 value = new String(AAFSSO.cons.readPassword(prompt, def));
433 value = AAFSSO.cons.readLine(prompt,def).trim();
436 if (value.length()>0) {
437 pa.setProperty(tag,value);
438 env.setProperty(tag,value);
439 } else if (def.length==1) {
440 value=def[0].toString();
441 pa.setProperty(tag,value);
442 env.setProperty(tag,value);
449 private static String fqi(Deque<String> cmds) {
451 String alias = env.getProperty(Config.CADI_ALIAS);
453 alias = env.getProperty(Config.AAF_APPID);
455 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
457 return cmds.removeFirst();
460 private static String machine(Deque<String> cmds) throws UnknownHostException {
462 return cmds.removeFirst();
464 String mach = env.getProperty(Config.HOSTNAME);
465 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
469 private static String[] machines(Deque<String> cmds) {
472 machines = cmds.removeFirst();
474 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
476 return Split.split(',', machines);
479 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
480 final String mechID = fqi(cmds);
481 final String machine = machine(cmds);
483 Artifacts artifacts = new Artifacts();
484 Artifact arti = new Artifact();
485 artifacts.getArtifact().add(arti);
486 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
487 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
488 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
490 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
491 for (String s : Split.splitTrim(',', resp)) {
492 arti.getType().add(s);
495 if (!resp.contains(SCRIPT)) {
496 arti.getType().add(SCRIPT);
499 // Note: Sponsor is set on Creation by CM
500 String configRootName = FQI.reverseDomain(arti.getMechid());
501 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
502 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
503 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
504 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
505 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
507 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
509 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
510 if (future.get(TIMEOUT)) {
511 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
513 trans.error().printf("Call to AAF Certman failed, %s",
514 errMsg.toMsg(future));
521 private static String toNotification(String notification) {
522 if (notification==null) {
524 } else if (notification.length()>0) {
525 if (notification.indexOf(':')<0) {
526 notification = "mailto:" + notification;
533 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
534 String mechID = fqi(cmds);
535 String machine = machine(cmds);
537 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
539 Future<Artifacts> future = aafcon.client(CM_VER)
540 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
542 if (future.get(TIMEOUT)) {
543 boolean printed = false;
544 for (Artifact a : future.value.getArtifact()) {
545 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
546 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
547 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
548 AAFSSO.cons.printf("CA: %s\n",a.getCa());
549 StringBuilder sb = new StringBuilder();
550 boolean first = true;
551 for (String t : a.getType()) {
552 if (first) {first=false;}
553 else{sb.append(',');}
556 AAFSSO.cons.printf("Types: %s\n",sb);
557 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
558 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
559 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
560 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
561 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
565 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
568 trans.error().log(errMsg.toMsg(future));
575 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
576 String mechID = fqi(cmds);
577 String machine = machine(cmds);
578 String[] newmachs = machines(cmds);
579 if (machine==null || newmachs == null) {
580 trans.error().log("No machines listed to copy to");
582 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
584 Future<Artifacts> future = aafcon.client(CM_VER)
585 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
587 if (future.get(TIMEOUT)) {
588 boolean printed = false;
589 for (Artifact a : future.value.getArtifact()) {
590 for (String m : newmachs) {
592 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
593 if (fup.get(TIMEOUT)) {
594 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
596 trans.error().printf("Call to AAF Certman failed, %s",
604 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
607 trans.error().log(errMsg.toMsg(future));
615 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
616 String mechID = fqi(cmds);
617 String machine = machine(cmds);
619 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
621 Future<Artifacts> fread = aafcon.client(CM_VER)
622 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
624 if (fread.get(TIMEOUT)) {
625 Artifacts artifacts = new Artifacts();
626 for (Artifact a : fread.value.getArtifact()) {
627 Artifact arti = new Artifact();
628 artifacts.getArtifact().add(arti);
630 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
631 arti.setMechid(a.getMechid());
632 arti.setMachine(a.getMachine());
633 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
634 StringBuilder sb = new StringBuilder();
635 boolean first = true;
636 for (String t : a.getType()) {
637 if (first) {first=false;}
638 else{sb.append(',');}
642 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
643 for (String s : Split.splitTrim(',', resp)) {
644 arti.getType().add(s);
647 if (!resp.contains(SCRIPT)) {
648 arti.getType().add(SCRIPT);
651 // Note: Sponsor is set on Creation by CM
652 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
653 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
654 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
655 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
656 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
659 if (artifacts.getArtifact().size()==0) {
660 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
662 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
663 if (fup.get(TIMEOUT)) {
664 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
666 trans.error().printf("Call to AAF Certman failed, %s",
671 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
672 errMsg.toMsg(fread),mechID,machine);
679 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
680 String mechid = fqi(cmds);
681 String machine = machine(cmds);
683 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
685 Future<Void> future = aafcon.client(CM_VER)
686 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
688 if (future.get(TIMEOUT)) {
689 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
691 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
692 errMsg.toMsg(future),mechid,machine);
701 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
703 String mechID = fqi(cmds);
704 String machine = machine(cmds);
705 String[] fqdns = Split.split(':', machine);
707 if (fqdns.length>1) {
714 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
716 Future<Artifacts> acf = aafcon.client(CM_VER)
717 .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
718 if (acf.get(TIMEOUT)) {
719 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
720 AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
722 for (Artifact a : acf.value.getArtifact()) {
723 String osID = System.getProperty("user.name");
724 if (a.getOsUser().equals(osID)) {
725 CertificateRequest cr = new CertificateRequest();
726 cr.setMechid(a.getMechid());
727 cr.setSponsor(a.getSponsor());
728 for (int i=0;i<fqdns.length;++i) {
729 cr.getFqdns().add(fqdns[i]);
731 Future<String> f = aafcon.client(CM_VER)
732 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
733 if (f.get(TIMEOUT)) {
734 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
735 for (String type : a.getType()) {
736 PlaceArtifact pa = placeArtifact.get(type);
738 if (rv = pa.place(trans, capi, a,machine)) {
743 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
745 trans.error().log(errMsg.toMsg(f));
748 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
752 PropHolder.writeAll();
754 trans.error().log(errMsg.toMsg(acf));
762 private static void notifyPlaced(Artifact a, boolean rv) {
765 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
766 String mechID = fqi(cmds);
767 String machine = machine(cmds);
769 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
771 Future<Artifacts> acf = aafcon.client(CM_VER)
772 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
773 if (acf.get(TIMEOUT)) {
774 // Have to wait for JDK 1.7 source...
775 //switch(artifact.getType()) {
776 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
777 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
779 String id = aafcon.defID();
781 for (Artifact a : acf.value.getArtifact()) {
782 allowed = id!=null && (id.equals(a.getSponsor()) ||
783 (id.equals(a.getMechid())
784 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
786 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
787 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
788 if (pf.get(TIMEOUT)) {
791 trans.error().log(errMsg.toMsg(pf));
795 File dir = new File(a.getDir());
796 Properties props = new Properties();
797 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
800 File chalFile = new File(dir,a.getNs()+".chal");
801 if(chalFile.exists()) {
803 fis = new FileInputStream(chalFile);
810 File f = new File(dir,a.getNs()+".keyfile");
812 Symm symm = ArtifactDir.getSymm(f);
814 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
815 Entry<Object,Object> en = iter.next();
816 if (en.getValue().toString().startsWith("enc:")) {
817 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
821 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
822 f.getAbsolutePath(),a.getMechid(), a.getMachine());
828 trans.error().log(errMsg.toMsg(acf));
836 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
837 final String fqi = fqi(cmds);
838 final String ns = FQI.reverseDomain(fqi);
839 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
840 File f = new File(dir,ns+".key");
843 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
844 if (!"Y".equalsIgnoreCase(line)) {
845 System.out.println("Canceling...");
850 KeyPair kp = Factory.generateKeyPair(trans);
851 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
852 System.out.printf("Wrote %s\n", f.getCanonicalFile());
854 f=new File(dir,ns+".pubkey");
855 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
856 System.out.printf("Wrote %s\n", f.getCanonicalFile());
859 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
860 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
862 final String fqi = fqi(cmds);
863 Artifact arti = new Artifact();
864 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir")));
865 arti.setNs(FQI.reverseDomain(fqi));
866 PropHolder loc = PropHolder.get(arti, "location.props");
867 PropHolder cred = PropHolder.get(arti,"cred.props");
868 PropHolder app= PropHolder.get(arti,"props");
869 for(String c : args) {
870 int idx = c.indexOf('=');
872 app.add(c.substring(0,idx), c.substring(idx+1));
875 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
877 for (String tag : LOC_TAGS) {
878 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
881 String keyfile = cred.getKeyPath();
883 File fkeyfile = new File(keyfile);
884 if(!fkeyfile.exists()) {
885 ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen());
888 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
889 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
890 if(fqi!=null && fqi.equals(ssoAppID)) {
891 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
892 // only Ask for Password when starting scratch
893 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
894 char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi);
896 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
900 // load all properties that are already setup.
901 Map<String, String> aaf_urls = loadURLs(propAccess);
902 for(Entry<String, String> es : aaf_urls.entrySet()) {
903 app.add(es.getKey(), es.getValue());
906 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
907 app.add(Config.AAF_ENV,propAccess, "DEV");
908 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
910 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
913 app.add(Config.AAF_DEPLOYED_VERSION, release);
915 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
916 String key = aaf_loc_prop.getKey().toString();
917 if(key.startsWith("aaf_locator")) {
918 app.add(key, aaf_loc_prop.getValue().toString());
922 app.add(Config.AAF_APPID, fqi);
924 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
925 System.out.println("Passed in Truststore is " + cts);
927 File origTruststore = new File(cts);
928 File newTruststore = new File(app.getDir(),origTruststore.getName());
929 if(!newTruststore.exists()) {
930 if (!origTruststore.exists()) {
931 // Try same directory as cadi_prop_files
932 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
934 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
935 File fcpf = new File(f);
937 int lastSep = cts.lastIndexOf(File.pathSeparator);
938 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
939 if (origTruststore.exists()) {
944 if (!origTruststore.exists()) {
945 throw new CadiException(cts + " does not exist");
950 if (!newTruststore.exists() && origTruststore.exists()) {
951 Files.copy(origTruststore.toPath(), newTruststore.toPath());
955 System.out.println("New Truststore is " + newTruststore);
956 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
957 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
959 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
961 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
962 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
963 String f = propFiles[pfi];
964 System.out.format("Reading %s\n",f);
965 FileInputStream fis = new FileInputStream(f);
967 Properties props = new Properties();
969 for (Entry<Object, Object> prop : props.entrySet()) {
970 boolean lower = true;
971 String key = prop.getKey().toString();
972 if(LOC_TAGS.contains(key)) {
975 for(int i=0;lower && i<key.length();++i) {
976 if(Character.isUpperCase(key.charAt(i))) {
981 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
982 if(key.endsWith("_password")) {
983 ph.addEnc(key, prop.getValue().toString());
985 ph.add(key, prop.getValue().toString());
994 aafcon = aafcon(propAccess);
995 if (aafcon!=null) { // get Properties from Remote AAF
996 for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
997 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
998 if(props.getTag().endsWith("_password")) {
999 ph.addEnc(props.getTag(), props.getValue());
1001 ph.add(props.getTag(), props.getValue());
1009 PropHolder.writeAll();
1015 public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, URISyntaxException {
1016 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
1017 .read("/configure/"+fqi+"/aaf", configDF);
1018 if (acf.get(TIMEOUT)) {
1019 return acf.value.getProps();
1020 } else if (acf.code()==401){
1021 trans.error().log("Bad Password sent to AAF");
1022 } else if (acf.code()==404){
1023 trans.error().log("This version of AAF does not support remote Properties");
1025 trans.error().log(errMsg.toMsg(acf));
1027 return new ArrayList<>();
1030 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
1031 System.out.println("Validating Configuration...");
1032 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
1033 aafcon.best(new Retryable<Void>() {
1035 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
1036 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
1037 if (fc.get(aafcon.timeout)) {
1038 System.out.print("Success connecting to ");
1039 System.out.println(client.getURI());
1040 System.out.print(" Permissions for ");
1041 System.out.println(aafcon.defID());
1042 for (Perm p : fc.value.getPerm()) {
1043 System.out.print('\t');
1044 System.out.print(p.getType());
1045 System.out.print('|');
1046 System.out.print(p.getInstance());
1047 System.out.print('|');
1048 System.out.println(p.getAction());
1051 System.err.println("Error: " + fc.code() + ' ' + fc.body());
1059 * Check returns Error Codes, so that Scripts can know what to do
1061 * 0 - Check Complete, nothing to do
1063 * 2 - Error for specific Artifact - read check.msg
1064 * 10 - Certificate Updated - check.msg is email content
1072 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1074 String mechID = fqi(cmds);
1075 String machine = machine(cmds);
1077 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
1080 Future<Artifacts> acf = aafcon.client(CM_VER)
1081 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1082 if (acf.get(TIMEOUT)) {
1083 // Have to wait for JDK 1.7 source...
1084 //switch(artifact.getType()) {
1085 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1086 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1088 String id = aafcon.defID();
1089 GregorianCalendar now = new GregorianCalendar();
1090 for (Artifact a : acf.value.getArtifact()) {
1091 if (id.equals(a.getMechid())) {
1092 File dir = new File(a.getDir());
1093 Properties props = new Properties();
1094 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1104 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1105 !(f=new File(prop)).exists()) {
1106 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1107 a.getMechid(), a.getMachine());
1109 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1110 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1111 if (ksf==null || ksps == null) {
1112 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1113 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1115 Symm symm = ArtifactDir.getSymm(f);
1117 KeyStore ks = KeyStore.getInstance("JKS");
1119 fis = new FileInputStream(ksf);
1121 ks.load(fis,symm.depass(ksps).toCharArray());
1125 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1129 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1130 a.getMechid(), a.getMachine(), ksf);
1131 trans.error().log(msg);
1134 GregorianCalendar renew = new GregorianCalendar();
1135 renew.setTime(cert.getNotAfter());
1136 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1137 if (renew.after(now)) {
1138 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",
1139 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1140 trans.info().log(msg);
1143 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1144 a.getMechid(), a.getMachine(),cert.getNotAfter());
1145 cmds.offerLast(mechID);
1146 cmds.offerLast(machine);
1147 if (placeCerts(trans,aafcon,cmds)) {
1148 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1149 a.getMechid(), a.getMachine());
1150 exitCode = 10; // Refreshed
1152 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1153 a.getMechid(), a.getMachine());
1154 exitCode = 1; // Error Renewing
1159 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1161 fos.write(msg.getBytes());
1173 trans.error().log(errMsg.toMsg(acf));