Change AD Password with Java - java

I have a good connection to AD. I can authenticate and check error messages from failed auths.
The issue I'm having comes from trying to change the password. I have an LDAPContext established at this point (yes it is an SSL connection). The issue comes from not knowing what value to use in the "username" parameter. I've tried all variations I can think of and end up getting one of three errors:
A) NO_OBJECT - I'm assuming this means it is connecting to AD properly but can't find what I'm looking for.
B) DIR_ERROR - I'm assuming this means it can get into AD properly but doesn't know wtf I want it to do after that.
C) Some type of ref error that only happens when I don't qualify the DC, so I think that's pretty much a given.
Here is the code I am using:
public void changePassword(String username, String password) {
ModificationItem[] mods = new ModificationItem[1];
String newQuotedPassword = "\"" + password + "\"";
byte[] newUnicodePassword = newQuotedPassword.getBytes();
try {
newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
try {
ldapContext.modifyAttributes(username, mods);
} catch (NamingException e) {
System.out.println("Error changing password for '" + username + "': " + e.getMessage());
e.printStackTrace();
}
}

Spring has an LDAP module that works very nicely. I'll bet it will do what you need.

Here is a working example:
Main.java:
package io.fouad.ldap;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
public class Main
{
public static void main(String[] args)
{
final String LDAP_SERVERS = "ldap://AD_SERVER:636 ldap://AD_SERVER2:636"; // separated by single spaces
final String LDAP_CONNECT_TIMEOUT_MS = "10000"; // 10 seconds
final String LDAP_READ_TIMEOUT_MS = "10000"; // 10 seconds
final String AUTHENTICATION_DOMAIN = "domain.com";
final String USERNAME = "username";
final String OLD_PASSWORD = "123";
final String NEW_PASSWORD = "456";
final String TARGET_BASE_DN = "dc=domain,dc=com";
Hashtable<String, String> ldapEnv = new Hashtable<>();
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, LDAP_SERVERS);
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put("java.naming.ldap.version", "3");
ldapEnv.put(Context.SECURITY_PRINCIPAL, USERNAME + "#" + AUTHENTICATION_DOMAIN);
ldapEnv.put(Context.SECURITY_CREDENTIALS, OLD_PASSWORD);
ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
ldapEnv.put("java.naming.ldap.factory.socket", "io.fouad.ldap.MySSLSocketFactory");
//ldapEnv.put("com.sun.jndi.ldap.connect.timeout", LDAP_CONNECT_TIMEOUT_MS);
//ldapEnv.put("com.sun.jndi.ldap.read.timeout", LDAP_READ_TIMEOUT_MS);
DirContext ldapContext = null;
try
{
ldapContext = new InitialDirContext(ldapEnv);
}
catch(AuthenticationException e)
{
System.out.println("Wrong username/password!");
e.printStackTrace();
}
catch(NamingException e)
{
e.printStackTrace();
}
if(ldapContext == null) return;
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration objects = null;
try
{
objects = ldapContext.search(TARGET_BASE_DN, String.format("(&(objectClass=user)(sAMAccountName=%s))", USERNAME), searchControls);
}
catch(NamingException e)
{
e.printStackTrace();
}
if(objects == null) return;
try
{
if(objects.hasMore())
{
SearchResult entry = (SearchResult) objects.next();
ModificationItem[] mods = new ModificationItem[2];
mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", getPasswordByteArray(OLD_PASSWORD)));
mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", getPasswordByteArray(NEW_PASSWORD)));
ldapContext.modifyAttributes(entry.getName() + "," + TARGET_BASE_DN, mods);
System.out.println("Successfully changed the password!");
}
else
{
System.out.println("User (" + USERNAME + ") was not found!");
}
}
catch(NamingException e)
{
e.printStackTrace();
}
System.out.println("DONE!");
}
private static byte[] getPasswordByteArray(String password)
{
String quotedPassword = "\"" + password + "\"";
try
{
return quotedPassword.getBytes("UTF-16LE");
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
return null;
}
}
}
MySSLSocketFactory.java: (Use it at your own risk)
package io.fouad.ldap;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class MySSLSocketFactory extends SSLSocketFactory
{
private SSLSocketFactory socketFactory;
public MySSLSocketFactory()
{
try
{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] {new X509TrustManager()
{
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s){}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s){}
#Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
}}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
}
catch(Exception ex)
{
ex.printStackTrace(System.err);
}
}
public static SocketFactory getDefault()
{
return new MySSLSocketFactory();
}
#Override
public String[] getDefaultCipherSuites()
{
return socketFactory.getDefaultCipherSuites();
}
#Override
public String[] getSupportedCipherSuites()
{
return socketFactory.getSupportedCipherSuites();
}
#Override
public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException
{
return socketFactory.createSocket(socket, string, i, bln);
}
#Override
public Socket createSocket(String string, int i) throws IOException
{
return socketFactory.createSocket(string, i);
}
#Override
public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException
{
return socketFactory.createSocket(string, i, ia, i1);
}
#Override
public Socket createSocket(InetAddress ia, int i) throws IOException
{
return socketFactory.createSocket(ia, i);
}
#Override
public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException
{
return socketFactory.createSocket(ia, i, ia1, i1);
}
}

