SSLSocketFactory.createSocket connects using http instead of https - http

I need to make a handshake. I do it with the code below.
I'm running the code in an applet and it works fine when running directly against the server. The problem I have occurs when the same code runs via a proxy.
I'm looking in the java console with trace level 5 activated. Directly after the code line "SSLSocket socket = (SSLSocket) factory.createSocket("www.theserver.com", 443);" is executed
this line appears in the java console "network: Connecting http://www.theserver.com:443 with proxy=DIRECT". After this the applet stops working. I think it is because the
proxy will not allow http traffic on port 443.
Can anyone tell me why it is connecting using http and what I should do to make it connect using https?
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class Handshake
{
class MyHandshakeListener implements HandshakeCompletedListener
{
public void handshakeCompleted(HandshakeCompletedEvent e)
{
System.out.println("Handshake succesful!");
System.out.println("Using cipher suite: " + e.getCipherSuite());
}
}
public void DoHandshake()
{
try
{
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) factory.createSocket("www.theserver.com", 443);
String[] suites = socket.getSupportedCipherSuites();
socket.setEnabledCipherSuites(suites);
socket.addHandshakeCompletedListener(new MyHandshakeListener());
socket.startHandshake();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

I know this is a little late, but we had the exact same problem and was just able to resolve it. The problem was on the client, the "Use SSL 2.0 compatible ClientHello format" was checked on the advanced tab of the Java Control Panel. Uncheck this box on the client and it will connect correctly.

Related

SignalR self host connection issue

I recently created a proof of concept console application using SignalR (self host). It worked a treat for our use. The client connected fine and I was able to send updates from the server to the client. Lovely!
I've now transferred the code from the Console application to a winforms application for a prettier UI. Now that same client won't connect to the server yet it will still connect to the old Console version.
Winforms code:
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
// Let the app know the server is up
}
Console code:
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
Client connection code:
if (!connected)
{
int i = 0;
// Try 3 times
while (i <= 2)
{
try
{
string server = Properties.Settings.Default.Server + ":" + Properties.Settings.Default.PortNumber.ToString();
connection = new HubConnection(server);
connection.StateChanged += connection_StateChanged;
hub = connection.CreateHubProxy("MyHub");
connection.Start().Wait();
hub.On<string>("addMessage", param => { UpdateAlarmStatus(param); });
return true;
}
catch (Exception)
{
i++;
}
}
return false;
}
else
{
return true;
}
The error the client is reporting is:
Exception:Thrown: "No connection could be made because the target machine actively refused it" (System.Net.Sockets.SocketException)
A System.Net.Sockets.SocketException was thrown: "No connection could be made because the target machine actively refused it"
Time: 25/01/2015 15:09:23
Thread:Worker Thread[8232]
Why would the target machine (localhost) refuse itself which the Console version doesn't? I've been looking at the code over and over and I cannot see where I'm going wrong. Can anyone point me in the right direction please?
Thank you for reading.
Paul.
I suspect this is an issue with the configuration of your machine/infrastructure rather than the code itself, which looks fine at first glance.
Have you checked the console debug output in Visual Studio? I recently encountered an issue with similar symptoms and that was what gave me the initial clue to keep investigating. In my particular case, an exception was written to the console debug output that didn't make it to the client.
SignalR will normally negotiate with the server automatically to determine the best transport method to use. In a .NET client, the available options are LongPollingTransport, ServerSentEventsTransport and WebSocketTransport. So for some reason, your console app can use at least one of those methods, whereas your WinForms client cannot.
You can perhaps enable tracing to give you more information to work with. To do this, enter the below before you create the hub proxy:
hubConnection.TraceLevel = TraceLevels.All;
hubConnection.TraceWriter = Console.Out;
ASP.NET doco on SignalR tracing

How to specify credentials from a Java Web Service in PTC Windchill PDMLink

I am currently investigating the possibility of using a Java Web Service (as described by the Info*Engine documentation of Windchill) in order to retrieve information regarding parts. I am using Windchill version 10.1.
I have successfully deployed a web service, which I consume in a .Net application. Calls which do not try to access Windchill information complete successfully. However, when trying to retrieve part information, I get a wt.method.AuthenticationException.
Here is the code that runs within the webService (The web service method simply calls this method)
public static String GetOnePart(String partNumber) throws WTException
{
WTPart part=null;
RemoteMethodServer server = RemoteMethodServer.getDefault();
server.setUserName("theUsername");
server.setPassword("thePassword");
try {
QuerySpec qspec= new QuerySpec(WTPart.class);
qspec.appendWhere(new SearchCondition(WTPart.class,WTPart.NUMBER,SearchCondition.LIKE,partNumber),new int[]{0,1});
// This fails.
QueryResult qr=PersistenceHelper.manager.find((StatementSpec)qspec);
while(qr.hasMoreElements())
{
part=(WTPart) qr.nextElement();
partName = part.getName();
}
} catch (AuthenticationException e) {
// Exception caught here.
partName = e.toString();
}
return partName;
}
This code works in a command line application deployed on the server, but fails with a wt.method.AuthenticationException when performed from within the web service. I feel it fails because the use of RemoteMethodServer is not what I should be doing since the web service is within the MethodServer.
Anyhow, if anyone knows how to do this, it would be awesome.
A bonus question would be how to log from within the web service, and how to configure this logging.
Thank you.
You don't need to authenticate on the server side with this code
RemoteMethodServer server = RemoteMethodServer.getDefault();
server.setUserName("theUsername");
server.setPassword("thePassword");
If you have followed the documentation (windchill help center), your web service should be something annotated with #WebServices and #WebMethod(operationName="getOnePart") and inherit com.ptc.jws.servlet.JaxWsService
Also you have to take care to the policy used during deployment.
The default ant script is configured with
security.policy=userNameAuthSymmetricKeys
So you need to manage it when you consume your ws with .Net.
For logging events, you just need to call the log4j logger instantiated by default with $log.debug("Hello")
You can't pre-authenticate server side.
You can write the auth into your client tho. Not sure what the .Net equivilent is, but this works for Java clients:
private static final String USERNAME = "admin";
private static final String PASSWORD = "password";
static {
java.net.Authenticator.setDefault(new java.net.Authenticator() {
#Override
protected java.net.PasswordAuthentication getPasswordAuthentication() {
return new java.net.PasswordAuthentication(USERNAME, PASSWORD.toCharArray());
}
});
}

SignalR connect error

I use SignalR 2.0.0 Win2012 iis8 with two environment with two different ips.
one environment service is up and second is down(purposely)
use websocket protocol.
i have the following scenario:
When i connect to first environment and want to connect to the second.
i disconnected from first environment and try connect to second environment i get error(its correct behavior)
i try to reconnect back to the first environment but I get still the same error.
the error is "Error during negotiation request."
after refresh the browser i can connect success again to first environment.
What am i doing wrong?
this is part of my code:
function connect(host)
{
var hubConnection = $.hubConnection.('');
hubConnection.url = host;
hubConnection.start()
.done(open)
.fail(error);
}
function open()
{
console.log('login success')
}
function disconnect()
{
var self = this,
hubConnection = $.hubConnection("");
console.log('disconnect ')
hubConnection.stop(true, true);
}
function error(error)
{
var self = this,
hubConnection = $.hubConnection("");
console.log('connection error ')
if(error && hubConnection.state !== $.connection.connectionState.connected)
{
.....
.....
//logic detemninate wich environment ip was previous
connect(environment ip)
}
}
//occured when button disconnect clicked
function disconnectFromFirstEnvironmentAndConnectToSecond()
{
disconect();
connect(second environment ip);
}
.....
.....
connect(first environment ip);
You're not retaining your first connection reference.
Aka you create a HubConnection and then never capture it in a scope that can be used later; therefore when you disconnect later the connection.stop does nothing because it's not calling stop on the HubConnection that was originally started.
This could ultimately lead to you having too many concurrently open requests which will then not allow you to negotiate with a server hence your error.
I'd recommend fixing how you stop/start connections. Next if the issue still occurs I'd inspect the network traffic to ensure that valid requests are being made.

Trying to implement PublicKey Authentication for SFTP test server using Apache Mina. However Authenticate method is not being called

I am using Apache Mina SSHD to implement a test SFTPServer. I have been able to get things working for simple Password authentication, however I am not able to configure things for PublicKey Authentication. I have a implemented the PublickeyAuthenticator interface as follows,
public class SimpleKeyAuthenticator implements PublickeyAuthenticator {
#Override
public boolean authenticate(String username, PublicKey key, ServerSession session) {
System.out.println("In authenticate");
return false;
}
}
My server implementation is as follows,
...
sshd = SshServer.setUpDefaultServer();
sshd.setPort(2222);
//sshd.setPort(config.getSFTPPort());
//sshd.setKeyPairProvider(new
sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider("hostkey.pem"));
//sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
sshd.setPublickeyAuthenticator(new SimpleKeyAuthenticator());
sshd.setFileSystemFactory(new SimpleFileSystemFactory());
List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
userAuthFactories.add(new UserAuthNone.Factory());
sshd.setUserAuthFactories(userAuthFactories);
sshd.setCommandFactory(new ScpCommandFactory());
List<NamedFactory<Command>> namedFactoryList = new ArrayList<NamedFactory<Command>>();
namedFactoryList.add(new SftpSubsystem.Factory());
sshd.setSubsystemFactories(namedFactoryList);
sshd.setSessionFactory(new SimpleSessionFactory(handler));
try {
sshd.start();
} catch (Exception e) {
e.printStackTrace();
}
However when I try to get a file using my SFTP client everything works. I would expect the authenticate method to fail given that it always returns false. I have tried setting the KeyPairProvider to use both the PEMGeneratorHostKeyProvider and the SimpleGeneratorHostKeyProvider. I have also set the PublicKeyAuthenticator to use my SimpleKeyAuthenticator class. Note, when I look at the console output I never see 'In authenticate' so I know that Authenticate is never being called. Could someone please point me to what I have missed? Any help is appreciated.
Regards,
Mark
// below line will make client login without any validation.
userAuthFactories.add(new UserAuthNone.Factory());
You should change it like this:
userAuthFactories.add(new UserAuthPublicKey.Factory());

