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