We have a reference for Java fro JNDI here http://ldapwiki.willeke.com/wiki/Set%20Active%20Directory%20Password%20From%20Java

You cannot change the password of a user by just modifying the property that stores it. Instead, you need to use a special LDAP operation SetPassword. I couldn't find a Java reference, but a C# one, and a Perl one.

Related

I can't use the "print/println" functions

I'm using IntelliJ IDEA.
I've done all that my Googling has provided me with as potential solutions.
I've tried doing the File -> Invalidate Caches/Restart, it still doesn't fix it.
This is the entire code;
This was copied from the OCI documentation, and I've already made some amendments to the code, but I don't know how to fix this.
I'm a junior yes, but am I wrong to be annoyed over how much of the documentation through the use of which I'm to be developing myself has these kinds of issues..
This is the entire code.
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.codec.binary.Base64;
import static java.lang.System.out;
import static com.sun.org.apache.xalan.internal.xsltc.cmdline.Compile.printUsage;
public class ociAuth {
private static String server;
private static String user;
private static String password;
private static String port = "8443";
private static String response_format = "json";
private static String server_url;
public static void main(String[] args) {
if(args.length < 3 || args.length > 4) {
printUsage();
System.exit(1);
}
setUserArguments(args);
server_url = "https://" + server + ":" + port + "/rest/v1/assets/storages";
try {
HttpsURLConnection connection =
getAllTrustingHttpsUrlConnection();
if(connection == null) {
System.err.println("FATAL: Failed to create HTTPS connection to URL: " + server_url);
System.exit(1);
}
System.out.println("Invoking API: " + server_url);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/" + response_format);
String authString = getAuthorizationString();
connection.setRequestProperty("Authorization", "Basic " +
authString);
if (connection.getResponseCode() != 200) {
System.err.println("API Invocation Failed : HTTP error code : "
+ connection.getResponseCode());
System.exit(1);
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
String response;
System.out.println("Response:");
while ((response = br.readLine()) != null) {
System.out.println(response);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
//THESE PRINTS HERE BELLOW
//THESE PRINTS HERE BELLOW
//THESE PRINTS HERE BELLOW
System.out.print("\nUsage:\n\tHelloApiServices <api-server host[:port]> <user> <password> [json|xml]\n");
System.out.print("\nExamples:\n\tHelloApiServices localhost admin mypassword");
System.out.print("\tHelloApiServices 10.22.12.34:8320 admin password");
System.out.print("\tHelloApiServices 10.22.12.34 admin password xml");
System.out.print("\tHelloApiServices 10.22.12.34:8212 admin password xml\n");
System.out.print("\nNote:\n\t(1) When port number is not provided, 8443 is chosen by default.");
System.out.print("\t(2) When response format (json or xml) is not provided, json is chosen by default. \n");
}
//THESE PRINTS HERE ABOVE
//THESE PRINTS HERE ABOVE
//THESE PRINTS HERE ABOVE
private static void setUserArguments(String[] args) {
server = args[0];
user = args[1];
password = args[2];
if(args.length == 4) {
response_format = args[3];
if(!response_format.equals("json") && ! response_format.equals("xml")) {
printUsage();
System.exit(1);
}
}
if(server.contains(":")) {
String[] parts = server.split(":");
server = parts[0];
port = parts[1];
}
}
private static HttpsURLConnection getAllTrustingHttpsUrlConnection() {
HttpsURLConnection conn = null;
try {
TrustManager[] trustAllCertificatesManager = new
TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return
null;
}
public void checkClientTrusted(X509Certificate[]
certs, String authType) {
}
public void checkServerTrusted(X509Certificate[]
certs, String authType) {
}
}};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCertificatesManager, new
SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
URL url = new URL(server_url);
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String host, SSLSession
session) {
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
private static String getAuthorizationString() {
String userPassword = user + ":" + password;
byte[] authEncodedBytes =
Base64.encodeBase64(userPassword.getBytes());
String ajdeovako = new String(authEncodedBytes);
return ajdeovako;
}
}
You have an extra bracket. The System.out.print calls are not inside you main method, but are instead between methods and the closing bracket after the print calls shouldn't be there. Move the print calls up inside your main method and it should compile fine.
You have one extra }, removing it will fix your error.
} <-- remove this
//THESE PRINTS HERE BELLOW
//THESE PRINTS HERE BELLOW
//THESE PRINTS HERE BELLOW
System.out.print("\nUsage:\n\tHelloApiServices <api-server host[:port]> <user> <password> [json|xml]\n");
System.out.print("\nExamples:\n\tHelloApiServices localhost admin mypassword");
System.out.print("\tHelloApiServices 10.22.12.34:8320 admin password");
System.out.print("\tHelloApiServices 10.22.12.34 admin password xml");
System.out.print("\tHelloApiServices 10.22.12.34:8212 admin password xml\n");
System.out.print("\nNote:\n\t(1) When port number is not provided, 8443 is chosen by default.");
System.out.print("\t(2) When response format (json or xml) is not provided, json is chosen by default. \n");
}

