Java 11: Kerberos using GSS API - kerberos

I'm upgrading a project to Java 11. I realized that some of the internal packages such as sun.security.krb5.Config & sun.security.krb5.KrbException are no longer "visible" due to modules.
Few examples of how the codebase is consuming these packages are below:
Exception cause = ExceptionUtils.findCause(ne, KrbException.class);
LoginException le = (LoginException) ne.getCause();
if (le.getCause() instanceof KrbException) {
KrbException ke = (KrbException) le.getCause();
try {
sun.security.krb5.Config.refresh();
} catch (KrbException e) {
//log something
}
I read that these internal packages are supposed to be implemented using GSS APIs.
I have been going through the GSS classes and tutorials but couldn't find anything on replacing the internal packages mentioned above.

Take the LoginException as-is. JAAS is supposed to abstract from everything. You just have bad code.

Related

Embedded Kafka in micronaut app not finding beans

I'm using the embedded Kafka server in my test described here: https://micronaut-projects.github.io/micronaut-kafka/latest/guide/#kafkaEmbedded. The problem is I'm getting this io.micronaut.context.exceptions.BeanContextException: Error processing bean [Definition: org.app.messaging.TestConsumer] method definition [void receive(String msg)]: Failed to inject value for parameter [testService] of method [setTestService] of class: org.app.messaging.TestConsumer when I run the test. Any ideas how to fix this?
Here's what the test looks like:
void "test run kafka embedded server"() {
given:
ApplicationContext applicationContext = ApplicationContext.run(
Collections.singletonMap(
AbstractKafkaConfiguration.EMBEDDED, true
)
)
when:
AbstractKafkaConsumerConfiguration config = applicationContext.getBean(AbstractKafkaConsumerConfiguration)
Properties props = config.getConfig()
then:
props[ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG] == 9091
when:
KafkaEmbedded kafkaEmbedded = applicationContext.getBean(KafkaEmbedded)
then:
kafkaEmbedded.kafkaServer.isPresent()
kafkaEmbedded.zkPort.isPresent()
cleanup:
applicationContext.close()
}
Placing a test anywhere other than the root package seem to be causing multiple "bean definition not found" issues. There's no ComponentScan support in the framework so the only thing that worked for me was to move the test file to the root package. There's some ideas here: https://github.com/micronaut-projects/micronaut-core/issues/511 if you're experiencing similar issues with a CLI app. However, it didn't work when using the embedded server and embedded kafka.

Calling Watson on Bluemix from java causes Trust Manager error

Trying out some code to call a Watson Service I provisioned on Bluemix. I get the following error:
Unable to extract the trust manager on
okhttp3.internal.Platform#e19ef72e, sslSocketFactory is class
com.ibm.jsse2.SSLSocketFactoryImpl
Here is my code:
try {
DocumentConversion service = new DocumentConversion("2016-05-25");
service.setUsernameAndPassword("*****", "*****");
File doc = new File("C:/Sample1.pdf");
Answers htmlToAnswers = service.convertDocumentToAnswer(doc).execute();
System.out.println(htmlToAnswers);
} catch(Exception e) {
System.out.println("Error! -> " + e.getMessage());
}
Thoughts? Do I need to import a cert from Bluemix? Thanks.
Looks like it is a known problem in the okhttp library. Are you using Java SDK to use the IBM Watson version 3.0.0-RC1? If so, try with 2.10.0 as it has an older version of the okhttp library which may not suffer from this problem.

Quartz scheduled job on Liberty app-server calling REST throwing exception

I'm having real hassle getting a quartz job in an application server to call a REST service - totally puzzled (:
I have quartz (v 2.2.2) deployed & working on an IBM Liberty Application Server (v 8.5.5.8) with Java 1.8
It scans a directory for files and then calls my Dummy Task.
However, when I replace the Dummy Task with a REST WebClient call - I get a pretty odd stacktrace.
java.lang.NullPointerException
[err] at com.ibm.ws.jaxrs20.client.bus.LibertyJAXRSClientBusFactory.getClientScopeBus(LibertyJAXRSClientBusFactory.java:89)
[err] at com.ibm.ws.jaxrs20.client.JAXRSClientImpl.target(JAXRSClientImpl.java:109)
[err] at org.apache.cxf.jaxrs.client.spec.ClientImpl.target(ClientImpl.java:100)
[err] at notification.server.rest.MyIBMHandler.testClient4(MyIBMHandler.java:61)
the last line is mine and the code I wrote is simply based on this: https://www.ibm.com/support/knowledgecenter/was_beta_liberty/com.ibm.websphere.wlp.nd.multiplatform.doc/ae/twlp_jaxrs2.0_clientconfig.html
When I googled the exception above, I didn't see much except for one stacktrace related one:-
NullPointerException when running CXF JAX-RS 2.0 client "target" method in Liberty Profile under a Thread
Which leads me to believe there may be some form of a threading conflict here.
To prove my REST client code was ok on my Liberty app-server, I did put my REST methodinto a servlet and call it there and it did work fine.
i.e.
public void testClient4() {
javax.ws.rs.client.ClientBuilder cb = ClientBuilder.newBuilder();
javax.ws.rs.client.Client c = cb.build();
String res = null;
try {
String resourceURL = "http://localhost:9080/SampleRest/sample/";
res = c.target(resourceURL).path("Greeting").request().get(String.class);
System.out.println("res:" + res);
} catch (Exception e) {
res = "[Error]:" + e.toString();
System.err.println("error:" + e.getMessage());
e.printStackTrace();
} finally {
if (c != null)
c.close();
System.out.println("res:" + res);
}
}
My Quartz props are close to out of the box, here is the threadpool section:-
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 4
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
My job class uses the annotation - #DisallowConcurrentExecution
I'm using the jersey 2.17 libs & jackson libs
I've added lots of features to my Liberty profile - i.e.
<featureManager>
<feature>jsp-2.3</feature>
<feature>jaxrs-2.0</feature>
<feature>servlet-3.1</feature>
<feature>apiDiscovery-1.0</feature>
<feature>jaxrsClient-2.0</feature>
</featureManager>
For now, the REST service being called is a simple one.
When running quartz within an app-server, do I need to do anyconfig to be able to call a REST service? - anyone got this working?
It appears we fixed this NPE in the latest Liberty fixpack, looking here, the 8.5.5.9 fixpack is planned to be available on March 18. Once released, please test and determine if it fixes this problem, and if not let us know.

How to get started with ESAPI out of a servlet container

Could anyone give some considerations to get started using the ESAPI on a no-web context?
I came with this little test that validates a string with DefaultValidator.isValidCreditCard, but I got some web-container dependency errors.
The following method is consumed from a Junit Test:
#Override
public ValidationErrorList creditCard(String value) {
this.value = value;
ValidationErrorList errorList = new ValidationErrorList();
try {
isValid = validator.isValidCreditCard(null, value, false, errorList);
}catch(Exception ie){
System.out.println(">>> CCValidator: [ " + value + "] " + ie.getMessage());
messages = (ArrayList) errorList.errors();
}
return messages;
}
This is the error that I get (relevant part) of course I'm not running in a container:
Attempting to load ESAPI.properties via file I/O.
Attempting to load ESAPI.properties as resource file via file I/O.
Found in 'org.owasp.esapi.resources' directory: C:\foundation\validation\providers\esapi\ESAPI.properties
Loaded 'ESAPI.properties' properties file
Attempting to load validation.properties via file I/O.
Attempting to load validation.properties as resource file via file I/O.
Found in 'org.owasp.esapi.resources' directory: C:\foundation\validation\providers\esapi\validation.properties
Loaded 'validation.properties' properties file
SecurityConfiguration for Encoder.AllowMixedEncoding not found in ESAPI.properties. Using default: false
SecurityConfiguration for Encoder.AllowMixedEncoding not found in ESAPI.properties. Using default: false
javax/servlet/ServletRequest
java.lang.NoClassDefFoundError: javax/servlet/ServletRequest
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:74)
at org.owasp.esapi.ESAPI.httpUtilities(ESAPI.java:121)
at org.owasp.esapi.ESAPI.currentRequest(ESAPI.java:70)
at org.owasp.esapi.reference.Log4JLogger.log(Log4JLogger.java:434)
...
Calls to ESAPI..xxxMethods() also raise dependency errors.
Any advice to get started will be appreciate.
Best,
jose
ESAPI has a servlet filter API that requires javax.servlet.ServletRequest to be on the classpath. ESAPI is owned by OWASP --> "Open Web Application Security Project." Therefore, ESAPI is designed with web applications in mind.
If you're not writing a web application, then its either a console application or a rich client application. If you don't expect to use it to connect to the outside world, then the main secure practices you really need to worry about are ensuring that you always use safely parameterized queries, and that any data passed into your application from a source that IS connected to the outside world is properly escaped. For that, the only thing you need is OWASP's encoder project.

