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