How to programmatically send an email from a Flash AIR MOBILE app

I am trying to figure out how to send an email from a Flash Mobile (smartphones: blackberries, iphones, androids) app using mxml and Flash using Flash Builder 4.6. My boss told me to find out if it is possible. So far, I have been doing a lot of searching around on the internet for an answer.
I found this website: http://www.bytearray.org/?p=27, that has some classes for sending email in flash, but #1, I don't know if they work in Mobile apps, and #2, I can't find any instructions or tutorials on how to use the classes to send a simple email.
I downloaded the package from the site and imported into my project, where I am trying to send the code. But without sample code on how to simply send an email, I am not entirely sure what all do, and nor am I sure how to determine things like what port number to construct the SMTPMailer object (the SMTPMailer object is included in that package, and it takes a host string and a port number integer in it's constructor), right now I am trying 80 or 8080 for the port number, and I've tried localhost and one of our server computers, 198.162.1.109 for the host.
Anyway, I keep getting this error: Error #2044: Unhandled IOErrorEvent:. text=Error #2031: Socket Error.
Here is some of my sample code:
[Bindable]
private var mailer : SMTPMailer;
private function init() : void {
tbPass.displayAsPassword = true;
}
protected function btnClick_email(toAddress : String, fromAddress : String, pass : String) : void {
mailer = new SMTPMailer("198.168.1.109", 8080);
mailer.addEventListener(SMTPEvent.MAIL_SENT, onMailSent);
mailer.addEventListener(SMTPEvent.MAIL_ERROR, onMailError);
mailer.addEventListener(SMTPEvent.CONNECTED, onConnected);
mailer.addEventListener(SMTPEvent.DISCONNECTED, onDisconnected);
mailer.connect("hotmail.com", 8080);
mailer.authenticate(toAddress, pass);
mailer.sendHTMLMail(fromAddress, toAddress, "Subect", "Message");
}
private function onMailSent() : void {
lblEmailResult.text = "Sent Mail";
}
private function onMailError() : void {
lblEmailResult.text = "Error";
}
private function onConnected() : void {
lblEmailResult.text = "Connected";
}
private function onDisconnected() : void {
lblEmailResult.text = "Disconnected";
}
I would suggest using a back-end service to send emails, it is same as connecting to a SMTP mail server but it is more flexible.
That being said, it should work, the error you are getting is related to your host IP, are you sure you have SMTP server running on "198.168.1.109:8080"?
First check if you can send mails from it before trying to do it trough Flex, if that is OK, then you should double check socket policy files:
http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
Hope that helps
Can't you just use navigateToURL() for this?
Ie:
var request:URLRequest("mailto:someone#somewhere.com");
navigateToURL(request);
That's all - 2 lines :)
I've accomplished this in a commercial app I worked on. We used a native extension found in distriqt's set of tools. Google them. The full suite of tools is cheap, though if you have any issues, do not expect a quick reply. Their message tool is what you are looking for, and it is easy to use.

Resources