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