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