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