How to correct Invalid Protocol: null sending mail and Could not to SMTP host: using javax.mail?

I have a problem, I am using slack and mail.
I have got a method to create a folder with header "chan", but it doesn't work:
method getMessage()
for (String chan : channels){
sentMessage(chan);//поменять куда вставить
System.out.println(chan);
Enter:
"Что то пошло не такjavax.mail.MessagingException: Could not to SMTP host: localhost, port 25; nested exception is : java.net.Connection refused connect"
If I comment out
sentMessage(chan);//поменять куда вставить
I have got send message from slack to mail.
This is my program on java.
package ru.slacks;
import com.github.seratch.jslack.*;
import com.github.seratch.jslack.api.methods.SlackApiException;
import com.github.seratch.jslack.api.methods.request.channels.ChannelsListRequest;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import com.github.seratch.jslack.api.methods.request.im.ImListRequest;
import com.ullink.slack.simpleslackapi.*;
import com.ullink.slack.simpleslackapi.SlackSession;
import com.ullink.slack.simpleslackapi.events.SlackMessagePosted;
import com.ullink.slack.simpleslackapi.impl.ChannelHistoryModuleFactory;
import static java.util.stream.Collectors.toList;
import com.ullink.slack.simpleslackapi.impl.SlackSessionFactory;
import org.glassfish.grizzly.http.server.util.StringParser;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.*;
public class SlackTools {
public SlackTools() throws IOException, SlackApiException {
}
private String token=".....our_token......";
static final Slack slack = Slack.getInstance();
List<String> channels = slack.methods().channelsList(ChannelsListRequest.builder().token(token).build())
.getChannels().stream().map(c -> c.getId()).collect(toList());
public void getChannels() throws IOException, SlackApiException {
System.out.println("---------------Channels---------------");
for (String chan : channels){
sentMessage(chan);//поменять куда вставить
System.out.println(chan);
}
}
public class EmailAuthenticator extends javax.mail.Authenticator
{
private String login;
private String password;
public EmailAuthenticator (final String login, final String password)
{
this.login = login;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(login, password);
}
}
public void sentMessage(String chanel) throws IOException {
Properties imap = new Properties();
imap.put("mail.debug" , "false" );
imap.put("mail.store.protocol" , "imaps" );//для доступа и обработки сообщений
imap.put("mail.imap.ssl.enable", true);
imap.put("mail.imap.port", 993);
Authenticator auth = new EmailAuthenticator("tm12018#yandex.ru",
"test123456");
Session session = Session.getDefaultInstance(imap, auth);
session.setDebug(false);
try {
Store store = session.getStore();
// Подключение к почтовому серверу
store.connect("imap.yandex.ru", "tm12018#yandex.ru", "test123456");
// Папка входящих сообщений
Folder inbox = store.getFolder(chanel);
if (!inbox.exists())
if (inbox.create(Folder.HOLDS_MESSAGES))
System.out.println("Folder was created successfully");
// Открываем папку в режиме только для чтения
//inbox.open(Folder.READ_ONLY);
inbox.open(Folder.READ_WRITE);
System.out.println("Количество сообщений : " +
String.valueOf(inbox.getMessageCount()));
if (inbox.getMessageCount() == 0)
return;
} catch (NoSuchProviderException e) {
System.err.println(e.getMessage());
} catch (MessagingException e) {
System.err.println(e.getMessage());
}
}
public void getMessage() throws IOException {
Properties p = new Properties();
p.put("mail.smtp.host", "smtp.yandex.ru");//протокол передачи сообщений, или smtp.gmail.com
p.put("mail.smtp.socketFactory.port", 465);
p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.put("mail.smtp.auth", true);
p.put("mail.smtp.port", 465);
// p.put("mail.transport.protocol", "smtp");
Scanner in = new Scanner(System.in);
System.out.print("Enter your e-mail ");
String user = in.nextLine();
System.out.println("Enter your password");
String password = in.nextLine();
Session s = Session.getDefaultInstance(p,
new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user, password);}});
System.out.print("Enter usernameto ");
String userto = in.nextLine();
for(String chan : channels ){
SlackSession sessiont = SlackSessionFactory.createWebSocketSlackSession(token);
sessiont.connect();
ChannelHistoryModule channelHistoryModule = ChannelHistoryModuleFactory.createChannelHistoryModule(sessiont);
List<SlackMessagePosted> messages = channelHistoryModule.fetchHistoryOfChannel(chan).stream().collect(toList());
System.out.println("---------------Messages- " + chan + "--------------");
for (SlackMessagePosted message : messages) {
System.out.println("E-mail:" + message.getUser().getUserMail() + ", message: " + message.getMessageContent() );
try {
Message mess = new MimeMessage(s);
mess.setFrom(new InternetAddress(user));
mess.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userto));
mess.setSubject(message.getMessageContent().toString());
mess.setText(chan);
Transport.send(mess);
JOptionPane.showMessageDialog(null, "Письмо отправлено" );
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Что то пошло не так" + ex);
}
}
}
}
public static void main(String[] args) throws IOException, SlackApiException, MessagingException {
SlackTools sl = new SlackTools();
sl.getChannels();
sl.getMessage();
System.exit(0);
}
}
Looks like the response is telling you that there is no process (or at least not a email host) listening on your localhost port 25. Are you sure it's there? What happens when you do telnet localhost 25 ?

