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