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;
126 private static boolean configNoPasswd = false;
129 public static void main(String[] args) {
132 if (args.length>0 && "cadi".equals(args[0])) {
133 String[] newArgs = new String[args.length-1];
134 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
135 if (newArgs.length==0) {
136 System.out.println(HASHES);
137 System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t"
138 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
139 System.out.println(HASHES);
141 CmdLine.main(newArgs);
142 } else if(args.length>0 && "connectivity".equals(args[0])) {
143 String[] newArgs = new String[args.length-1];
144 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
145 if(newArgs.length>0 && newArgs[0].indexOf('@')>=0) {
146 newArgs[0]=FQI.reverseDomain(newArgs[0])+".props";
148 TestConnectivity.main(newArgs);
152 PropAccess access=null;
154 String hasEtc = null;
155 for(String a : args) {
156 if(a.startsWith(Config.CADI_PROP_FILES)) {
157 access = new PropAccess(args);
159 } else if(a.startsWith(Config.CADI_ETCDIR)) {
160 int idx = a.indexOf('=');
161 if(idx>=0 && idx<a.length()) {
162 hasEtc = a.substring(idx+1);
164 } else if(a.equals("--nopasswd")) {
170 if(args.length>1 && args[1].contains("@")) {
171 String domain = FQI.reverseDomain(args[1]);
176 File etc = new File(hasEtc);
178 File nsprops = new File(etc,domain+".props");
179 if(nsprops.exists()) {
180 access = new PropAccess(new String[] {Config.CADI_PROP_FILES+'='+nsprops.getAbsolutePath()});
188 for(Entry<Object, Object> es : System.getProperties().entrySet()) {
189 if(Config.CADI_PROP_FILES.equals(es.getKey())) {
190 access = new PropAccess();
195 // When using Config file, check if Cred Exists, and if not, work with Deployer.
196 if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) {
197 // not enough credentials to use Props. Use AAFSSO
202 if (args.length>1 && args[0].equals("validate") ) {
203 int idx = args[1].indexOf('=');
205 access = new PropAccess(
206 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
208 (idx<0?args[1]:args[1].substring(idx+1)));
210 aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
212 public Properties process(String[] args, Properties props) {
214 if (!args[0].equals("keypairgen")) {
215 props.put(Config.AAF_APPID, args[1]);
221 access = aafsso.access();
225 if (aafsso!=null && aafsso.loginOnly()) {
226 aafsso.setLogDefault();
228 System.out.println("AAF SSO information created in ~/.aaf");
230 env = new RosettaEnv(access.getProperties());
231 Deque<String> cmds = new ArrayDeque<String>();
232 for (String p : args) {
234 if ("-noexit".equalsIgnoreCase(p)) {
236 } else if ((eq=p.indexOf('=')) < 0) {
239 access.setProperty(p.substring(0,eq), p.substring(eq+1));
243 if (cmds.size()==0) {
245 aafsso.setLogDefault();
247 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
248 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
249 System.out.println(" create <FQI> [<machine>]");
250 System.out.println(" read <FQI> [<machine>]");
251 System.out.println(" update <FQI> [<machine>]");
252 System.out.println(" delete <FQI> [<machine>]");
253 System.out.println(" copy <FQI> <machine> <newmachine>[,<newmachine>]*");
254 System.out.println(" place <FQI> [<machine>]");
255 System.out.println(" showpass <FQI> [<machine>]");
256 System.out.println(" check <FQI> [<machine>]");
257 System.out.println(" keypairgen <FQI>");
258 System.out.println(" config <FQI> [--nopasswd]");
259 System.out.println(" validate <NS>.props>");
260 System.out.println(" connectivity <NS>.props>");
261 System.out.println(" --- Additional Tool Access ---");
262 System.out.println(" ** Type with no params for Tool Help");
263 System.out.println(" ** If using with Agent, preface with \"cadi\"");
264 System.out.println(" cadi <cadi tool params, see -?>");
271 TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
273 reqDF = env.newDataFactory(CertificateRequest.class);
274 artifactsDF = env.newDataFactory(Artifacts.class);
275 certDF = env.newDataFactory(CertInfo.class);
276 configDF = env.newDataFactory(Configuration.class);
277 permDF = env.newDataFactory(Perms.class);
278 errMsg = new ErrMessage(env);
280 placeArtifact = new HashMap<>();
281 placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
282 placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
283 placeArtifact.put(FILE, new PlaceArtifactInFiles());
284 placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
285 placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
287 Trans trans = env.newTrans();
289 if ((token=access.getProperty("oauth_token"))!=null) {
290 trans.setProperty("oauth_token", token);
294 // show Std out again
295 aafsso.setLogDefault();
296 aafsso.setStdErrDefault();
298 /*urls=*/loadURLs(access);
304 String cmd = cmds.removeFirst();
307 placeCerts(trans,aafcon(access),cmds);
310 createArtifact(trans, aafcon(access),cmds);
313 readArtifact(trans, aafcon(access), cmds);
316 copyArtifact(trans, aafcon(access), cmds);
319 updateArtifact(trans, aafcon(access), cmds);
322 deleteArtifact(trans, aafcon(access), cmds);
325 showPass(trans, aafcon(access), cmds);
328 keypairGen(trans, access, cmds);
331 config(trans,access,args,cmds);
338 exitCode = check(trans,aafcon(access),cmds);
339 } catch (Exception e) {
345 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
348 StringBuilder sb = new StringBuilder();
349 trans.auditTrail(4, sb, Trans.REMOTE);
351 trans.info().log("Trans Info\n",sb);
358 } catch (Exception e) {
362 if (exitCode != 0 && doExit) {
363 System.exit(exitCode);
367 public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException {
369 Map<String,String> rv = new HashMap<>();
370 RegistrationPropHolder rph = new RegistrationPropHolder(access, 0);
371 String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null);
372 dot_le=dot_le==null?"":'.'+dot_le;
373 String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
374 for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) {
378 case "aaf": tag = Config.AAF_URL; break;
379 case "locate":tag = Config.AAF_LOCATE_URL; break;
380 case "oauth": tag = Config.AAF_URL_OAUTH; break;
381 case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break;
382 case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break;
383 case "cm": tag = Config.AAF_URL_CM; break;
384 case "gui": tag = Config.AAF_URL_GUI; break;
385 case "fs": tag = Config.AAF_URL_FS; break;
386 case "hello": tag = Config.AAF_URL_HELLO; break;
388 tag = "aaf_url_" + u;
391 if((value=access.getProperty(tag,null))==null) {
392 String proto = "fs".equals(u)?"http://":"https://";
394 if("locate".equals(u)) {
395 lhost=rph.default_fqdn;
397 lhost=Config.AAF_LOCATE_URL_TAG;
399 value = rph.replacements(AGENT_LOAD_URLS,
400 proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version,
406 value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le);
415 public static void fillMissing(PropAccess access, Map<String, String> map) {
416 for(Entry<String, String> es : map.entrySet()) {
417 if(access.getProperty(es.getKey())==null) {
418 access.setProperty(es.getKey(),es.getValue());
423 private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException {
425 aafcon = new AAFConHttp(access,Config.AAF_URL_CM);
430 private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
432 if ((value=pa.getProperty(tag))==null) {
434 value = new String(AAFSSO.cons.readPassword(prompt, def));
436 value = AAFSSO.cons.readLine(prompt,def).trim();
439 if (value.length()>0) {
440 pa.setProperty(tag,value);
441 env.setProperty(tag,value);
442 } else if (def.length==1) {
443 value=def[0].toString();
444 pa.setProperty(tag,value);
445 env.setProperty(tag,value);
452 private static String fqi(Deque<String> cmds) {
454 String alias = env.getProperty(Config.CADI_ALIAS);
456 alias = env.getProperty(Config.AAF_APPID);
458 return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
460 return cmds.removeFirst();
463 private static String machine(Deque<String> cmds) throws UnknownHostException {
465 return cmds.removeFirst();
467 String mach = env.getProperty(Config.HOSTNAME);
468 return mach!=null?mach:InetAddress.getLocalHost().getHostName();
472 private static String[] machines(Deque<String> cmds) {
475 machines = cmds.removeFirst();
477 machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
479 return Split.split(',', machines);
482 private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
483 final String mechID = fqi(cmds);
484 final String machine = machine(cmds);
486 Artifacts artifacts = new Artifacts();
487 Artifact arti = new Artifact();
488 artifacts.getArtifact().add(arti);
489 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
490 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
491 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
493 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
494 for (String s : Split.splitTrim(',', resp)) {
495 arti.getType().add(s);
498 if (!resp.contains(SCRIPT)) {
499 arti.getType().add(SCRIPT);
502 // Note: Sponsor is set on Creation by CM
503 String configRootName = FQI.reverseDomain(arti.getMechid());
504 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
505 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
506 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
507 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
508 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
510 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
512 Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
513 if (future.get(TIMEOUT)) {
514 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
516 trans.error().printf("Call to AAF Certman failed, %s",
517 errMsg.toMsg(future));
524 private static String toNotification(String notification) {
525 if (notification==null) {
527 } else if (notification.length()>0) {
528 if (notification.indexOf(':')<0) {
529 notification = "mailto:" + notification;
536 private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
537 String mechID = fqi(cmds);
538 String machine = machine(cmds);
540 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
542 Future<Artifacts> future = aafcon.client(CM_VER)
543 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
545 if (future.get(TIMEOUT)) {
546 boolean printed = false;
547 for (Artifact a : future.value.getArtifact()) {
548 AAFSSO.cons.printf("AppID: %s\n",a.getMechid());
549 AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor());
550 AAFSSO.cons.printf("Machine: %s\n",a.getMachine());
551 AAFSSO.cons.printf("CA: %s\n",a.getCa());
552 StringBuilder sb = new StringBuilder();
553 boolean first = true;
554 for (String t : a.getType()) {
555 if (first) {first=false;}
556 else{sb.append(',');}
559 AAFSSO.cons.printf("Types: %s\n",sb);
560 AAFSSO.cons.printf("Namespace: %s\n",a.getNs());
561 AAFSSO.cons.printf("Directory: %s\n",a.getDir());
562 AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser());
563 AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays());
564 AAFSSO.cons.printf("Notification %s\n",a.getNotification());
568 AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
571 trans.error().log(errMsg.toMsg(future));
578 private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
579 String mechID = fqi(cmds);
580 String machine = machine(cmds);
581 String[] newmachs = machines(cmds);
582 if (machine==null || newmachs == null) {
583 trans.error().log("No machines listed to copy to");
585 TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
587 Future<Artifacts> future = aafcon.client(CM_VER)
588 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
590 if (future.get(TIMEOUT)) {
591 boolean printed = false;
592 for (Artifact a : future.value.getArtifact()) {
593 for (String m : newmachs) {
595 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
596 if (fup.get(TIMEOUT)) {
597 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
599 trans.error().printf("Call to AAF Certman failed, %s",
607 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
610 trans.error().log(errMsg.toMsg(future));
618 private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
619 String mechID = fqi(cmds);
620 String machine = machine(cmds);
622 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
624 Future<Artifacts> fread = aafcon.client(CM_VER)
625 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
627 if (fread.get(TIMEOUT)) {
628 Artifacts artifacts = new Artifacts();
629 for (Artifact a : fread.value.getArtifact()) {
630 Artifact arti = new Artifact();
631 artifacts.getArtifact().add(arti);
633 AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
634 arti.setMechid(a.getMechid());
635 arti.setMachine(a.getMachine());
636 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
637 StringBuilder sb = new StringBuilder();
638 boolean first = true;
639 for (String t : a.getType()) {
640 if (first) {first=false;}
641 else{sb.append(',');}
645 String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
646 for (String s : Split.splitTrim(',', resp)) {
647 arti.getType().add(s);
650 if (!resp.contains(SCRIPT)) {
651 arti.getType().add(SCRIPT);
654 // Note: Sponsor is set on Creation by CM
655 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
656 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
657 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
658 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
659 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
662 if (artifacts.getArtifact().size()==0) {
663 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
665 Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
666 if (fup.get(TIMEOUT)) {
667 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
669 trans.error().printf("Call to AAF Certman failed, %s",
674 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
675 errMsg.toMsg(fread),mechID,machine);
682 private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
683 String mechid = fqi(cmds);
684 String machine = machine(cmds);
686 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
688 Future<Void> future = aafcon.client(CM_VER)
689 .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
691 if (future.get(TIMEOUT)) {
692 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
694 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
695 errMsg.toMsg(future),mechid,machine);
704 private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
706 String mechID = fqi(cmds);
707 String machine = machine(cmds);
708 String[] fqdns = Split.split(':', machine);
710 if (fqdns.length>1) {
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 for (int i=0;i<fqdns.length;++i) {
732 cr.getFqdns().add(fqdns[i]);
734 Future<String> f = aafcon.client(CM_VER)
735 .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
736 if (f.get(TIMEOUT)) {
737 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
738 for (String type : a.getType()) {
739 PlaceArtifact pa = placeArtifact.get(type);
741 if (rv = pa.place(trans, capi, a,machine)) {
746 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
748 trans.error().log(errMsg.toMsg(f));
751 trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
755 PropHolder.writeAll();
757 trans.error().log(errMsg.toMsg(acf));
765 private static void notifyPlaced(Artifact a, boolean rv) {
768 private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
769 String mechID = fqi(cmds);
770 String machine = machine(cmds);
772 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
774 Future<Artifacts> acf = aafcon.client(CM_VER)
775 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
776 if (acf.get(TIMEOUT)) {
777 // Have to wait for JDK 1.7 source...
778 //switch(artifact.getType()) {
779 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
780 AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
782 String id = aafcon.defID();
784 for (Artifact a : acf.value.getArtifact()) {
785 allowed = id!=null && (id.equals(a.getSponsor()) ||
786 (id.equals(a.getMechid())
787 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
789 Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" +
790 a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
791 if (pf.get(TIMEOUT)) {
794 trans.error().log(errMsg.toMsg(pf));
798 File dir = new File(a.getDir());
799 Properties props = new Properties();
800 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
803 File chalFile = new File(dir,a.getNs()+".chal");
804 if(chalFile.exists()) {
806 fis = new FileInputStream(chalFile);
813 File f = new File(dir,a.getNs()+".keyfile");
815 Symm symm = ArtifactDir.getSymm(f);
817 for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
818 Entry<Object,Object> en = iter.next();
819 if (en.getValue().toString().startsWith("enc:")) {
820 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
824 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
825 f.getAbsolutePath(),a.getMechid(), a.getMachine());
831 trans.error().log(errMsg.toMsg(acf));
839 private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
840 final String fqi = fqi(cmds);
841 final String ns = FQI.reverseDomain(fqi);
842 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
843 File f = new File(dir,ns+".key");
846 String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
847 if (!"Y".equalsIgnoreCase(line)) {
848 System.out.println("Canceling...");
853 KeyPair kp = Factory.generateKeyPair(trans);
854 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
855 System.out.printf("Wrote %s\n", f.getCanonicalFile());
857 f=new File(dir,ns+".pubkey");
858 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
859 System.out.printf("Wrote %s\n", f.getCanonicalFile());
862 private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception {
863 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
865 final String fqi = fqi(cmds);
866 Artifact arti = new Artifact();
867 arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir")));
868 arti.setNs(FQI.reverseDomain(fqi));
869 PropHolder loc = PropHolder.get(arti, "location.props");
870 PropHolder cred = PropHolder.get(arti,"cred.props");
871 PropHolder app= PropHolder.get(arti,"props");
872 for(String c : args) {
873 int idx = c.indexOf('=');
875 app.add(c.substring(0,idx), c.substring(idx+1));
878 app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath());
880 for (String tag : LOC_TAGS) {
881 loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag));
884 String keyfile = cred.getKeyPath();
886 File fkeyfile = new File(keyfile);
887 if(!fkeyfile.exists()) {
888 ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen());
891 cred.add(Config.CADI_KEYFILE, cred.getKeyPath());
892 final String ssoAppID = propAccess.getProperty(Config.AAF_APPID);
893 if(fqi!=null && fqi.equals(ssoAppID)) {
894 cred.addEnc(Config.AAF_APPPASS, propAccess, null);
895 // only Ask for Password when starting scratch
896 } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) {
897 if(!configNoPasswd) {
898 char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi);
900 cred.addEnc(Config.AAF_APPPASS, new String(pwd));
905 // load all properties that are already setup.
906 Map<String, String> aaf_urls = loadURLs(propAccess);
907 for(Entry<String, String> es : aaf_urls.entrySet()) {
908 app.add(es.getKey(), es.getValue());
911 app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess));
912 app.add(Config.AAF_ENV,propAccess, "DEV");
913 String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION);
915 release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null);
918 app.add(Config.AAF_DEPLOYED_VERSION, release);
920 for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) {
921 String key = aaf_loc_prop.getKey().toString();
922 if(key.startsWith("aaf_locator")) {
923 app.add(key, aaf_loc_prop.getValue().toString());
927 app.add(Config.AAF_APPID, fqi);
929 String cts = propAccess.getProperty(Config.CADI_TRUSTSTORE);
930 System.out.println("Passed in Truststore is " + cts);
932 File origTruststore = new File(cts);
933 File newTruststore = new File(app.getDir(),origTruststore.getName());
934 if(!newTruststore.exists()) {
935 if (!origTruststore.exists()) {
936 // Try same directory as cadi_prop_files
937 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
939 for (String f : Split.split(File.pathSeparatorChar, cpf)) {
940 File fcpf = new File(f);
942 int lastSep = cts.lastIndexOf(File.pathSeparator);
943 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
944 if (origTruststore.exists()) {
949 if (!origTruststore.exists()) {
950 throw new CadiException(cts + " does not exist");
955 if (!newTruststore.exists() && origTruststore.exists()) {
956 Files.copy(origTruststore.toPath(), newTruststore.toPath());
960 System.out.println("New Truststore is " + newTruststore);
961 cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath());
962 cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */);
964 String cpf = propAccess.getProperty(Config.CADI_PROP_FILES);
966 String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf);
967 for (int pfi = propFiles.length-1;pfi>=0;--pfi) {
968 String f = propFiles[pfi];
969 System.out.format("Reading %s\n",f);
970 FileInputStream fis = new FileInputStream(f);
972 Properties props = new Properties();
974 for (Entry<Object, Object> prop : props.entrySet()) {
975 boolean lower = true;
976 String key = prop.getKey().toString();
977 if(LOC_TAGS.contains(key)) {
980 for(int i=0;lower && i<key.length();++i) {
981 if(Character.isUpperCase(key.charAt(i))) {
986 PropHolder ph = CRED_TAGS.contains(key)?cred:app;
987 if(key.endsWith("_password")) {
988 ph.addEnc(key, prop.getValue().toString());
990 ph.add(key, prop.getValue().toString());
999 aafcon = aafcon(propAccess);
1000 if (aafcon!=null) { // get Properties from Remote AAF
1001 for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) {
1002 PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app;
1003 if(props.getTag().endsWith("_password")) {
1004 ph.addEnc(props.getTag(), props.getValue());
1006 ph.add(props.getTag(), props.getValue());
1014 PropHolder.writeAll();
1020 public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, URISyntaxException {
1021 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
1022 .read("/configure/"+fqi+"/aaf", configDF);
1023 if (acf.get(TIMEOUT)) {
1024 return acf.value.getProps();
1025 } else if (acf.code()==401){
1026 trans.error().log("Bad Password sent to AAF");
1027 } else if (acf.code()==404){
1028 trans.error().log("This version of AAF does not support remote Properties");
1030 trans.error().log(errMsg.toMsg(acf));
1032 return new ArrayList<>();
1035 private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
1036 System.out.println("Validating Configuration...");
1037 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
1038 aafcon.best(new Retryable<Void>() {
1040 public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
1041 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
1042 if (fc.get(aafcon.timeout)) {
1043 System.out.print("Success connecting to ");
1044 System.out.println(client.getURI());
1045 System.out.print(" Permissions for ");
1046 System.out.println(aafcon.defID());
1047 for (Perm p : fc.value.getPerm()) {
1048 System.out.print('\t');
1049 System.out.print(p.getType());
1050 System.out.print('|');
1051 System.out.print(p.getInstance());
1052 System.out.print('|');
1053 System.out.println(p.getAction());
1056 System.err.println("Error: " + fc.code() + ' ' + fc.body());
1064 * Check returns Error Codes, so that Scripts can know what to do
1066 * 0 - Check Complete, nothing to do
1068 * 2 - Error for specific Artifact - read check.msg
1069 * 10 - Certificate Updated - check.msg is email content
1077 private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
1079 String mechID = fqi(cmds);
1080 String machine = machine(cmds);
1082 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
1085 Future<Artifacts> acf = aafcon.client(CM_VER)
1086 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
1087 if (acf.get(TIMEOUT)) {
1088 // Have to wait for JDK 1.7 source...
1089 //switch(artifact.getType()) {
1090 if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1091 AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1093 String id = aafcon.defID();
1094 GregorianCalendar now = new GregorianCalendar();
1095 for (Artifact a : acf.value.getArtifact()) {
1096 if (id.equals(a.getMechid())) {
1097 File dir = new File(a.getDir());
1098 Properties props = new Properties();
1099 FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1109 if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1110 !(f=new File(prop)).exists()) {
1111 trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1112 a.getMechid(), a.getMachine());
1114 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1115 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1116 if (ksf==null || ksps == null) {
1117 trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1118 Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1120 Symm symm = ArtifactDir.getSymm(f);
1122 KeyStore ks = KeyStore.getInstance("JKS");
1124 fis = new FileInputStream(ksf);
1126 ks.load(fis,symm.depass(ksps).toCharArray());
1130 X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1134 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1135 a.getMechid(), a.getMachine(), ksf);
1136 trans.error().log(msg);
1139 GregorianCalendar renew = new GregorianCalendar();
1140 renew.setTime(cert.getNotAfter());
1141 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1142 if (renew.after(now)) {
1143 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",
1144 a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1145 trans.info().log(msg);
1148 trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n",
1149 a.getMechid(), a.getMachine(),cert.getNotAfter());
1150 cmds.offerLast(mechID);
1151 cmds.offerLast(machine);
1152 if (placeCerts(trans,aafcon,cmds)) {
1153 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n",
1154 a.getMechid(), a.getMachine());
1155 exitCode = 10; // Refreshed
1157 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n",
1158 a.getMechid(), a.getMachine());
1159 exitCode = 1; // Error Renewing
1164 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1166 fos.write(msg.getBytes());
1178 trans.error().log(errMsg.toMsg(acf));