Find the algorithm of SSL Symmetric Encryption - ssl

Is there a way we could find what is the algorithm used to encrypt HTTPS requests between server and client after SSL handshake. looking at the network calls, server certificate or browser settings etc.

Using java you can try this.
private void printSSLDetails(){
String https_url = "https://www.google.com/";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
//dumpl all cert info
if(con!=null){
try {
System.out.println("Response Code : " + con.getResponseCode());
System.out.println("Cipher Suite : " + con.getCipherSuite());
System.out.println("\n");
Certificate[] certs = con.getServerCertificates();
for(Certificate cert : certs){
System.out.println("Cert Type : " + cert.getType());
System.out.println("Cert Hash Code : " + cert.hashCode());
System.out.println("Cert Public Key Algorithm : "
+ cert.getPublicKey().getAlgorithm());
System.out.println("Cert Public Key Format : "
+ cert.getPublicKey().getFormat());
System.out.println("\n");
}
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

CXF RESTful Client

I have a rest org.apache.cxf.jaxrs.client.WebClient client for testing:
WebClient client = WebClient.create(URL);
and I want to make https request with cxf jax-rs
How can I do it? Examples?
ok, this is my solution:
public static void configureSSLOnTheClient(WebClient client,
String keyStoreFileName, String keyStorePassword,
String trustStoreFileName, String trustStorePassword) {
HTTPConduit httpConduit = (HTTPConduit) WebClient.getConfig(client).getConduit();
try {
TLSClientParameters tlsParams = new TLSClientParameters();
KeyStore keyStore;
KeyStore trustStore;
try {
keyStore = KeyStore.getInstance("JKS");
keyStore.load(ClassLoader.getSystemResourceAsStream(keyStoreFileName), keyStorePassword.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
trustStore = KeyStore.getInstance("JKS");
trustStore.load(ClassLoader.getSystemResourceAsStream(trustStoreFileName), trustStorePassword.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
tlsParams.setSSLSocketFactory(sslContext.getSocketFactory());
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// These filters ensure that a ciphersuite with export-suitable or null encryption is used,
// but exclude anonymous Diffie-Hellman key change as this is vulnerable to man-in-the-middle attacks
FiltersType filters = new FiltersType();
filters.getInclude().add(".*_EXPORT_.*");
filters.getInclude().add(".*_EXPORT1024_.*");
filters.getInclude().add(".*_WITH_DES_.*");
filters.getInclude().add(".*_WITH_AES_.*");
filters.getInclude().add(".*_WITH_NULL_.*");
filters.getExclude().add(".*_DH_anon_.*");
tlsParams.setCipherSuitesFilter(filters);
httpConduit.setTlsClientParameters(tlsParams);
} catch (Exception exception) {
LOGGER.error("Security configuration failed with the following: " + exception.getCause(), exception);
}
}

Renci.SshNet : "server response does not contain ssh protocol identification"

I'm working with the Renci SSH.Net library on a WPF application and I'm having an issue with using the SFTP client. When the user tries to connect to download some files from the SFTP server he gets the message shown below:
Server response does not contain ssh protocol identification
It doesn't appear to be something specific with the server as I'm able to connect and download the files just fine on my development desktop and a secondary laptop. The same application is able to connect over SSH and run commands without issue, it's just the SFTP connection that appears to be the problem. I'm looking for a little guidance as to where to begin troubleshooting this.
Code for SFTP shown below:
void DownloadPlogs()
{
try
{
SftpClient SFTP;
if (GV.UseCustomPort && GV.CustomPort > 0 && GV.CustomPort < 65535)
{
SFTP = new SftpClient(GV.IpAddress, GV.CustomPort, GV.Username, GV.Password);
}
else
{
SFTP = new SftpClient(GV.IpAddress, 22, GV.Username, "");
}
SFTP.Connect();
DownloadDirectory(SFTP, "/PLOG", Directory.GetCurrentDirectory() + #"\PLOG");
ZipFile.CreateFromDirectory("PLOG", String.Format("{0} - {1} PLOGS.zip", GV.IpAddress, DateTime.Now.ToString("yyyyMMddHHmmss")));
Directory.Delete(Directory.GetCurrentDirectory() + #"\PLOG", true);
SFTP.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Getting PLOGS");
}
}
void DownloadDirectory(SftpClient Client, string Source, string Destination)
{
var Files = Client.ListDirectory(Source);
foreach (var File in Files)
{
if (!File.IsDirectory && !File.IsSymbolicLink)
{
DownloadFile(Client, File, Destination);
}
else if (File.IsSymbolicLink)
{
//Ignore
}
else if (File.Name != "." && File.Name != "..")
{
var Dir = Directory.CreateDirectory(System.IO.Path.Combine(Destination, File.Name));
DownloadDirectory(Client, File.FullName, Dir.FullName);
}
}
}
void DownloadFile(SftpClient Client, Renci.SshNet.Sftp.SftpFile File, string Directory)
{
using (Stream FileStream = System.IO.File.OpenWrite(System.IO.Path.Combine(Directory, File.Name)))
{
Client.DownloadFile(File.FullName, FileStream);
}
}
Code for SSH below:
public SshConnection(string Host, int Port, string Username, string Password)
{
myClient = new SshClient(Host, Port, Username, Password);
myClient.KeepAliveInterval = new TimeSpan(0, 0, 5);
myClient.HostKeyReceived += myClient_HostKeyReceived;
myClient.ErrorOccurred += myClient_ErrorOccurred;
}
void myClient_ErrorOccurred(object sender, Renci.SshNet.Common.ExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "SSH Error Occurred");
}
void myClient_HostKeyReceived(object sender, Renci.SshNet.Common.HostKeyEventArgs e)
{
e.CanTrust = true;
}
public async void Connect()
{
Task T = new Task(() =>
{
try
{
myClient.Connect();
}
catch (System.Net.Sockets.SocketException)
{
MessageBox.Show("Invalid IP Address or Hostname", "SSH Connection Error");
}
catch (Renci.SshNet.Common.SshAuthenticationException ex)
{
MessageBox.Show(ex.Message, "SSH Authentication Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
MessageBox.Show(ex.GetType().ToString());
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
});
T.Start();
await T;
if (T.IsCompleted)
{
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
}
public void Disconnect()
{
try
{
myClient.Disconnect();
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
public void SendData(string Data)
{
try
{
if (Data.EndsWith("\r\n"))
{
RunCommandAsync(Data, SshCommandRx);
}
else
{
RunCommandAsync(String.Format("{0}\r\n",Data), SshCommandRx);
}
//SshCommand Command = myClient.RunCommand(Data);
//OnDataReceived(this, new DataEventArgs(Command.Result));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
private async void RunCommandAsync(String Data, SshCommandCallback Callback)
{
Task<SshCommand> T = new Task<SshCommand>(() =>
{
try
{
SshCommand Command = myClient.RunCommand(Data);
return Command;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
return null;
}
});
T.Start();
await T;
if (T.IsCompleted)
{
Callback(this, T.Result);
}
}
private void SshCommandRx(SshConnection C, SshCommand Command)
{
if (Command != null)
{
string Rx = Command.Result;
//if (Rx.StartsWith(Command.CommandText))
//{
// Rx = Rx.Remove(0, Command.CommandText.Length);
//}
while (Rx.EndsWith("\r\n\r\n") == false)
{
Rx += "\r\n";
}
OnDataReceived(this, new DataEventArgs(Rx));
}
}
I solve it for my self only with connections retrying attempts. Didn't find what exactly the issue is, but have this connection issue many times.
Example:
int attempts = 0;
do
{
try
{
client.Connect();
}
catch (Renci.SshNet.Common.SshConnectionException e)
{
attempts++;
}
} while (attempts < _connectiontRetryAttempts && !client.IsConnected);
I experienced the same odd error message when attempting to connect to a SFTP server while using the SSH.NET library in a program on the server. The problem did not appear while testing from my development machine.
The solution was to have our server team add the IP address of the server into the hosts.allow file on the SFTP Linux server.

Outbound (!) SSL connection Wildfly

our Wildfly 8.1-Server needs to establish an outbound (!) LDAPS-connection to a server within the organization's network. This connection is only used to sync various application data.
Unfortunately, there's no documentation about Wildfly's outbound-only truststore. Every research I do just gives me results about enabling SSL for inbound connections.
How exactly can I add a certificate to Wildfly's truststore for outbound SSL connections? Is there any documentation about this? I'd be thankful for any help on this topic.
Found two possible solutions. First the one i would not use:
System.setProperty("javax.net.ssl.trustStore",path_to_your_cacerts_file);
The second one I'd prefer:
public class LDAPSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory actualSocketFactory;
public LDAPSSocketFactory() {
InputStream certificateInputStream = this.getClass().getClassLoader().getResourceAsStream("yourcert.pfx");
try {
KeyStore pkcs12 = KeyStore.getInstance("pkcs12");
pkcs12.load(certificateInputStream, "".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(pkcs12);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
actualSocketFactory = ctx.getSocketFactory();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
//Override methods by simply deligating them to the actualSocketFactory
}
And pass this as an JNDI param for ldap connections:
env.put("java.naming.ldap.factory.socket", "LDAPSSocketFactory");
Found all of this on StackOverflow, but I forgot where exactly, so I basically pasted their solution here.

SMACK API In Band registration fails with forbidden error

I am using SMACK API's AccountManager class but failed to successfully create a new account. supportsAccountCreation() returns true.
The createAccount method fails with the following error.
D/SMACK: SENT (0): <iq to='xmpp.jp' id='e740L-48' type='set'><query xmlns='jabber:iq:register'><username>MY_NEW_USER</username><password>**********************</password></query></iq>
D/SMACK: RECV (0): <iq from='xmpp.jp' id='e740L-48' type='error'><query xmlns='jabber:iq:register'><username>MY_NEW_USER</username><password>*****************</password></query><error code='403' type='auth'><forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></iq>
W/System.err: org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: forbidden - auth
W/System.err: at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:232)
W/System.err: at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:213)
W/System.err: at org.jivesoftware.smackx.iqregister.AccountManager.createAccount(AccountManager.java:272)
W/System.err: at org.jivesoftware.smackx.iqregister.AccountManager.createAccount(AccountManager.java:244)
..
D/SMACK: SENT (0): <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='SCRAM-SHA-1'>*****************************************</auth>
D/SMACK: RECV (0): <failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><not-authorized/></failure>
UPDATE: Code added here
API v4.1.5
private void initialiseConnection() {
Log.d("xmpp", "Initialising connection");
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(getServer());
config.setHost(getServer());
config.setPort(getPort());
config.setDebuggerEnabled(true);
config.setSendPresence(true);
XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
connection.addConnectionListener(new XMPPConnectionStateHandler(this));
connection.addConnectionListener(new XMPPAccountLoginHandler(this));
connection.addConnectionListener(new XMPPOfflineMessageHandler(this));
connection.addConnectionListener(new XMPPPingMessageHandler(this));
connection.addConnectionListener(new XMPPReconnectionHandler(this));
connection.addConnectionListener(new XMPPPresenceHandler(this));
connection.addConnectionListener(new XMPPDeliveryReceiptHandler(this));
}
public void connect(final String caller) {
if (ConnectionManagerHelper.hasDataConnection(context)){
Log.d(TAG, "Data connection fine");
} else {
Log.d(TAG, "Data connection not avaiable");
}
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected()) return false;
isconnecting = true;
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
connected = true;
notifyConnectionEstablishedEvent();
} catch (IOException e) {
Log.e(TAG, "(" + caller + ")" + " IOException: " + e.getMessage());
notifyConnectionFailureEvent();
} catch (final SmackException e) {
Log.e(TAG, "(" + caller + ")" + " SMACKException: " + e.getMessage());
notifyConnectionFailureEvent();
} catch (final XMPPException e) {
Log.e(TAG, "(" + caller + ")" + " XMPPException: " + e.getMessage());
notifyConnectionFailureEvent();
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login() {
try {
connection.addAsyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws NotConnectedException {
Log.d(TAG, packet.toXML().toString());
notifyMessageStatusReceivedEvent(packet);
}
}, new StanzaFilter() {
#Override
public boolean accept(Stanza stanza) {
return true;
}
});
Log.d(TAG, "Attempting to login as " + loginUser);
connection.login(loginUser, passwordUser);
notifyConnectionConnectedEvent();
} catch (SmackException.AlreadyLoggedInException e){
Log.d(TAG, "Already logged on to chat server");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
//if first login failed, try to create an account and then login
Log.d(TAG, "Login failed. Trying to create a new account.");
register();
}
}
public void register(){
Log.d(TAG, "Attempting to register");
try {
AccountManager accountManager = AccountManager.getInstance(connection);
if (accountManager.supportsAccountCreation()){
Log.d(TAG, "Server supports remote registration");
accountManager.sensitiveOperationOverInsecureConnection(true);
Log.d(TAG, "Sending registration request");
HashMap<String, String> attributes = new HashMap<>();
attributes.put("email", "test#gmail.com");
accountManager.createAccount(loginUser, passwordUser, attributes);
} else {
Log.w(TAG, "Server does not support remote registrations");
}
} catch (XMPPException | SmackException e) {
e.printStackTrace();
}
}
I have spent 3 days already googl-ing and stackoverflow-ing.
Has someone seen and fixed this already?
You have to set access rules for registering new user. I have attached here the complete access rules. You can add this by clicking raw in access rules.
[{access,announce,[{allow,[{acl,admin}]}]},
{access,c2s,[{deny,[{acl,blocked}]},{allow,[all]}]},
{access,c2s_shaper,[{none,[{acl,admin}]},{normal,[all]}]},
{access,configure,[{allow,[{acl,admin}]}]},
{access,local,[{allow,[{acl,local}]}]},
{access,max_user_offline_messages,[{5000,[{acl,admin}]},{100,[all]}]},
{access,max_user_sessions,[{10,[all]}]},
{access,mod_register,[{access_from,register_from},{access,register}]},
{access,register,[{allow,[{acl,local}]}]},
{access,muc_create,[{allow,[{acl,local}]}]},
{access,pubsub_createnode,[{allow,[{acl,local}]}]},
{access,register,[{allow,[all]}]},
{access,register_from,[{allow,[all]}]},
{access,s2s_shaper,[{fast,[all]}]},
{access,trusted_network,[{allow,[{acl,loopback}]}]}]
The below code worked for me,
AccountManager accountManager = AccountManager.getInstance(connection);
try {
if (accountManager.supportsAccountCreation()) {
accountManager.sensitiveOperationOverInsecureConnection(true);
accountManager.createAccount("name", "password");
}
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}

why pwcb.getPassword is null in this code

I try to add the rampart security to my axis2 web service using rampart module.
So here is what I have made:
I have stored in a database the hashed value of "bobWWW" password and the salt
In my PWCBHandler.java class
•I select the stored in the database password and hash
•I try to hash with same algorithm pwcb.getPassword() with the same stored salt
•check if this new hashed password is equal to the stored password
But I constantly was receiving nullpointerexception so I decide to check and wrote this code
if(pwcb.getPassword()==null)
{
try {
throw new Exception ("passwordget pass null" +pwcb.getPassword());
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I see that pwcb.getPassword() is empty. So here is the code of PWCBHandler.java
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
for (int i = 0; i < callbacks.length; i++)
{
WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
try {
pasandsalt = getdataforChecking();
if(pwcb.getPassword()==null)
{
try {
throw new Exception ("passwordget pass null" +pwcb.getPassword());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
passwordforchecking = hash(pwcb.getPassword(),Base64.decodeBase64(pasandsalt[1]));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if((pwcb.getIdentifier().equals("bob")) && (passwordforchecking.equals(pasandsalt[0])) )
{
return;
}
}
And here is my soaprequest with the sequeiry header
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soapenv:Envelope " +
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:nilo=\"http://nilo\">"+
"<soapenv:Header>"+
'<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" soapenv:mustUnderstand="1">'+
'<wsse:UsernameToken xmlns:wsu="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="123">'+
'<wsse:Username>bob</wsse:Username>'+
'<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobWWW</wsse:Password>'+
'</wsse:UsernameToken>'+
'</wsse:Security>'+
"</soapenv:Header>"+
"<soapenv:Body>" +
"<nilo:getdataForChecking>" +
'<nilo:data>'+tranXml+'</nilo:data>' +
' </nilo:getdataForChecking>'+
'</soapenv:Body>' +
'</soapenv:Envelope>';
According to your soap headers i can see you are using a Plain text password instead of Password Digest. You might need to change the rampart configuration
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobWWW</wsse:Password>
this might be helpful to you. http://wso2.com/library/240/