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