Has anyone successfully deployed a GWT app on Heroku?

Heroku recently began supporting Java apps. Looking through the docs, it seems to resemble the Java Servlet Standard. Does anyone know of an instance where a GWT app has been successfully deployed on Heroku? If so, are there any limitations?
Yes, I've got a successful deployment using the getting started with Java instructions here:
http://devcenter.heroku.com/articles/java
I use the Maven project with appassembler plugin approach but added gwt-maven-plugin to compile a GWT app during the build.
When you push to heroku you see the GWT compile process running, on one thread only so quite slow but it works fine.
The embedded Jetty instance is configured to serve up static resources at /static from src/main/resources/static and I copy the compiled GWT app to this location during the build and then reference the .nocache.js as normal.
What else do you want to know?
You've got a choice, either build the Javascript representation of your GWT app locally into your Maven project, commit it and the read it from your app, or to generate it inside Heroku via the gwt-maven-plugin as I mentioned.
The code to serve up files from a static location inside your jar via embedded Jetty is something like this inside a Guice ServletModule:
(See my other answer below for a simpler and less Guice-driven way to do this.)
protected void configureServlets() {
bind(DefaultServlet.class).in(Singleton.class);
Map<String, String> initParams = new HashMap<String, String>();
initParams.put("pathInfoOnly", "true");
initParams.put("resourceBase", staticResourceBase());
serve("/static/*").with(DefaultServlet.class, initParams);
}
private String staticResourceBase() {
try {
return WebServletModule.class.getResource("/static").toURI().toString();
}
catch (URISyntaxException e) {
e.printStackTrace();
return "couldn't resolve real path to static/";
}
}
There's a few other tricks to getting embedded Jetty working with guice-servlet, let me know if this isn't enough.
My first answer to this turned out to have problems when GWT tried to read its serialization policy. In the end I went for a simpler approach that was less Guice-based. I had to step through the Jetty code to understand why setBaseResource() was the way to go - it's not immediately obvious from the Javadoc.
Here's my server class - the one with the main() method that you point Heroku at via your app-assembler plugin as per the Heroku docs.
public class MyServer {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
new MyServer().start(Integer.valueOf(args[0]));
}
else {
new MyServer().start(Integer.valueOf(System.getenv("PORT")));
}
}
public void start(int port) throws Exception {
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setBaseResource(createResourceForStatics());
context.setContextPath("/");
context.addEventListener(new AppConfig());
context.addFilter(GuiceFilter.class, "/*", null);
context.addServlet(DefaultServlet.class, "/");
server.setHandler(context);
server.start();
server.join();
}
private Resource createResourceForStatics() throws MalformedURLException, IOException {
String staticDir = getClass().getClassLoader().getResource("static/").toExternalForm();
Resource staticResource = Resource.newResource(staticDir);
return staticResource;
}
}
AppConfig.java is a GuiceServletContextListener.
You then put your static resources under src/main/resources/static/.
In theory, one should be able to run GWT using the embedded versions of Jetty or Tomcat, and bootstrap the server in main as described in the Heroku Java docs.