add check and showpass
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / configure / Agent.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi.configure;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.PrintStream;
29 import java.net.ConnectException;
30 import java.net.HttpURLConnection;
31 import java.net.InetAddress;
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.Arrays;
39 import java.util.Date;
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;
45 import java.util.Map;
46 import java.util.Map.Entry;
47 import java.util.Properties;
48 import java.util.TreeMap;
49
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.Defaults;
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.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;
78
79 import aaf.v2_0.Perm;
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;
87
88 public class Agent {
89         private static final String HASHES = "################################################################";
90         private static final String PRINT = "print";
91         private static final String FILE = "file";
92         public static final String PKCS12 = "pkcs12";
93         public static final String JKS = "jks";
94         private static final String SCRIPT="script";
95         
96         private static final String CM_VER = "1.0";
97         public static final int PASS_SIZE = 24;
98         private static int TIMEOUT;
99         
100         private static RosettaDF<CertificateRequest> reqDF;
101         private static RosettaDF<CertInfo> certDF;
102         private static RosettaDF<Artifacts> artifactsDF;
103         private static RosettaDF<Configuration> configDF;
104         private static RosettaDF<Perms> permDF;
105         private static ErrMessage errMsg;
106         private static Map<String,PlaceArtifact> placeArtifact;
107         private static RosettaEnv env;
108         
109         private static boolean doExit;
110         private static AAFCon<?> aafcon;
111
112         public static void main(String[] args) {
113                 int exitCode = 0;
114                 doExit = true;
115                 if(args.length>0 && "cadi".equals(args[0])) {
116                         String[] newArgs = new String[args.length-1];
117                         System.arraycopy(args, 1, newArgs, 0, newArgs.length);
118                         if(newArgs.length==0) {
119                                 System.out.println(HASHES);
120                                 System.out.println("Note: Cadi CmdLine is a separate component.  When running with\n\t"
121                                                 + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]");
122                                 System.out.println(HASHES);
123                         }
124                         CmdLine.main(newArgs);
125                 } else {
126                         try {
127                                 AAFSSO aafsso=null;
128                                 PropAccess access;
129                                 
130                                 if(args.length>1 && args[0].equals("validate") ) {
131                                         int idx = args[1].indexOf('=');
132                                         aafsso = null;
133                                         access = new PropAccess(
134                                                                 (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+
135                                                                 '='+
136                                                             (idx<0?args[1]:args[1].substring(idx+1)));
137                                 } else {
138                                         aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() {
139                                                 @Override
140                                                 public Properties process(String[] args, Properties props) {
141                                                         if(args.length>1) {
142                                                                 if (!args[0].equals("keypairgen")) {
143                                                                         props.put("aaf_id", args[1]);
144                                                                 }       
145                                                         }
146                                                         return props;
147                                                 }
148                                         });
149                                         access = aafsso.access();
150                                 }
151                                         
152                                 if(aafsso!=null && aafsso.loginOnly()) {
153                                         aafsso.setLogDefault();
154                                         aafsso.writeFiles();
155                                         System.out.println("AAF SSO information created in ~/.aaf");
156                                 } else {
157                                         env = new RosettaEnv(access.getProperties());
158                                         Deque<String> cmds = new ArrayDeque<String>();
159                                         for(String p : args) {
160                                                 if("-noexit".equalsIgnoreCase(p)) {
161                                                         doExit = false;
162                                                 } else if(p.indexOf('=') < 0) {
163                                                         cmds.add(p);
164                                                 }
165                                         }
166                                         
167                                         if(cmds.size()==0) {
168                                                 if(aafsso!=null) {
169                                                         aafsso.setLogDefault();
170                                                 }
171                                                 // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not
172                                                 System.out.println("Usage: java -jar <cadi-aaf-*-full.jar> cmd [<tag=value>]*");
173                                                 System.out.println("   create     <FQI> [<machine>]");
174                                                 System.out.println("   read       <FQI> [<machine>]");
175                                                 System.out.println("   update     <FQI> [<machine>]");
176                                                 System.out.println("   delete     <FQI> [<machine>]");
177                                                 System.out.println("   copy       <FQI> <machine> <newmachine>[,<newmachine>]*");
178                                                 System.out.println("   place      <FQI> [<machine>]");
179                                                 System.out.println("   showpass   <FQI> [<machine>]");
180                                                 System.out.println("   check      <FQI> [<machine>]");
181                                                 System.out.println("   keypairgen <FQI>");
182                                                 System.out.println("   config     <FQI>");
183                                                 System.out.println("   validate   <NS>.props>");
184                                                 System.out.println("   --- Additional Tool Access ---");
185                                                 System.out.println("     ** Type with no params for Tool Help");
186                                                 System.out.println("     ** If using with Agent, preface with \"cadi\"");
187                                                 System.out.println("   cadi <cadi tool params, see -?>");
188                                                 
189                                                 if (doExit) {
190                                                         System.exit(1);
191                                                 }
192                                         }
193                                         
194                                         TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000"));
195                                 
196                                         reqDF = env.newDataFactory(CertificateRequest.class);
197                                         artifactsDF = env.newDataFactory(Artifacts.class);
198                                         certDF = env.newDataFactory(CertInfo.class);
199                                         configDF = env.newDataFactory(Configuration.class);
200                                         permDF = env.newDataFactory(Perms.class);
201                                         errMsg = new ErrMessage(env);
202                 
203                                         placeArtifact = new HashMap<>();
204                                         placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS));
205                                         placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12));
206                                         placeArtifact.put(FILE, new PlaceArtifactInFiles());
207                                         placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out));
208                                         placeArtifact.put(SCRIPT, new PlaceArtifactScripts());
209                                         
210                                         Trans trans = env.newTrans();
211                                         String token;
212                                         if((token=access.getProperty("oauth_token"))!=null) {
213                                                 trans.setProperty("oauth_token", token);
214                                         }
215                                         try {
216                                                 if(aafsso!=null) {
217                                                 // show Std out again
218                                                         aafsso.setLogDefault();
219                                                         aafsso.setStdErrDefault();
220                                                         
221                                                         // if CM_URL can be obtained, add to sso.props, if written
222                                                         String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": ");
223                                                         if(cm_url!=null) {
224                                                                 aafsso.addProp(Config.CM_URL, cm_url);
225                                                         }
226                                                         aafsso.writeFiles();
227                                                 }
228         
229                                                 
230         
231                                                 String cmd = cmds.removeFirst();
232                                                 switch(cmd) {
233                                                         case "place":
234                                                                 placeCerts(trans,aafcon(access),cmds);
235                                                                 break;
236                                                         case "create":
237                                                                 createArtifact(trans, aafcon(access),cmds);
238                                                                 break;
239                                                         case "read":
240                                                                 readArtifact(trans, aafcon(access), cmds);
241                                                                 break;
242                                                         case "copy":
243                                                                 copyArtifact(trans, aafcon(access), cmds);
244                                                                 break;
245                                                         case "update":
246                                                                 updateArtifact(trans, aafcon(access), cmds);
247                                                                 break;
248                                                         case "delete":
249                                                                 deleteArtifact(trans, aafcon(access), cmds);
250                                                                 break;
251                                                         case "showpass":
252                                                                 showPass(trans, aafcon(access), cmds);
253                                                                 break;
254                                                         case "keypairgen":
255                                                                 keypairGen(trans, access, cmds);
256                                                                 break;
257                                                         case "config":
258                                                                 if(access.getProperty(Config.CADI_PROP_FILES)!=null) {
259                                                                         // Get Properties from initialization Prop Files
260                                                                         config(trans,access,null,cmds);
261                                                                 } else {
262                                                                         // Get Properties from existing AAF Instance
263                                                                         config(trans,access,aafcon(access),cmds);
264                                                                 }
265                                                                 break;
266                                                         case "validate":
267                                                                 validate(access);
268                                                                 break;
269                                                         case "check":
270                                                                 try {
271                                                                         exitCode = check(trans,aafcon(access),cmds);
272                                                                 } catch (Exception e) {
273                                                                         exitCode = 1;
274                                                                         throw e;
275                                                                 }
276                                                                 break;
277                                                         default:
278                                                                 AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd);
279                                                 }
280                                         } finally {
281                                                 StringBuilder sb = new StringBuilder();
282                                 trans.auditTrail(4, sb, Trans.REMOTE);
283                                 if(sb.length()>0) {
284                                         trans.info().log("Trans Info\n",sb);
285                                 }
286                                         }
287                                         if(aafsso!=null) {
288                                                 aafsso.close();
289                                         }
290                                 }
291                         } catch (Exception e) {
292                                 e.printStackTrace();
293                         }
294                 }
295                 if(exitCode != 0 && doExit) {
296                         System.exit(exitCode);
297                 }
298         }
299
300         private static synchronized AAFCon<?> aafcon(PropAccess access) throws APIException, CadiException, LocatorException {
301                 if(aafcon==null) {
302                         aafcon = new AAFConHttp(access,Config.CM_URL);
303                 }
304                 return aafcon;
305         }
306
307         private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) {
308                 String value;
309                 if((value=pa.getProperty(tag))==null) {
310                         if(secure) {
311                                 value = new String(AAFSSO.cons.readPassword(prompt, def));
312                         } else {
313                                 value = AAFSSO.cons.readLine(prompt,def).trim();
314                         }
315                         if(value!=null) {
316                                 if(value.length()>0) {
317                                         pa.setProperty(tag,value);
318                                         env.setProperty(tag,value);
319                                 } else if(def.length==1) {
320                                         value=def[0].toString();
321                                         pa.setProperty(tag,value);
322                                         env.setProperty(tag,value);
323                                 }
324                         }
325                 }
326                 return value;
327         }
328
329         private static String fqi(Deque<String> cmds) {
330                 if(cmds.size()<1) {
331                         String alias = env.getProperty(Config.CADI_ALIAS);
332                         return alias!=null?alias:AAFSSO.cons.readLine("AppID: ");
333                 }
334                 return cmds.removeFirst();      
335         }
336
337         private static String machine(Deque<String> cmds) throws UnknownHostException {
338                 if(cmds.size()>0) {
339                         return cmds.removeFirst();
340                 } else {
341                         String mach = env.getProperty(Config.HOSTNAME);
342                         return mach!=null?mach:InetAddress.getLocalHost().getHostName();
343                 }
344         }
345
346         private static String[] machines(Deque<String> cmds)  {
347                 String machines;
348                 if(cmds.size()>0) {
349                         machines = cmds.removeFirst();
350                 } else {
351                         machines = AAFSSO.cons.readLine("Machines (sep by ','): ");
352                 }
353                 return Split.split(',', machines);
354         }
355
356         private static void createArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
357                 final String mechID = fqi(cmds);
358                 final String machine = machine(cmds);
359
360                 Artifacts artifacts = new Artifacts();
361                 Artifact arti = new Artifact();
362                 artifacts.getArtifact().add(arti);
363                 arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: "));
364                 arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName()));
365                 arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf"));
366                 
367                 String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12);
368                 for(String s : Split.splitTrim(',', resp)) {
369                         arti.getType().add(s);
370                 }
371                 // Always do Script
372                 if(!resp.contains(SCRIPT)) {
373                         arti.getType().add(SCRIPT);
374                 }
375
376                 // Note: Sponsor is set on Creation by CM
377                 String configRootName = FQI.reverseDomain(arti.getMechid());
378                 arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName));
379                 arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir")));
380                 arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name")));
381                 arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30")));
382                 arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", "")));
383                 
384                 TimeTaken tt = trans.start("Create Artifact", Env.REMOTE);
385                 try {
386                         Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts);
387                         if(future.get(TIMEOUT)) {
388                                 trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine());
389                         } else {
390                                 trans.error().printf("Call to AAF Certman failed, %s",
391                                         errMsg.toMsg(future));
392                         }
393                 } finally {
394                         tt.done();
395                 }
396         }
397
398         private static String toNotification(String notification) {
399                 if(notification==null) {
400                         notification="";
401                 } else if(notification.length()>0) {
402                         if(notification.indexOf(':')<0) {
403                                 notification = "mailto:" + notification;
404                         }
405                 }
406                 return notification;
407         }
408         
409
410         private static void readArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
411                 String mechID = fqi(cmds);
412                 String machine = machine(cmds);
413
414                 TimeTaken tt = trans.start("Read Artifact", Env.SUB);
415                 try {
416                         Future<Artifacts> future = aafcon.client(CM_VER)
417                                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token"));
418         
419                         if(future.get(TIMEOUT)) {
420                                 boolean printed = false;
421                                 for(Artifact a : future.value.getArtifact()) {
422                                         AAFSSO.cons.printf("AppID:          %s\n",a.getMechid()); 
423                                         AAFSSO.cons.printf("  Sponsor:       %s\n",a.getSponsor()); 
424                                         AAFSSO.cons.printf("Machine:         %s\n",a.getMachine()); 
425                                         AAFSSO.cons.printf("CA:              %s\n",a.getCa()); 
426                                         StringBuilder sb = new StringBuilder();
427                                         boolean first = true;
428                                         for(String t : a.getType()) {
429                                                 if(first) {first=false;}
430                                                 else{sb.append(',');}
431                                                 sb.append(t);
432                                         }
433                                         AAFSSO.cons.printf("Types:           %s\n",sb);
434                                         AAFSSO.cons.printf("Namespace:       %s\n",a.getNs()); 
435                                         AAFSSO.cons.printf("Directory:       %s\n",a.getDir());
436                                         AAFSSO.cons.printf("O/S User:        %s\n",a.getOsUser());
437                                         AAFSSO.cons.printf("Renew Days:      %d\n",a.getRenewDays());
438                                         AAFSSO.cons.printf("Notification     %s\n",a.getNotification());
439                                         printed = true;
440                                 }
441                                 if(!printed) {
442                                         AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine);
443                                 }
444                         } else {
445                                 trans.error().log(errMsg.toMsg(future));
446                         }
447                 } finally {
448                         tt.done();
449                 }
450         }
451         
452         private static void copyArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
453                 String mechID = fqi(cmds);
454                 String machine = machine(cmds);
455                 String[] newmachs = machines(cmds);
456                 if(machine==null || newmachs == null) {
457                         trans.error().log("No machines listed to copy to");
458                 } else {
459                         TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE);
460                         try {
461                                 Future<Artifacts> future = aafcon.client(CM_VER)
462                                                 .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
463                         
464                                 if(future.get(TIMEOUT)) {
465                                         boolean printed = false;
466                                         for(Artifact a : future.value.getArtifact()) {
467                                                 for(String m : newmachs) {
468                                                         a.setMachine(m);
469                                                         Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value);
470                                                         if(fup.get(TIMEOUT)) {
471                                                                 trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m);
472                                                         } else {
473                                                                 trans.error().printf("Call to AAF Certman failed, %s",
474                                                                         errMsg.toMsg(fup));
475                                                         }
476         
477                                                         printed = true;
478                                                 }
479                                         }
480                                         if(!printed) {
481                                                 AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
482                                         }
483                                 } else {
484                                         trans.error().log(errMsg.toMsg(future));
485                                 }
486                         } finally {
487                                 tt.done();
488                         }
489                 }
490         }
491
492         private static void updateArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
493                 String mechID = fqi(cmds);
494                 String machine = machine(cmds);
495
496                 TimeTaken tt = trans.start("Update Artifact", Env.REMOTE);
497                 try {
498                         Future<Artifacts> fread = aafcon.client(CM_VER)
499                                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
500         
501                         if(fread.get(TIMEOUT)) {
502                                 Artifacts artifacts = new Artifacts();
503                                 for(Artifact a : fread.value.getArtifact()) {
504                                         Artifact arti = new Artifact();
505                                         artifacts.getArtifact().add(arti);
506                                         
507                                         AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine());
508                                         arti.setMechid(a.getMechid());
509                                         arti.setMachine(a.getMachine());
510                                         arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa()));
511                                         StringBuilder sb = new StringBuilder();
512                                         boolean first = true;
513                                         for(String t : a.getType()) {
514                                                 if(first) {first=false;}
515                                                 else{sb.append(',');}
516                                                 sb.append(t);
517                                         }
518         
519                                         String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb);
520                                         for(String s : Split.splitTrim(',', resp)) {
521                                                 arti.getType().add(s);
522                                         }
523                                         // Always do Script
524                                         if(!resp.contains(SCRIPT)) {
525                                                 arti.getType().add(SCRIPT);
526                                         }
527
528                                         // Note: Sponsor is set on Creation by CM
529                                         arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs()));
530                                         arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir()));
531                                         arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser()));
532                                         arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays())));
533                                         arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification())));
534         
535                                 }
536                                 if(artifacts.getArtifact().size()==0) {
537                                         AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine);
538                                 } else {
539                                         Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts);
540                                         if(fup.get(TIMEOUT)) {
541                                                 trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine);
542                                         } else {
543                                                 trans.error().printf("Call to AAF Certman failed, %s",
544                                                         errMsg.toMsg(fup));
545                                         }
546                                 }
547                         } else {
548                                 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
549                                                 errMsg.toMsg(fread),mechID,machine);
550                         }
551                 } finally {
552                         tt.done();
553                 }
554         }
555         
556         private static void deleteArtifact(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
557                 String mechid = fqi(cmds);
558                 String machine = machine(cmds);
559                 
560                 TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE);
561                 try {
562                         Future<Void> future = aafcon.client(CM_VER)
563                                         .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" );
564         
565                         if(future.get(TIMEOUT)) {
566                                 trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine);
567                         } else {
568                                 trans.error().printf("Call to AAF Certman failed, %s %s, %s",
569                                         errMsg.toMsg(future),mechid,machine);
570                         }
571                 } finally {
572                         tt.done();
573                 }
574         }
575
576         
577
578         private static boolean placeCerts(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
579                 boolean rv = false;
580                 String mechID = fqi(cmds);
581                 String machine = machine(cmds);
582                 String[] fqdns = Split.split(':', machine);
583                 String key;
584                 if(fqdns.length>1) {
585                         key = fqdns[0];
586                         machine = fqdns[1];
587                 } else {
588                         key = machine;
589                 }
590                 
591                 TimeTaken tt = trans.start("Place Artifact", Env.REMOTE);
592                 try {
593                         Future<Artifacts> acf = aafcon.client(CM_VER)
594                                         .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF);
595                         if(acf.get(TIMEOUT)) {
596                                 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
597                                         AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key);
598                                 } else {
599                                         for(Artifact a : acf.value.getArtifact()) {
600                                                 String osID = System.getProperty("user.name");
601                                                 if(a.getOsUser().equals(osID)) {
602                                                         CertificateRequest cr = new CertificateRequest();
603                                                         cr.setMechid(a.getMechid());
604                                                         cr.setSponsor(a.getSponsor());
605                                                         for(int i=0;i<fqdns.length;++i) {
606                                                                 cr.getFqdns().add(fqdns[i]);
607                                                         }
608                                                         Future<String> f = aafcon.client(CM_VER)
609                                                                         .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr);
610                                                         if(f.get(TIMEOUT)) {
611                                                                 CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject();
612                                                                 for(String type : a.getType()) {
613                                                                         PlaceArtifact pa = placeArtifact.get(type);
614                                                                         if(pa!=null) {
615                                                                                 if(rv = pa.place(trans, capi, a,machine)) {
616                                                                                         notifyPlaced(a,rv);
617                                                                                 }
618                                                                         }
619                                                                 }
620                                                                 // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact
621                                                         } else {
622                                                                 trans.error().log(errMsg.toMsg(f));
623                                                         }
624                                                 } else {
625                                                         trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box");
626                                                 }
627                                         }
628                                 }
629                         } else {
630                                 trans.error().log(errMsg.toMsg(acf));
631                         }
632                 } finally {
633                         tt.done();
634                 }
635                 return rv;
636         }
637         
638         private static void notifyPlaced(Artifact a, boolean rv) {
639         }
640
641         private static void showPass(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
642                 String mechID = fqi(cmds);
643                 String machine = machine(cmds);
644
645                 TimeTaken tt = trans.start("Show Password", Env.REMOTE);
646                 try {
647                         Future<Artifacts> acf = aafcon.client(CM_VER)
648                                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
649                         if(acf.get(TIMEOUT)) {
650                                 // Have to wait for JDK 1.7 source...
651                                 //switch(artifact.getType()) {
652                                 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
653                                         AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine);
654                                 } else {
655                                         String id = aafcon.defID();
656                                         boolean allowed;
657                                         for(Artifact a : acf.value.getArtifact()) {
658                                                 allowed = id!=null && (id.equals(a.getSponsor()) ||
659                                                                 (id.equals(a.getMechid()) 
660                                                                                 && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class)));
661                                                 if(!allowed) {
662                                                         Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" + 
663                                                                         a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*");
664                                                         if(pf.get(TIMEOUT)) {
665                                                                 allowed = true;
666                                                         } else {
667                                                                 trans.error().log(errMsg.toMsg(pf));
668                                                         }
669                                                 }
670                                                 if(allowed) {
671                                                         File dir = new File(a.getDir());
672                                                         Properties props = new Properties();
673                                                         FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props"));
674                                                         try {
675                                                                 props.load(fis);
676                                                                 fis.close();
677                                                                 fis = new FileInputStream(new File(dir,a.getNs()+".chal"));
678                                                                 props.load(fis);
679                                                         } finally {
680                                                                 fis.close();
681                                                         }
682                                                         
683                                                         File f = new File(dir,a.getNs()+".keyfile");
684                                                         if(f.exists()) {
685                                                                 Symm symm = Symm.obtain(f);
686                                                                 
687                                                                 for(Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) {
688                                                                         Entry<Object,Object> en = iter.next();
689                                                                         if(en.getValue().toString().startsWith("enc:")) {
690                                                                                 System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString()));
691                                                                         }
692                                                                 }
693                                                         } else {
694                                                                 trans.error().printf("%s.keyfile must exist to read passwords for %s on %s",
695                                                                                 f.getAbsolutePath(),a.getMechid(), a.getMachine());
696                                                         }
697                                                 }
698                                         }
699                                 }
700                         } else {
701                                 trans.error().log(errMsg.toMsg(acf));
702                         }
703                 } finally {
704                         tt.done();
705                 }
706
707         }
708         
709         private static void keypairGen(final Trans trans, final PropAccess access, final Deque<String> cmds) throws IOException {
710                 final String fqi = fqi(cmds);
711                 final String ns = FQI.reverseDomain(fqi);
712                 File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory
713                 File f = new File(dir,ns+".key");
714                 
715                 if(f.exists()) {
716                         String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath());
717                         if(!"Y".equalsIgnoreCase(line)) {
718                                 System.out.println("Canceling...");
719                                 return;
720                         }
721                 }
722                 
723                 KeyPair kp = Factory.generateKeyPair(trans);
724                 ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate()));
725                 System.out.printf("Wrote %s\n", f.getCanonicalFile());
726
727                 f=new File(dir,ns+".pubkey");
728                 ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic()));
729                 System.out.printf("Wrote %s\n", f.getCanonicalFile());
730         }
731         
732         private static void config(Trans trans, PropAccess pa, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
733                 final String fqi = fqi(cmds);
734                 final String rootFile = FQI.reverseDomain(fqi);
735                 final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, "."));
736                 if(dir.exists()) {
737                         System.out.println("Writing to " + dir.getCanonicalFile());
738                 } else if(dir.mkdirs()) {
739                         System.out.println("Created directory " + dir.getCanonicalFile());
740                 } else {
741                         System.err.println("Unable to create or write to " + dir.getCanonicalPath());
742                         return;
743                 }
744                 
745                 TimeTaken tt = trans.start("Get Configuration", Env.REMOTE);
746                 try {
747                         boolean ok=false;
748                         File fProps = File.createTempFile(rootFile, ".tmp",dir);
749                         File fSecureTempProps = File.createTempFile(rootFile, ".cred.tmp",dir);
750                         File fSecureProps = new File(dir,rootFile+".cred.props");
751                         PrintStream psProps;
752
753                         File fLocProps = new File(dir,rootFile + ".location.props");
754                         if(!fLocProps.exists()) {
755                                 psProps = new PrintStream(new FileOutputStream(fLocProps));
756                                 try {
757                                         psProps.println(HASHES);
758                                         psProps.print("# Configuration File generated on ");
759                                         psProps.println(new Date().toString());
760                                         psProps.println(HASHES);
761                                         for(String tag : LOC_TAGS) {
762                                                 psProps.print(tag);
763                                                 psProps.print('=');
764                                                 psProps.println(getProperty(pa, trans, false, tag, "%s: ",tag));
765                                         }
766                                 } finally {
767                                         psProps.close();
768                                 }
769                         }
770
771                         psProps = new PrintStream(new FileOutputStream(fProps));
772                         try {
773                                 PrintStream psCredProps = new PrintStream(new FileOutputStream(fSecureTempProps));
774                                 try {
775                                         psCredProps.println(HASHES);
776                                         psCredProps.print("# Configuration File generated on ");
777                                         psCredProps.println(new Date().toString());
778                                         psCredProps.println(HASHES);
779
780                                         psProps.println(HASHES);
781                                         psProps.print("# Configuration File generated on ");
782                                         psProps.println(new Date().toString());
783                                         psProps.println(HASHES);
784                                         
785                                         psProps.print(Config.CADI_PROP_FILES);
786                                         psProps.print('=');
787                                         psProps.print(fSecureProps.getCanonicalPath());
788                                         psProps.print(File.pathSeparatorChar);
789                                         psProps.println(fLocProps.getCanonicalPath());
790                                         
791                                         File fkf = new File(dir,rootFile+".keyfile");
792                                         if(!fkf.exists()) {
793                                                 CmdLine.main(new String[] {"keygen",fkf.toString()});
794                                         }
795                                         Symm filesymm = Symm.obtain(fkf);
796                                         Map<String,String> normal = new TreeMap<>();
797                                         Map<String,String> creds = new TreeMap<>();
798
799                                         directedPut(pa, filesymm, normal,creds, Config.CADI_KEYFILE, fkf.getCanonicalPath());
800                                         directedPut(pa, filesymm, normal,creds, Config.AAF_APPID,fqi);
801                                         directedPut(pa, filesymm, normal,creds, Config.AAF_APPPASS,null);
802                                         directedPut(pa, filesymm, normal,creds, Config.AAF_URL, Defaults.AAF_URL);
803                                         
804
805                                         String cts = pa.getProperty(Config.CADI_TRUSTSTORE);
806                                         if(cts!=null) {
807                                                 File origTruststore = new File(cts);
808                                                 if(!origTruststore.exists()) {
809                                                         // Try same directory as cadi_prop_files
810                                                         String cpf = pa.getProperty(Config.CADI_PROP_FILES);
811                                                         if(cpf!=null) {
812                                                                 for(String f : Split.split(File.pathSeparatorChar, cpf)) {
813                                                                         File fcpf = new File(f);
814                                                                         if(fcpf.exists()) {
815                                                                                 int lastSep = cts.lastIndexOf(File.pathSeparator);
816                                                                                 origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts);
817                                                                                 if(origTruststore.exists()) { 
818                                                                                         break;
819                                                                                 }
820                                                                         }
821                                                                 }
822                                                                 if(!origTruststore.exists()) {
823                                                                         throw new CadiException(cts + " does not exist");
824                                                                 }
825                                                         }
826                                                         
827                                                 }
828                                                 File newTruststore = new File(dir,origTruststore.getName());
829                                                 if(!newTruststore.exists()) {
830                                                         Files.copy(origTruststore.toPath(), newTruststore.toPath());
831                                                 }
832                                                 
833                                                 directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE,newTruststore.getCanonicalPath());
834                                                 directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE_PASSWORD,null);
835                                         }
836                                         
837                                         if(aafcon!=null) { // get Properties from Remote AAF
838                                                 final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: ");
839
840                                                 Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator))
841                                                                 .read("/configure/"+fqi+"/aaf", configDF);
842                                                 if(acf.get(TIMEOUT)) {
843                                                         for(Props props : acf.value.getProps()) {
844                                                                 directedPut(pa, filesymm, normal,creds, props.getTag(),props.getValue());                                       
845                                                         }
846                                                         ok = true;
847                                                 } else if(acf.code()==401){
848                                                         trans.error().log("Bad Password sent to AAF");
849                                                 } else {
850                                                         trans.error().log(errMsg.toMsg(acf));
851                                                 }
852                                         } else {
853                                                 String cpf = pa.getProperty(Config.CADI_PROP_FILES);
854                                                 if(cpf!=null){
855                                                         for(String f : Split.split(File.pathSeparatorChar, cpf)) {
856                                                                 System.out.format("Reading %s\n",f);
857                                                                 FileInputStream fis = new FileInputStream(f); 
858                                                                 try {
859                                                                         Properties props = new Properties();
860                                                                         props.load(fis);
861                                                                         for(Entry<Object, Object> prop : props.entrySet()) {
862                                                                                 directedPut(pa, filesymm, normal,creds, prop.getKey().toString(),prop.getValue().toString());
863                                                                         }
864                                                                 } finally {
865                                                                         fis.close();
866                                                                 }
867                                                         }
868                                                 }
869                                                 ok = true;
870                                         }
871                                         if(ok) {
872                                                 for(Entry<String, String> es : normal.entrySet()) {
873                                                         psProps.print(es.getKey());
874                                                         psProps.print('=');
875                                                         psProps.println(es.getValue());
876                                                 }
877                                                 
878                                                 for(Entry<String, String> es : creds.entrySet()) {
879                                                         psCredProps.print(es.getKey());
880                                                         psCredProps.print('=');
881                                                         psCredProps.println(es.getValue());
882                                                 }
883                                                 
884                                                 File newFile = new File(dir,rootFile+".props");
885                                                 if(newFile.exists()) {
886                                                         File backup = new File(dir,rootFile+".props.backup");
887                                                         newFile.renameTo(backup);
888                                                         System.out.println("Backed up to " + backup.getCanonicalPath());
889                                                 }
890                                                 fProps.renameTo(newFile);
891                                                 System.out.println("Created " + newFile.getCanonicalPath());
892                                                 fProps = newFile;
893                                                 
894                                                 if(fSecureProps.exists()) {
895                                                         File backup = new File(dir,fSecureProps.getName()+".backup");
896                                                         fSecureProps.renameTo(backup);
897                                                         System.out.println("Backed up to " + backup.getCanonicalPath());
898                                                 }
899                                                 fSecureTempProps.renameTo(fSecureProps);
900                                                 System.out.println("Created " + fSecureProps.getCanonicalPath());
901                                                 fProps = newFile;
902                                         } else {
903                                                 fProps.delete();
904                                                 fSecureTempProps.delete();
905                                         }
906                                 } finally {
907                                         psCredProps.close();
908                                 }
909                         } finally {
910                                 psProps.close();
911                         }
912                 } finally {
913                         tt.done();
914                 }
915         }
916
917         private static List<String> CRED_TAGS = Arrays.asList(new String[] {
918                         Config.CADI_KEYFILE,
919                         Config.AAF_APPID, Config.AAF_APPPASS,
920                         Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD,
921                         Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD,
922                         Config.CADI_ALIAS, Config.CADI_X509_ISSUERS
923                         });
924
925         private static List<String> LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE});
926         
927         private static void directedPut(final PropAccess orig, final Symm symm, final Map<String,String> main, final Map<String,String> secured, final String tag, final String value) throws IOException {
928                 if(!LOC_TAGS.contains(tag)) { // Location already covered
929                         String val = value==null?orig.getProperty(tag):value;
930                         if(tag.endsWith("_password")) {
931                                 if(val.length()>4) {
932                                         if(val.startsWith("enc:")) {
933                                                 val = orig.decrypt(val, true);
934                                         }
935                                         val = "enc:" + symm.enpass(val);
936                                 }
937                         }
938                         if(CRED_TAGS.contains(tag)) {
939                                 secured.put(tag, val);
940                         } else {
941                                 main.put(tag, val);
942                         }
943                 }
944         }
945
946         private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException {
947                 System.out.println("Validating Configuration...");
948                 final AAFCon<?> aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC<HttpURLConnection>(pa));
949                 aafcon.best(new Retryable<Void>() {
950                         @Override
951                         public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException {
952                                 Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF);
953                                 if(fc.get(aafcon.timeout)) {
954                                         System.out.print("Success connecting to ");
955                                         System.out.println(client.getURI());
956                                         System.out.print("   Permissions for ");
957                                         System.out.println(aafcon.defID());
958                                         for(Perm p : fc.value.getPerm()) {
959                                                 System.out.print('\t');
960                                                 System.out.print(p.getType());
961                                                 System.out.print('|');
962                                                 System.out.print(p.getInstance());
963                                                 System.out.print('|');
964                                                 System.out.println(p.getAction());
965                                         }
966                                 } else {
967                                         System.err.println("Error: " + fc.code() + ' ' + fc.body());
968                                 }
969                                 return null;
970                         }
971                 });
972         }
973
974         /**
975          * Check returns Error Codes, so that Scripts can know what to do
976          * 
977          *   0 - Check Complete, nothing to do
978          *   1 - General Error
979          *   2 - Error for specific Artifact - read check.msg
980          *   10 - Certificate Updated - check.msg is email content
981          *   
982          * @param trans
983          * @param aafcon
984          * @param cmds
985          * @return
986          * @throws Exception
987          */
988         private static int check(Trans trans, AAFCon<?> aafcon, Deque<String> cmds) throws Exception {
989                 int exitCode=1;
990                 String mechID = fqi(cmds);
991                 String machine = machine(cmds);
992                 
993                 TimeTaken tt = trans.start("Check Certificate", Env.REMOTE);
994                 try {
995                 
996                         Future<Artifacts> acf = aafcon.client(CM_VER)
997                                         .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF);
998                         if(acf.get(TIMEOUT)) {
999                                 // Have to wait for JDK 1.7 source...
1000                                 //switch(artifact.getType()) {
1001                                 if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) {
1002                                         AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine);
1003                                 } else {
1004                                         String id = aafcon.defID();
1005                                         GregorianCalendar now = new GregorianCalendar();
1006                                         for(Artifact a : acf.value.getArtifact()) {
1007                                                 if(id.equals(a.getMechid())) {
1008                                                         File dir = new File(a.getDir());
1009                                                         Properties props = new Properties();
1010                                                         FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props"));
1011                                                         try {
1012                                                                 props.load(fis);
1013                                                         } finally {
1014                                                                 fis.close();
1015                                                         }
1016                                                         
1017                                                         String prop;                                            
1018                                                         File f;
1019         
1020                                                         if((prop=trans.getProperty(Config.CADI_KEYFILE))==null ||
1021                                                                 !(f=new File(prop)).exists()) {
1022                                                                         trans.error().printf("Keyfile must exist to check Certificates for %s on %s",
1023                                                                                 a.getMechid(), a.getMachine());
1024                                                         } else {
1025                                                                 String ksf = trans.getProperty(Config.CADI_KEYSTORE);
1026                                                                 String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD);
1027                                                                 if(ksf==null || ksps == null) {
1028                                                                         trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s",
1029                                                                                         Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine());
1030                                                                 } else {
1031                                                                         KeyStore ks = KeyStore.getInstance("JKS");
1032                                                                         Symm symm = Symm.obtain(f);
1033                                                                         
1034                                                                         fis = new FileInputStream(ksf);
1035                                                                         try {
1036                                                                                 ks.load(fis,symm.depass(ksps).toCharArray());
1037                                                                         } finally {
1038                                                                                 fis.close();
1039                                                                         }
1040                                                                         X509Certificate cert = (X509Certificate)ks.getCertificate(mechID);
1041                                                                         String msg = null;
1042
1043                                                                         if(cert==null) {
1044                                                                                 msg = String.format("X509Certificate does not exist for %s on %s in %s",
1045                                                                                                 a.getMechid(), a.getMachine(), ksf);
1046                                                                                 trans.error().log(msg);
1047                                                                                 exitCode = 2;
1048                                                                         } else {
1049                                                                                 GregorianCalendar renew = new GregorianCalendar();
1050                                                                                 renew.setTime(cert.getNotAfter());
1051                                                                                 renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays());
1052                                                                                 if(renew.after(now)) {
1053                                                                                         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", 
1054                                                                                                         a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew));
1055                                                                                         trans.info().log(msg);
1056                                                                                         exitCode = 0; // OK
1057                                                                                 } else {
1058                                                                                         trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n", 
1059                                                                                                         a.getMechid(), a.getMachine(),cert.getNotAfter());
1060                                                                                         cmds.offerLast(mechID);
1061                                                                                         cmds.offerLast(machine);
1062                                                                                         if(placeCerts(trans,aafcon,cmds)) {
1063                                                                                                 msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n", 
1064                                                                                                                 a.getMechid(), a.getMachine());
1065                                                                                                 exitCode = 10; // Refreshed
1066                                                                                         } else {
1067                                                                                                 msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n", 
1068                                                                                                                 a.getMechid(), a.getMachine());
1069                                                                                                 exitCode = 1; // Error Renewing
1070                                                                                         }
1071                                                                                 }
1072                                                                         }
1073                                                                         if(msg!=null) {
1074                                                                                 FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg");
1075                                                                                 try {
1076                                                                                         fos.write(msg.getBytes());
1077                                                                                 } finally {
1078                                                                                         fos.close();
1079                                                                                 }
1080                                                                         }
1081                                                                 }
1082                                                                 
1083                                                         }
1084                                                 }
1085                                         }
1086                                 }
1087                         } else {
1088                                 trans.error().log(errMsg.toMsg(acf));
1089                                 exitCode=1;
1090                         }
1091                 } finally {
1092                         tt.done();
1093                 }
1094                 return exitCode;
1095         }
1096
1097 }
1098                         
1099                 
1100
1101