Java 1.6 + BouncyCastle + TLS1.2 (handshake_failure(40))

In my case, I have Java 1.6 and want to connect to a remote server which only supports TLS1.2. Server URL is: https://blagajne-test.fu.gov.si:9002 and certificate public key is here: http://datoteke.durs.gov.si/dpr/files/test-tls.cer
I have no possibility to upgrade Java because is a part of Oracle Database 11g (11.4).
I tried to write a simple program in Java which uses BouncyCastel libraries but got error: Exception in thread "main"
org.bouncycastle.crypto.tls.TlsFatalAlertReceived: handshake_failure(40)
at org.bouncycastle.crypto.tls.TlsProtocol.handleAlertMessage(Unknown Source)
The step I have followed was:
1.) have downloaded test-tls.cer and imported the key into jssacerts and cacerts.
2.) In Java have done this example:
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URL;
import java.security.MessageDigest;
import java.security.Security;
import java.security.Signature;
import javax.net.ssl.HttpsURLConnection;
import org.bouncycastle.crypto.tls.CertificateRequest;
import org.bouncycastle.crypto.tls.DefaultTlsClient;
import org.bouncycastle.crypto.tls.TlsAuthentication;
import org.bouncycastle.crypto.tls.TlsClientProtocol;
import org.bouncycastle.crypto.tls.TlsCredentials;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Test3 {
public static Signature podpis = null;
public static MessageDigest md = null;
static {
try {
Security.addProvider(new BouncyCastleProvider());
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
String httpsURL = "https://blagajne-test.fu.gov.si:9002";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection )myurl.openConnection();
con.setSSLSocketFactory(new TLSSocketConnectionFactory());
InputStream ins = con.getInputStream();
}
}
and
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.Principal;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.security.cert.X509Certificate;
import org.apache.commons.logging.Log;
import org.bouncycastle.crypto.tls.Certificate;
import org.bouncycastle.crypto.tls.CertificateRequest;
import org.bouncycastle.crypto.tls.DefaultTlsClient;
import org.bouncycastle.crypto.tls.ExtensionType;
import org.bouncycastle.crypto.tls.TlsAuthentication;
import org.bouncycastle.crypto.tls.TlsClientProtocol;
import org.bouncycastle.crypto.tls.TlsCredentials;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class TLSSocketConnectionFactory extends SSLSocketFactory {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Adding Custom BouncyCastleProvider
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
static {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//SECURE RANDOM
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
private SecureRandom _secureRandom = new SecureRandom();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Adding Custom BouncyCastleProvider
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
public Socket createSocket(Socket socket, final String host, int port, boolean arg3)
throws IOException {
if (socket == null) {
socket = new Socket();
}
if (!socket.isConnected()) {
socket.connect(new InetSocketAddress(host, port));
}
final TlsClientProtocol tlsClientProtocol = new TlsClientProtocol(socket.getInputStream(), socket.getOutputStream(), _secureRandom);
return _createSSLSocket(host, tlsClientProtocol);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SOCKET FACTORY METHODS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
public String[] getDefaultCipherSuites() {
return null;
}
#Override
public String[] getSupportedCipherSuites() {
return null;
}
#Override
public Socket createSocket(String host,
int port) throws IOException, UnknownHostException {
return null;
}
#Override
public Socket createSocket(InetAddress host,
int port) throws IOException {
return null;
}
#Override
public Socket createSocket(String host,
int port,
InetAddress localHost,
int localPort) throws IOException, UnknownHostException {
return null;
}
#Override
public Socket createSocket(InetAddress address,
int port,
InetAddress localAddress,
int localPort) throws IOException {
return null;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//SOCKET CREATION
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private SSLSocket _createSSLSocket(final String host, final TlsClientProtocol tlsClientProtocol) {
return new SSLSocket() {
private java.security.cert.Certificate[] peertCerts;
#Override
public InputStream getInputStream() throws IOException {
return tlsClientProtocol.getInputStream();
}
#Override
public OutputStream getOutputStream() throws IOException {
return tlsClientProtocol.getOutputStream();
}
#Override
public synchronized void close() throws IOException {
tlsClientProtocol.close();
}
#Override
public void addHandshakeCompletedListener(HandshakeCompletedListener arg0) {
}
#Override
public boolean getEnableSessionCreation() {
return false;
}
#Override
public String[] getEnabledCipherSuites() {
return null;
}
#Override
public String[] getEnabledProtocols() {
return null;
}
#Override
public boolean getNeedClientAuth() {
return false;
}
#Override
public SSLSession getSession() {
return new SSLSession() {
#Override
public int getApplicationBufferSize() {
return 0;
}
#Override
public String getCipherSuite() {
throw new UnsupportedOperationException();
}
#Override
public long getCreationTime() {
throw new UnsupportedOperationException();
}
#Override
public byte[] getId() {
throw new UnsupportedOperationException();
}
#Override
public long getLastAccessedTime() {
throw new UnsupportedOperationException();
}
#Override
public java.security.cert.Certificate[] getLocalCertificates() {
throw new UnsupportedOperationException();
}
#Override
public Principal getLocalPrincipal() {
throw new UnsupportedOperationException();
}
#Override
public int getPacketBufferSize() {
throw new UnsupportedOperationException();
}
#Override
public X509Certificate[] getPeerCertificateChain()
throws SSLPeerUnverifiedException {
return null;
}
#Override
public java.security.cert.Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
return peertCerts;
}
#Override
public String getPeerHost() {
throw new UnsupportedOperationException();
}
#Override
public int getPeerPort() {
return 0;
}
#Override
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
return null;
//throw new UnsupportedOperationException();
}
#Override
public String getProtocol() {
throw new UnsupportedOperationException();
}
#Override
public SSLSessionContext getSessionContext() {
throw new UnsupportedOperationException();
}
#Override
public Object getValue(String arg0) {
throw new UnsupportedOperationException();
}
#Override
public String[] getValueNames() {
throw new UnsupportedOperationException();
}
#Override
public void invalidate() {
throw new UnsupportedOperationException();
}
#Override
public boolean isValid() {
throw new UnsupportedOperationException();
}
#Override
public void putValue(String arg0, Object arg1) {
throw new UnsupportedOperationException();
}
#Override
public void removeValue(String arg0) {
throw new UnsupportedOperationException();
}
};
}
#Override
public String[] getSupportedProtocols() {
return null;
}
#Override
public boolean getUseClientMode() {
return false;
}
#Override
public boolean getWantClientAuth() {
return false;
}
#Override
public void removeHandshakeCompletedListener(HandshakeCompletedListener arg0) {
}
#Override
public void setEnableSessionCreation(boolean arg0) {
}
#Override
public void setEnabledCipherSuites(String[] arg0) {
}
#Override
public void setEnabledProtocols(String[] arg0) {
}
#Override
public void setNeedClientAuth(boolean arg0) {
}
#Override
public void setUseClientMode(boolean arg0) {
}
#Override
public void setWantClientAuth(boolean arg0) {
}
#Override
public String[] getSupportedCipherSuites() {
return null;
}
#Override
public void startHandshake() throws IOException {
tlsClientProtocol.connect(new DefaultTlsClient() {
#SuppressWarnings("unchecked")
#Override
public Hashtable<Integer, byte[]> getClientExtensions() throws IOException {
Hashtable<Integer, byte[]> clientExtensions = super.getClientExtensions();
if (clientExtensions == null) {
clientExtensions = new Hashtable<Integer, byte[]>();
}
//Add host_name
byte[] host_name = host.getBytes();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream dos = new DataOutputStream(baos);
dos.writeShort(host_name.length + 3);
dos.writeByte(0); //
dos.writeShort(host_name.length);
dos.write(host_name);
dos.close();
clientExtensions.put(ExtensionType.server_name, baos.toByteArray());
return clientExtensions;
}
#Override
public TlsAuthentication getAuthentication()
throws IOException {
return new TlsAuthentication() {
#Override
public void notifyServerCertificate(Certificate serverCertificate) throws IOException {
try {
KeyStore ks = _loadKeyStore();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
List<java.security.cert.Certificate> certs = new LinkedList<java.security.cert.Certificate>();
boolean trustedCertificate = false;
for (org.bouncycastle.asn1.x509.Certificate c : serverCertificate.getCertificateList()) {
java.security.cert.Certificate cert = cf.generateCertificate(new ByteArrayInputStream(c.getEncoded()));
certs.add(cert);
String alias = ks.getCertificateAlias(cert);
if (alias != null) {
if (cert instanceof java.security.cert.X509Certificate) {
try {
((java.security.cert.X509Certificate) cert).checkValidity();
trustedCertificate = true;
} catch (CertificateExpiredException cee) {
cee.printStackTrace();
}
}
} else {
System.out.println("-->");
}
}
if (!trustedCertificate) {
throw new CertificateException("Unknown cert " + serverCertificate);
}
peertCerts = certs.toArray(new java.security.cert.Certificate[0]);
} catch (Exception ex) {
ex.printStackTrace();
throw new IOException(ex);
}
}
#Override
public TlsCredentials getClientCredentials(CertificateRequest arg0)
throws IOException {
return null;
}
/**
* Private method to load keyStore with system or
* default properties.
*
* #return
* #throws Exception
*/
private KeyStore _loadKeyStore() throws Exception {
FileInputStream trustStoreFis = null;
try {
String sysTrustStore = null;
File trustStoreFile = null;
KeyStore localKeyStore = null;
sysTrustStore = System.getProperty("javax.net.ssl.trustStore");
String javaHome;
if (!"NONE".equals(sysTrustStore)) {
if (sysTrustStore != null) {
trustStoreFile = new File(sysTrustStore);
trustStoreFis = _getFileInputStream(trustStoreFile);
} else {
javaHome = System.getProperty("java.home");
trustStoreFile = new File(javaHome + File.separator + "lib" + File.separator + "security" + File.separator + "jssecacerts");
if ((trustStoreFis = _getFileInputStream(trustStoreFile)) == null) {
trustStoreFile = new File(javaHome + File.separator + "lib" + File.separator + "security" + File.separator + "cacerts");
trustStoreFis = _getFileInputStream(trustStoreFile);
}
}
if (trustStoreFis != null) {
sysTrustStore = trustStoreFile.getPath();
} else {
sysTrustStore = "No File Available, using empty keystore.";
}
}
System.out.println("sysTrustStore: " +sysTrustStore);
String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType") != null ? System.getProperty("javax.net.ssl.trustStoreType") : KeyStore.getDefaultType();
String trustStoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider") != null ? System.getProperty("javax.net.ssl.trustStoreProvider") : "";
if (trustStoreType.length() != 0) {
if (trustStoreProvider.length() == 0) {
localKeyStore = KeyStore.getInstance(trustStoreType);
} else {
localKeyStore = KeyStore.getInstance(trustStoreType, trustStoreProvider);
}
char[] keyStorePass = null;
String str5 = System.getProperty("javax.net.ssl.trustStorePassword") != null ? System.getProperty("javax.net.ssl.trustStorePassword") : "";
if (str5.length() != 0) {
keyStorePass = str5.toCharArray();
}
localKeyStore.load(trustStoreFis, (char[]) keyStorePass);
if (keyStorePass != null) {
for (int i = 0; i < keyStorePass.length; i++) {
keyStorePass[i] = 0;
}
}
}
return (KeyStore) localKeyStore;
} finally {
if (trustStoreFis != null) {
trustStoreFis.close();
}
}
}
private FileInputStream _getFileInputStream(File paramFile) throws Exception {
if (paramFile.exists()) {
return new FileInputStream(paramFile);
}
return null;
}
};
}
});
}
};//Socket
}
}
When I execute the main program I got:
What I'm doing wrong or why I get back that exception?
Download jce_policy-6.zip from oracle website
unzip the jce_policy-6.zip you will have two jars local_policy.jar and US_export_policy.jar.
Install the jars based on the README file provided in the zip - two jars should be copied to %JAVA_HOME%/lib/security
Edit the file %JAVA_HOME%/jre/lib/security/java.security and locate the security-provider list add this line -
security.provider.10=org.bouncycastle.jce.provider.BouncyCastleProvider
Use the following code to get the SSLContext.
Provider provider = new BouncyCastleJsseProvider();
Security.addProvider(provider);
SSLContext ctx = SSLContext.getInstance("TLS",provider.getName());
Please switch to Version 1.55 this will fix the issue...

WMI Win32_SoundDevice J-Interop throws Unknown name exception

I am trying to get Win32_SoundDevice and Win32_VideoControllerHardware id but getting Win32_SoundDevice instance throws Unknow Name Exception
here is my code
package com.az;
import static org.jinterop.dcom.core.JIProgId.valueOf;
import static org.jinterop.dcom.impls.JIObjectFactory.narrowObject;
import static org.jinterop.dcom.impls.automation.IJIDispatch.IID;
import java.awt.Label;
import java.util.logging.Level;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.automation.IJIDispatch;
import org.jinterop.dcom.impls.automation.IJIEnumVariant;
public class PerformanceMonitor extends JApplet {
String domain = "az.com.us";
String hostname = "mc-us-az";
String username = "az";
String password = "test_az_";
public JIComServer comServer = null;
public JISession dcomSession = null;
public IJIDispatch wbemServices = null;
public Object[] params = null;
public static final String soundCardInfo = "Win32_SoundDevice";
public void setWindowsCredentials(String domain, String hostname, String username, String password) {
try {
dcomSession = init(domain, username, password);
comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"), hostname, dcomSession);
IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
params = new Object[] { new JIString(hostname), new JIString("ROOT\\CIMV2"), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(),
JIVariant.OPTIONAL_PARAM(), new Integer(0), JIVariant.OPTIONAL_PARAM() };
JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
getWMISoundCard(getJIVariants(wbemLocator, soundCardInfo));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dcomSession != null) {
try {
JISession.destroySession(dcomSession);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
private void getWMISoundCard(JIVariant[] diskMonit) {
try {
IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(diskMonit[0].getObjectAsComObject());
JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
IJIComObject object2 = newEnumvariant.getObjectAsComObject();
IJIEnumVariant enumVARIANT = (IJIEnumVariant) narrowObject(object2.queryInterface(IJIEnumVariant.IID));
JIVariant countVariant = wbemObjectSet.get("Count");
int numberOfServices = countVariant.getObjectAsInt();
for (int i = 0; i < numberOfServices; i++) {
Object[] elements = enumVARIANT.next(1);
JIArray aJIArray = (JIArray) elements[0];
JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();
for (JIVariant variant : array) {
IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());
JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] { 1 });
JIVariant deviceID = (JIVariant) (wbemObjectDispatch.get("DeviceID"));
System.out.println("SoundCard Device ID =" + deviceID.getObjectAsString2());
}
}
} catch (JIException e) {
e.printStackTrace();
}
}
public JIVariant[] getJIVariants(IJIDispatch wbemServices, String task) {
JIVariant[] arrJIVariant = null;
try {
params = new Object[] { new JIString(task), new Integer(0), JIVariant.OPTIONAL_PARAM() };
arrJIVariant = wbemServices.callMethodA("InstancesOf", params);
} catch (JIException e) {
e.printStackTrace();
}
return arrJIVariant;
}
private static JISession init(String domain, String user, String pass) throws Exception {
JISystem.getLogger().setLevel(Level.OFF);
JISystem.setAutoRegisteration(true);
JISession dcomSession = JISession.createSession(domain, user, pass);
dcomSession.useSessionSecurity(false);
return dcomSession;
}
public static void main(String[] args) {
PerformanceMonitor performanceMonitor = new PerformanceMonitor();
performanceMonitor.setWindowsCredentials(performanceMonitor.domain, performanceMonitor.hostname, performanceMonitor.username, performanceMonitor.password);
}
}
Stack Trace
org.jinterop.dcom.common.JIException: Unknown name. [0x80020006]
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:910)
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:856)
at org.jinterop.dcom.core.JIComObjectImpl.call(JIComObjectImpl.java:266)
at org.jinterop.dcom.core.JIComObjectImpl.call(JIComObjectImpl.java:153)
at org.jinterop.dcom.impls.automation.JIDispatchImpl.getIDsOfNames(JIDispatchImpl.java:109)
at org.jinterop.dcom.impls.automation.JIDispatchImpl.callMethodA(JIDispatchImpl.java:477)
at com.az.PerformanceMonitor.getJIVariants(PerformanceMonitor.java:682)
at com.az.PerformanceMonitor.setWindowsCredentials(PerformanceMonitor.java:123)
at com.az.PerformanceMonitor.init(PerformanceMonitor.java:80)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.jinterop.dcom.common.JIRuntimeException: Unknown name. [0x80020006]
at org.jinterop.dcom.core.JICallBuilder.readResult(JICallBuilder.java:1079)
at org.jinterop.dcom.core.JICallBuilder.read(JICallBuilder.java:957)
at ndr.NdrObject.decode(NdrObject.java:36)
at rpc.ConnectionOrientedEndpoint.call(ConnectionOrientedEndpoint.java:137)
at rpc.Stub.call(Stub.java:113)
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:901)
... 10 more
Just replace this line
getWMISoundCard(getJIVariants(wbemLocator, soundCardInfo));
with this
getWMISoundCard(getJIVariants(wbemServices, soundCardInfo));
and problem solved

