View Javadoc
1   /**
2    * This Source Code Form is subject to the terms of the Mozilla Public
3    * License, v. 2.0. If a copy of the MPL was not distributed with this
4    * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5    *
6    * If it is not possible or desirable to put the notice in a particular
7    * file, then You may include the notice in a location (such as a LICENSE
8    * file in a relevant directory) where a recipient would be likely to look
9    * for such a notice.
10  
11   * 
12   */
13   
14  /*  ---------------------------------------------------------------------------
15   *  U.S. Government, Department of the Army
16   *  Army Materiel Command
17   *  Research Development Engineering Command
18   *  Communications Electronics Research Development and Engineering Center
19   *  ---------------------------------------------------------------------------
20   */
21  package org.miloss.fgsms.agentcore;
22  
23  import java.io.*;
24  import java.util.Map;
25  import javax.xml.bind.JAXBContext;
26  import javax.xml.bind.JAXBElement;
27  import javax.xml.bind.Unmarshaller;
28  import javax.xml.stream.XMLInputFactory;
29  import javax.xml.stream.XMLStreamReader;
30  import javax.xml.ws.BindingProvider;
31  import org.miloss.fgsms.common.Utility;
32  
33  import org.miloss.fgsms.services.interfaces.common.PolicyType;
34  import org.miloss.fgsms.services.interfaces.common.SecurityWrapper;
35  import org.miloss.fgsms.services.interfaces.policyconfiguration.GetGlobalPolicyRequestMsg;
36  import org.miloss.fgsms.services.interfaces.policyconfiguration.GetGlobalPolicyResponseMsg;
37  import org.miloss.fgsms.services.interfaces.policyconfiguration.GlobalPolicy;
38  import org.miloss.fgsms.services.interfaces.policyconfiguration.ServicePolicy;
39  import org.miloss.fgsms.services.interfaces.policyconfiguration.ServicePolicyRequestMsg;
40  import org.miloss.fgsms.services.interfaces.policyconfiguration.ServicePolicyResponseMsg;
41  import org.miloss.fgsms.services.interfaces.policyconfiguration.StatisticalServicePolicy;
42  import org.miloss.fgsms.services.interfaces.policyconfiguration.TransactionalWebServicePolicy;
43  import org.apache.log4j.Level;
44  import org.miloss.fgsms.common.Logger;;
45  import org.miloss.fgsms.common.Constants;
46  import us.gov.ic.ism.v2.ClassificationType;
47  
48  /**
49   * Provides some useful functions for building agents.. All functions
50   * use the fgsms-agent.properties file within this JAR for configuration
51   * purposes All functions support discovery mechanisms, retry counts,
52   * failover/roundrobin
53   *
54   * @author AO
55   */
56  public class PolicyFetch extends HelperBase{
57  
58      static ConfigLoader cfg = null;
59  
60      private static void Init() throws ConfigurationException {
61          if (cfg == null) {
62              cfg = new ConfigLoader();
63          }
64  
65      }
66  
67      static Logger log = Logger.getLogger(org.miloss.fgsms.common.Constants.LoggerName);
68  
69      /**
70       * * Attempts to retrieve the current global policy from the fgsms server
71       * A successful return typically indicates that the server is up and
72       * running.
73       *
74       * @since 6.3
75       * @return A non-null global policy if successful. Null if not successful
76       * @throws ConfigurationException
77       */
78      public static GlobalPolicy TryFetchGlobalPolicy() throws ConfigurationException {
79          if (cfg == null) {
80              Init();
81          }
82          discoverEndpoints();
83          int retrycount = 0;
84          int urlcount = 0;
85          switch (cfg.PCSalgo) {
86              case FAILOVER:
87                  retrycount = 0;
88                  urlcount = 0;
89                  while ((retrycount < cfg.PCSRetryCount)) {
90  
91                      urlcount = 0;
92                      while (urlcount < cfg.PCS_URLS.size()) {
93                          try { // Call Web Service Operation
94  
95                              BindingProvider bp = (BindingProvider) cfg.pcsport;
96                              Map<String, Object> context = bp.getRequestContext();
97                              //    context.remove(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
98                              context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, cfg.PCS_URLS.get(urlcount));
99                              if (cfg.mode_ == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
100                                 context.put(BindingProvider.USERNAME_PROPERTY, cfg.username);
101                                 context.put(BindingProvider.PASSWORD_PROPERTY, Utility.DE(cfg.password));
102                             }
103                             if (Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.trustStore")) && !Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.trustStorePassword"))) {
104                                 context.put("javax.net.ssl.trustStorePassword", Utility.DE(cfg.getJavaxtruststorepass()));
105                                 context.put("javax.net.ssl.trustStore", Utility.DE(cfg.getJavaxtruststore()));
106                             }
107                             try {
108                                 if (cfg.mode_ == org.miloss.fgsms.common.Constants.AuthMode.PKI) {
109                                     if (Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.keyStore")) && !Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.keyStorePassword"))) {
110                                         context.put("javax.net.ssl.keyStorePassword", Utility.DE(cfg.getJavaxkeystorepass()));
111                                         context.put("javax.net.ssl.keyStore", Utility.DE(cfg.getJavaxkeystore()));
112                                     }
113                                 }
114 
115                             } catch (Exception ex) {
116                                 log.log(Level.FATAL, "error caught when referencing (get or set) System.properties for SSL communication. Check to ensure that this is enabled in your JAAS managemer", ex);
117                             }
118                             //send it
119                             GetGlobalPolicyRequestMsg req = new GetGlobalPolicyRequestMsg();
120                             req.setClassification(new SecurityWrapper(ClassificationType.U, "none"));
121                             GetGlobalPolicyResponseMsg servicePolicy = cfg.pcsport.getGlobalPolicy(req);
122 
123                             return servicePolicy.getPolicy();
124 
125 
126                         } catch (Exception ex) {
127                             log.log(Level.WARN, "fgsms unable to fetch policy from PCS at " + cfg.PCS_URLS.get(urlcount) + " will retry " + (cfg.PCSRetryCount - retrycount) + " times." + ex.getMessage(), ex);
128                         }
129                         urlcount++;
130                     }
131                     retrycount++;
132                 }
133 
134                 log.log(Level.FATAL, "fgsms unable to fetch policy from any of the PCS[" + cfg.PCS_URLS.size() + "] URLs, retry count exceeded. Falling back to default policy");
135                 return null;
136             case ROUNDROBIN:
137                 retrycount = 0;
138                 urlcount = 0;
139                 while ((retrycount < cfg.PCSRetryCount)) {
140 
141                     urlcount = 0;
142                     while (urlcount < cfg.PCS_URLS.size()) {
143                         try { // Call Web Service Operation
144 
145                             BindingProvider bp = (BindingProvider) cfg.pcsport;
146                             Map<String, Object> context = bp.getRequestContext();
147                             //    context.remove(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
148                             context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, cfg.PCS_URLS.get(urlcount));
149 //                            StubExt sec = (StubExt) pcsport;
150                             if (cfg.mode_ == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
151 //                                sec.setSecurityConfig("/META-INF/fgsms-username-config.xml");
152                                 context.put(BindingProvider.USERNAME_PROPERTY, cfg.username);
153                                 context.put(BindingProvider.PASSWORD_PROPERTY, Utility.DE(cfg.password));
154                             }
155                             if (cfg.mode_ == org.miloss.fgsms.common.Constants.AuthMode.PKI) {
156                                 if (Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.keyStore")) && !Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.keyStorePassword"))) {
157                                     System.setProperty("javax.net.ssl.keyStorePassword", Utility.DE(cfg.getJavaxkeystorepass()));
158                                     System.setProperty("javax.net.ssl.keyStore", Utility.DE(cfg.getJavaxkeystore()));
159                                 }
160                             }
161                             if (Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.trustStore")) && !Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.trustStorePassword"))) {
162                                 System.setProperty("javax.net.ssl.trustStorePassword", Utility.DE(cfg.getJavaxtruststorepass()));
163                                 System.setProperty("javax.net.ssl.trustStore", Utility.DE(cfg.getJavaxtruststore()));
164                             }
165                             //send it
166                             GetGlobalPolicyRequestMsg req = new GetGlobalPolicyRequestMsg();
167                             req.setClassification(new SecurityWrapper(ClassificationType.U, "none"));
168                             GetGlobalPolicyResponseMsg servicePolicy = cfg.pcsport.getGlobalPolicy(req);
169 
170                             return servicePolicy.getPolicy();
171 
172                         } catch (Exception ex) {
173                             log.log(Level.WARN, "fgsms unable to fetch policy from PCS at " + cfg.PCS_URLS.get(urlcount) + " will retry " + (cfg.PCSRetryCount - retrycount) + " times." + ex.getMessage(), ex);
174                         }
175                         urlcount++;
176                     }
177                     retrycount++;
178                 }
179 
180                 log.log(Level.FATAL, "fgsms unable to fetch policy from any of the PCS[" + cfg.PCS_URLS.size() + "] URLs, retry count exceeded.");
181                 return null;
182 
183         }
184         return null;
185     }
186 
187     /**
188      * Gets a service policy from the fgsms server under the context of the an
189      * agent meaning that if the policy does not exist, it will be created. Will
190      * use discovery and retry logic if configured for it.
191      *
192      * @param URI
193      * @param policyType
194      * @param domainname
195      * @param hostname
196      * @return
197      * @throws ConfigurationException
198      */
199     public static ServicePolicy TryFetchPolicy(String URI, PolicyType policyType, String domainname, String hostname) throws ConfigurationException {
200         if (cfg == null) {
201             Init();
202         }
203         discoverEndpoints();
204 
205         ServicePolicyRequestMsg req = new ServicePolicyRequestMsg();
206         req.setClassification(cfg.classlevel);
207         req.setDomain(domainname);
208         req.setURI(URI);
209         req.setPolicytype(policyType);
210 
211         if (Utility.stringIsNullOrEmpty(hostname)) {
212             req.setMachine(Utility.getHostName());
213         } else {
214             req.setMachine(hostname);
215         }
216 
217         try {
218 
219             return Send(req);
220         } catch (Exception ex) {
221             log.log(Level.ERROR, "could not retrieve a policy for the specified url", ex);
222             return null;
223         }
224     }
225 
226     private static ServicePolicy Send(ServicePolicyRequestMsg req) throws ConfigurationException {
227         if (cfg == null) {
228             Init();
229         }
230         int retrycount = 0;
231         int urlcount = 0;
232         switch (cfg.PCSalgo) {
233             case FAILOVER:
234                 retrycount = 0;
235                 urlcount = 0;
236                 while ((retrycount < cfg.PCSRetryCount)) {
237 
238                     urlcount = 0;
239                     while (urlcount < cfg.PCS_URLS.size()) {
240                         try { // Call Web Service Operation
241 
242                             BindingProvider bp = (BindingProvider) cfg.pcsport;
243                             Map<String, Object> context = bp.getRequestContext();
244                             //    context.remove(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
245                             context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, cfg.PCS_URLS.get(urlcount));
246                             if (cfg.mode_ == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
247                                 context.put(BindingProvider.USERNAME_PROPERTY, cfg.username);
248                                 context.put(BindingProvider.PASSWORD_PROPERTY, Utility.DE(cfg.password));
249                             }
250                             if (Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.trustStore")) && !Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.trustStorePassword"))) {
251                                 context.put("javax.net.ssl.trustStorePassword", Utility.DE(cfg.getJavaxtruststorepass()));
252                                 context.put("javax.net.ssl.trustStore", Utility.DE(cfg.getJavaxtruststore()));
253                             }
254                             try {
255                                 if (cfg.mode_ == org.miloss.fgsms.common.Constants.AuthMode.PKI) {
256                                     if (Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.keyStore")) && !Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.keyStorePassword"))) {
257                                         context.put("javax.net.ssl.keyStorePassword", Utility.DE(cfg.getJavaxkeystorepass()));
258                                         context.put("javax.net.ssl.keyStore", Utility.DE(cfg.getJavaxkeystore()));
259                                     }
260                                 }
261 
262                             } catch (Exception ex) {
263                                 log.log(Level.FATAL, "error caught when referencing (get or set) System.properties for SSL communication. Check to ensure that this is enabled in your JAAS managemer", ex);
264                             }
265                             //send it
266                             ServicePolicyResponseMsg servicePolicy = cfg.pcsport.getServicePolicy(req);
267                             cfg.classlevel = servicePolicy.getClassification();
268                             return servicePolicy.getPolicy();
269 
270 
271                         } catch (Exception ex) {
272                             log.log(Level.WARN, "fgsms unable to fetch policy from PCS at " + cfg.PCS_URLS.get(urlcount) + " will retry " + (cfg.PCSRetryCount - retrycount) + " times." + ex.getMessage(), ex);
273                         }
274                         urlcount++;
275                     }
276                     retrycount++;
277                 }
278 
279                 log.log(Level.FATAL, "fgsms unable to fetch policy from any of the PCS[" + cfg.PCS_URLS.size() + "] URLs, retry count exceeded. Falling back to default policy");
280                 return null;
281             case ROUNDROBIN:
282                 retrycount = 0;
283                 urlcount = 0;
284                 while ((retrycount < cfg.PCSRetryCount)) {
285 
286                     urlcount = 0;
287                     while (urlcount < cfg.PCS_URLS.size()) {
288                         try { // Call Web Service Operation
289 
290                             BindingProvider bp = (BindingProvider) cfg.pcsport;
291                             Map<String, Object> context = bp.getRequestContext();
292                             //    context.remove(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
293                             context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, cfg.PCS_URLS.get(urlcount));
294 //                            StubExt sec = (StubExt) pcsport;
295                             if (cfg.mode_ == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
296 //                                sec.setSecurityConfig("/META-INF/fgsms-username-config.xml");
297                                 context.put(BindingProvider.USERNAME_PROPERTY, cfg.username);
298                                 context.put(BindingProvider.PASSWORD_PROPERTY, Utility.DE(cfg.password));
299                             }
300                             if (cfg.mode_ == org.miloss.fgsms.common.Constants.AuthMode.PKI) {
301                                 if (Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.keyStore")) && !Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.keyStorePassword"))) {
302                                     System.setProperty("javax.net.ssl.keyStorePassword", Utility.DE(cfg.getJavaxkeystorepass()));
303                                     System.setProperty("javax.net.ssl.keyStore", Utility.DE(cfg.getJavaxkeystore()));
304                                 }
305                             }
306                             if (Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.trustStore")) && !Utility.stringIsNullOrEmpty(System.getProperty("javax.net.ssl.trustStorePassword"))) {
307                                 System.setProperty("javax.net.ssl.trustStorePassword", Utility.DE(cfg.getJavaxtruststorepass()));
308                                 System.setProperty("javax.net.ssl.trustStore", Utility.DE(cfg.getJavaxtruststore()));
309                             }
310                             //send it
311                             ServicePolicyResponseMsg servicePolicy = cfg.pcsport.getServicePolicy(req);
312                             cfg.classlevel = servicePolicy.getClassification();
313                             return servicePolicy.getPolicy();
314                         } catch (Exception ex) {
315                             log.log(Level.WARN, "fgsms unable to fetch policy from PCS at " + cfg.PCS_URLS.get(urlcount) + " will retry " + (cfg.PCSRetryCount - retrycount) + " times." + ex.getMessage(), ex);
316                         }
317                         urlcount++;
318                     }
319                     retrycount++;
320                 }
321 
322                 log.log(Level.FATAL, "fgsms unable to fetch policy from any of the PCS[" + cfg.PCS_URLS.size() + "] URLs, retry count exceeded.");
323                 return null;
324 
325         }
326         return null;
327     }
328 
329     protected static String readAllText(InputStream in) {
330         try {
331             InputStreamReader sr = new InputStreamReader(in,Constants.CHARSET);
332             StringBuilder fileData = new StringBuilder(1000);
333             BufferedReader reader = new BufferedReader(sr);
334 
335             char[] buf = new char[1024];
336             int numRead = 0;
337             while ((numRead = reader.read(buf)) != -1) {
338                 String readData = String.valueOf(buf, 0, numRead);
339                 fileData.append(readData);
340                 buf = new char[1024];
341             }
342             reader.close();
343             sr.close();
344             return fileData.toString();
345         } catch (Exception ex) {
346         }
347         return "";
348     }
349 
350     /**
351      * Loads the default policy. does not register this policy with the fgsms
352      * server
353      *
354      * @param url
355      * @return
356      */
357     public static TransactionalWebServicePolicy loadTranasctionalDefaultPolicy(String url) {
358 
359         try {
360             InputStream in = null;
361             ClassLoader loader = Thread.currentThread().getContextClassLoader();
362             if (loader == null) {
363                 loader = ClassLoader.getSystemClassLoader();
364             }
365 
366             // Returns null on lookup failures:
367             in = loader.getResourceAsStream("org/miloss/fgsms/agentcore/defaultpolicy.xml");
368             String pol = readAllText(in);
369             in.close();
370 
371             JAXBContext jc = Utility.getSerializationContext();
372             Unmarshaller u = jc.createUnmarshaller();
373             ByteArrayInputStream bss = new ByteArrayInputStream(pol.getBytes(Constants.CHARSET));
374             XMLInputFactory xf = XMLInputFactory.newInstance();
375             XMLStreamReader r = xf.createXMLStreamReader(bss);
376             JAXBElement<TransactionalWebServicePolicy> foo = (JAXBElement<TransactionalWebServicePolicy>) u.unmarshal(r, TransactionalWebServicePolicy.class);
377             if (foo == null || foo.getValue() == null) {
378                 log.log(Level.WARN, "ServicePolicy is unexpectedly null or empty");
379                 return null;
380             }
381             ServicePolicyResponseMsg ret = new ServicePolicyResponseMsg();
382             ret.setPolicy(foo.getValue());
383             ret.setClassification(cfg.classlevel);
384             ret.getPolicy().setURL(url);
385             return (TransactionalWebServicePolicy) ret.getPolicy();
386         } catch (Exception ex) {
387             log.log(Level.ERROR, "error loading default policy from disk", ex);
388         }
389         return null;
390     }
391 
392     /**
393      * Loads the default policy for statistic services, does not register this
394      * policy with the fgsms server
395      *
396      * @param url
397      * @param machine
398      * @param domain
399      * @return
400      */
401     public static StatisticalServicePolicy loadStatisticalDefaultPolicy(String url, String machine, String domain) {
402         StatisticalServicePolicy pol = new StatisticalServicePolicy();
403         pol.setAgentsEnabled(true);
404         pol.setURL(url);
405         pol.setMachineName(machine);
406         pol.setDomainName(domain);
407 
408         return pol;
409     }
410 }