Java Simpleframework and SSL

When I run the code below i can access it okay over a browser, but I can't seem to get it to work using curl with this command:
curl -v -s -k "https://localhost:8080"
I am running the following code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.core.Container;
import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection;
/**
* Simple Server SSL Hello World Example.
*
*/
public class SimpleSSLHelloWorld implements Container {
public static int count = 0;
public static String EMTPY_STRING = "";
public static int serverPort;
public static String KEYSTORE_PROPERTY = "javax.net.ssl.keyStore";
public static String KEYSTORE_PASSWORD_PROPERTY = "javax.net.ssl.keyStorePassword";
public static String KEYSTORE_TYPE_PROPERTY = "javax.net.ssl.keyStoreType";
public static String KEYSTORE_ALIAS_PROPERTY = "javax.net.ssl.keyStoreAlias";
public static void main(final String[] args) throws Exception {
SimpleSSLHelloWorld.serverPort = 8080;
// System.setProperty("javax.net.debug", "all");
System.setProperty(SimpleSSLHelloWorld.KEYSTORE_PROPERTY, "mySrvKeystore");
System.setProperty(SimpleSSLHelloWorld.KEYSTORE_PASSWORD_PROPERTY, "123456");
Container container = new SimpleSSLHelloWorld();
SocketAddress address = new InetSocketAddress(SimpleSSLHelloWorld.serverPort);
SSLContext sslContext = SimpleSSLHelloWorld.createSSLContext();
Connection connectionHttps = new SocketConnection(container);
connectionHttps.connect(address, sslContext);
System.out.println("Simple Server started on port: " + SimpleSSLHelloWorld.serverPort);
}
public void handle(final Request request, final Response response) {
try {
System.out.println("what");
SimpleSSLHelloWorld.logRequest(request);
SimpleSSLHelloWorld.dummyResponse(response);
SimpleSSLHelloWorld.logResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SSLContext createSSLContext() throws Exception {
String keyStoreFile = System.getProperty(SimpleSSLHelloWorld.KEYSTORE_PROPERTY);
String keyStorePassword = System.getProperty(SimpleSSLHelloWorld.KEYSTORE_PASSWORD_PROPERTY,
SimpleSSLHelloWorld.EMTPY_STRING);
String keyStoreType = System.getProperty(SimpleSSLHelloWorld.KEYSTORE_TYPE_PROPERTY, KeyStore.getDefaultType());
KeyStore keyStore = SimpleSSLHelloWorld.loadKeyStore(keyStoreFile, keyStorePassword, null);
FileInputStream keyStoreFileInpuStream = null;
try {
if (keyStoreFile != null) {
keyStoreFileInpuStream = new FileInputStream(keyStoreFile);
keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(keyStoreFileInpuStream, keyStorePassword.toCharArray());
}
} finally {
if (keyStoreFileInpuStream != null) {
keyStoreFileInpuStream.close();
}
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
SSLContext sslContext = SSLContext.getInstance("SSLv3");
// sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[]{new NaiveX509TrustManager()}, null);
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
return sslContext;
}
public static KeyStore loadKeyStore(final String keyStoreFilePath, final String keyStorePassword,
final String keyStoreType) throws Exception {
KeyStore keyStore = null;
File keyStoreFile = new File(keyStoreFilePath);
if (keyStoreFile.isFile()) {
keyStore = KeyStore.getInstance(keyStoreType != null ? keyStoreType : KeyStore.getDefaultType());
keyStore.load(new FileInputStream(keyStoreFile), keyStorePassword != null ? keyStorePassword
.toCharArray() : SimpleSSLHelloWorld.EMTPY_STRING.toCharArray());
}
return keyStore;
}
public static void logRequest(final Request request) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append(">>> REQUEST\n");
builder.append(request);
builder.append(request.getContent());
System.out.println(builder);
}
public static void logResponse(final Response response) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("<<< RESPONSE\n");
builder.append(response);
if (response.getContentLength() > 0) {
builder.append("... ").append(response.getContentLength()).append(" bytes ...\n");
}
System.out.println(builder);
}
public static void dummyResponse(final Response response) throws IOException {
PrintStream body = response.getPrintStream();
long time = System.currentTimeMillis();
response.set("Content-Type", "text/plain");
response.set("Server", "SSL HelloWorld/1.0 (Simple 4.0)");
response.setDate("Date", time);
response.setDate("Last-Modified", time);
body.println("Hello World: " + ++SimpleSSLHelloWorld.count);
body.close();
}
}
I'm stumped and not really sure why it doesn't work over curl.

Categories

Resources