I'm trying to modify an ActionScript 3 FTP library to support explicit secure (FTP-ES) connections.
With FTP-ES, the client initially makes an insecure FTP connection, then explicitly asks the server to switch to a secure SSL/TLS connection.
Right now, I initially connect to the FTP server with a regular Socket, ask the server to switch to TLS, and then try connect with a SecureSocket after the server returns FTP code 234:
if (code.indexOf('220 ') == 0 || code.indexOf('220-') == 0) { //Send user name
if (_useTLS) {
trace("AUTH TLS");
cmdSocket.writeUTFBytes('AUTH TLS\r\n');
} else {
cmdSocket.writeUTFBytes('USER ' + _username + '\r\n');
}
cmdSocket.flush();
}
if (responseCode.indexOf('234 ') == 0) { //Auth OK, expecting SSL/TLS negotatiation
if (SecureSocket.isSupported) {
secureCommandSocket = new SecureSocket();
secureCommandSocket.addEventListener(ProgressEvent.SOCKET_DATA, onReceivedSCmd);
secureCommandSocket.addEventListener(Event.CONNECT, onConnectSCmd);
secureCommandSocket.addEventListener(IOErrorEvent.IO_ERROR, onSocketError);
secureCommandSocket.addEventListener(Event.CLOSE, onCloseSCmd);
secureCommandSocket.connect(_host, _port);
} else {
throw new Error("Secure socket is not supported on this platform");
}
}
However, the socket returns an IOError 2031 (socket error). Here's the output:
MESSAGE: CONNECTED TO FTP
MESSAGE: Received command: 220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 1 of 50 allowed.
AUTH TLS
MESSAGE: Received command: 234 AUTH TLS OK.
MESSAGE: 2031:Error #2031: Socket Error. URL: xx.xx.xxx.xx
ERROR: Connection failed
With no more information about what's going wrong, I have no idea why the secure socket connection is failing. Is it because I'm trying to switch from a regular Socket to a SecureSocket mid-connection? If so, is there any other way to handle this in AS3?
Related
I know that there are many questions regarding this problem already, and believe me I've looked through all of them.
Some background, I'm using IntelliJ and I've been able to both connect to the database with IntelliJ's data source tool and I've been able to SSH into the server itself using the terminal. For some reason, even if I try to do the same thing with Java it doesn't work. Here's my code:
String serverIP = "123.45.67.890"
String username = "root";
String password = "password";
// Establish SSH tunnel with server if not running locally
try {
if (!Inet4Address.getLocalHost().getHostAddress().equals(ServerIP) {
System.out.println("Remote connection detected.");
System.out.println("Establishing SSH Tunnel...");
JSch jSch = new JSch();
Session session = jSch.getSession(username, ServerIP, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
System.out.printf("Connecting to remote server at %s...\n", ServerIP);
session.connect();
System.out.println("Connected!");
session.setPortForwardingL(3306, ServerIP, 3306);
}
} catch (Exception e) {
e.printStackTrace();
}
// Load mySQL Driver
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
String url = String.format("jdbc:mysql://%s:3306/db_name", ServerIP);
// Connect to database
System.out.println("Connecting to database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
this.connection = connection;
} catch (SQLException e) {
this.connection = null;
throw new IllegalStateException("Cannot connect to database!", e);
}
And here's the error I get:
Remote connection detected.
Establishing SSH Tunnel...
Connecting to remote server at 123.45.67.890...
Connected!
Loading driver...
Driver loaded!
Connecting to database...
java.lang.IllegalStateException: Cannot connect to database!
...
a bunch of crap
...
Caused by: java.sql.SQLException: null, message from server: "Host 'my.personal.computer.local.hostname' is not allowed to connect to this MySQL server"
...
a bunch more crap
...
It seems to me like for some reason, the Java code isn't using the SSH tunnel I put so much effort into copying StackOverflow code to make, and is instead rudely trying to connect normally. What am I doing wrong?
Some more info: The server itself is configured to listen for SQL on 0.0.0.0 and I also set the firewall to accept connections on port 3306.
Edit for clarity: I understand that I can probably fix this by giving my local computer privileges on the server, but I want to be able to connect through SSH.
Solution by OP.
The reason SSH wasn't working was because I needed to use a local open port, connect to SQL through that, then forward that to the remote port 3306. Also, I needed to port forward through localhost, not the server address.
(That is, change the session.setPortForwardingL(3306, ServerIP, 3306); line to session.setPortForwardingL(some-open-port, "localhost", 3306); and "jdbc:mysql://%s:3306/db_name" to "jdbc:mysql://%s:same-open-port/db_name".
I am developing Android mobile application on Windows(OS). I want to send data to couchbase server.
I am making mistake in URL for sync gateway. I am running services on my machine as well. I have already set up couchbase server.
My config.json file:
{
"log": ["HTTP+"],
"adminInterface": "127.0.0.1:4985",
"interface": "0.0.0.0:4984",
"databases": {
"db": {
"server": "http://localhost:8091",
"bucket": "mobile_data",
"users": {
"GUEST": {"disabled": false, "admin_channels": ["*"] }
}
}
}
}
My Android App code:
private void initCouchbase() {
// Create replicators to push & pull changes to & from Sync Gateway.
URL url = null;
try {
url = new URL("http://127.0.0.1:4984/db/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Replication push = database.createPushReplication(url);
Replication pull = database.createPullReplication(url);
push.setContinuous(true);
pull.setContinuous(true);
// Start replicators
push.start();
pull.start();
}
I am using my mobile for testing.
I am getting an error in connection with the URL.
Logcat:
01-28 19:21:23.851 28672-28718/com.example.yumnaasim.couchbaseapp W/RemoteRequest: com.couchbase.lite.replicator.RemoteRequest {GET, http://127.0.0.1:4984/db/_local/3259f53711e089457eaed7b5c61d82403d1a98e4}: executeRequest() Exception: java.net.ConnectException: Failed to connect to /127.0.0.1:4984. url: http://127.0.0.1:4984/db/_local/3259f53711e089457eaed7b5c61d82403d1a98e4
java.net.ConnectException: Failed to connect to /127.0.0.1:4984
at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:187)
at okhttp3.internal.io.RealConnection.buildConnection(RealConnection.java:170)
at okhttp3.internal.io.RealConnection.connect(RealConnection.java:111)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:187)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.execute(RealCall.java:57)
at com.couchbase.lite.replicator.RemoteRequest.executeRequest(RemoteRequest.java:261)
at com.couchbase.lite.replicator.RemoteRequest.execute(RemoteRequest.java:165)
at com.couchbase.lite.replicator.RemoteRequest.run(RemoteRequest.java:105)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
01-28 19:21:23.853 28672-28719/com.example.yumnaasim.couchbaseapp W/RemoteRequest: com.couchbase.lite.replicator.RemoteRequest {GET, http://127.0.0.1:4984/db/_local/3410a851b84016993416af638a20280537838364}: executeRequest() Exception: java.net.ConnectException: Failed to connect to /127.0.0.1:4984. url: http://127.0.0.1:4984/db/_local/3410a851b84016993416af638a20280537838364
java.net.ConnectException: Failed to connect to /127.0.0.1:4984
at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:187)
at okhttp3.internal.io.RealConnection.buildConnection(RealConnection.java:170)
at okhttp3.internal.io.RealConnection.connect(RealConnection.java:111)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:187)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.execute(RealCall.java:57)
at com.couchbase.lite.replicator.RemoteRequest.executeRequest(RemoteRequest.java:261)
at com.couchbase.lite.replicator.RemoteRequest.execute(RemoteRequest.java:165)
at com.couchbase.lite.replicator.RemoteRequest.run(RemoteRequest.java:105)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
01-28 19:21:25.877 28450-28450/? I/Finsky: [1] com.google.android.finsky.scheduler.ak.a(146): onJobSchedulerWakeup
The problem is with your Android app URL. You have http://127.0.0.1:4984/db/. This tries to connect to the Android device itself.
You need to have the external IP address of your server there instead. You configured Sync Gateway correctly with "interface": "0.0.0.0:4984". Beware, though, that you have guest access on ("GUEST": {"disabled": false, "admin_channels": ["*"] }, so you have no security as it stands.
You can reach on localhost with adb reverse port forwarding:
adb reverse tcp:4984 tcp:4984
After port forwarding, that is certain that you will encounter ssl problem. You have three options to solve this issue:
1- Add network security config for permit cleartext on localhost
Easy to apply: https://developer.android.com/training/articles/security-config
Maybe security vulnerability
2- Create and install custom ssl and push emulator/physical devices via adb
Every developer should install certificate to their machine, emulator
and physical devices(Maybe scripting needed)
All service projects which used by Android should serve with ssl
Complexity
3- Permit cleartext globally while debugging
Quick to apply
You shouldn't forget in the prod environment.
Adb Extra:
If you have connected multiple devices, you can select device "-s {deviceId}" parameter
For removing port forwarding, adb forward -remove tcp: {specifiedPort} or -remove-all
following instructions from Jeremy Gooch, see http://goochgooch.co.uk/2014/08/01/building-mosquitto-1-4/, i installed mosquitto over websockets on RPi. i can sub/pub messages to test site http://test.mosquitto.org/ws.html
from that point, i enabled user and topic access control in mosquitto.conf for more tests, but the strange point is that when i start mosquitto again, i see socket errors per second...
sudo /usr/local/sbin/mosquitto -v -c /etc/mosquitto/mosquitto.conf
1429857948: mosquitto version 1.4 (build date 2015-04-20 22:04:51+0800) starting
1429857948: Config loaded from /etc/mosquitto/mosquitto.conf.
1429857948: Opening ipv4 listen socket on port 1883.
1429857948: Opening ipv6 listen socket on port 1883.
1429857948: Warning: Address family not supported by protocol
1429857949: New connection from 127.0.0.1 on port 1883.
1429857949: Sending CONNACK to 127.0.0.1 (0, 5)
1429857949: Socket error on client <unknown>, disconnecting.
1429857950: New connection from 127.0.0.1 on port 1883.
1429857950: Sending CONNACK to 127.0.0.1 (0, 5)
...
i modify the config file to enable ACL only, comment out all others, the socket errors are still there. config file looks now:
sudo nano /etc/mosquitto/mosquitto.conf
autosave_interval 1800
persistence true
persistence_file m2.db
persistence_location /var/tmp/
connection_messages true
log_timestamp true
log_dest stderr
log_type error
log_type warning
log_type debug
allow_anonymous false
password_file /etc/mosquitto/mqtt.pw
acl_file /etc/mosquitto/mqtt.acl
port 1883
protocol mqtt
i even test to use the sample password_file and acl_file, but same error.
searched on google, also no result, could anyone help on this? thanks.
1429857949: Sending CONNACK to 127.0.0.1 (0, 5)
CONNACK return code of 5 means the connection was not authorised. If it
works with allow_anonymous=true, then it sounds like your client isn't
sending a username / or isn't sending a correct username&password.
It looks like you have a Paho Python client running.
I had the same problem my solution was that I wasn't closing the connection. Once I added client.Disconnect() it solved my problem.
Code:
public IEnumerator ooverhere()
{
MqttClient client;
client = new MqttClient(urlPath, port, false, MqttSslProtocols.None, null, null);
client.ProtocolVersion = MqttProtocolVersion.Version_3_1;
byte code = client.Connect(Guid.NewGuid().ToString(), user, pass);
if (code == 0)
{
Debug.Log("successful connection ...");
//client.MqttMsgPublishReceived += client_recievedMessage;
Debug.Log("your client id is: " + client.ClientId);
client.Subscribe(new string[] { "example" }, new byte[] { 0 });
client.Publish("Helpme", Encoding.UTF8.GetBytes("#" + 0));
yield return client;
client.Disconnect();
}
}
Ubuntu machine in internet zone with proxy server.
And i want to connect to remote mysql server mysql -u userName -p -h hostname.
And also i have java application that connect to that remote mysql host using hibernate ORM.
And i can't connect with the server.
Edit
I dont want to use mysql proxy but my database exists on remote server but my local machine have connection to the internet throw web proxy so i can't connect to remote db server.
And when i try connect from machine that has direct access to the internet That Work Perfectly
Trials.
1-System -> Preferences -> Network Proxy.
2- export http_proxy = http:userName:password#proxyserver:port
but that doesn't work.
and help will be appreciated..
Update:
static {
// SOCKS Proxy
System.setProperty("proxySet", "true");
System.setProperty("socksProxyHost", "proxy-host");
System.setProperty("socksProxyPort", "proxy-port");
System.setProperty("http.proxyHost", "proxy-host");
System.setProperty("http.proxyPort", "proxy-port");
System.setProperty("java.net.socks.username", "username");
System.setProperty("java.net.socks.password", "password");
Authenticator.setDefault(new ProxyAuthenticator("username", "password"));
// Open Web Site Work good
try {
URL url = new URL("http://www.kooora.com/");
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
// Read it ...
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
} catch (IOException iOException) {
iOException.printStackTrace();
}
// But open mysql connection throw exception
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection(getDBUrl(), USERNAME, PASSWORD);
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I'm trying to connect to a remote mysql server using a SSH tunnel set up using OpenSSH key file and SSH.Net library as shown in the code section below...
try
{
PrivateKeyFile pkfile = new PrivateKeyFile("C:\\Users\\OpenSSHKey", "mypassword");
var client = new SshClient("servername.com", 22, "myusername", pkfile);
client.Connect();
if (client.IsConnected)
{
var local = new ForwardedPortLocal(22, "localhost", 3306);
client.AddForwardedPort(local);
try
{
local.Start();
}
catch (SocketException se)
{
}
string connStr = "server=localhost;user=mysql_username;database=database_name;port=3306;password=MyDBPassword;";
MySqlConnection sql = new MySqlConnection(connStr);
sql.Ping();
try
{
sql.Open();
}
catch (MySqlException se)
{
}
}
}
catch(Exception e)
{
}
the tunnel is definitely set up because it throws the following error "Unable to connect to any of the specified MySQL hosts" on the sql.Open() call...
Im sure the database is on the server named mysername because I can connect to it using putty or workbench with the credentials used in the MYSQL connection string... I hope someone can help
I've just solved exactly this problem myself. Simply change your ForwardedPortLocal to:
var local = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306);
In your original, you were giving the source port as 22. However, your MySql connection would have been connecting to port 3306 on your local machine (which you would then tunnel across to port 3306 on the destination), so you need to ensure that the forwarded port is listening locally on 3306 to start with.
In addition, I've changed localhost to 127.0.0.1. A secondary issue I tripped over was that localhost on my machine was actually resolving to ::1, an IPv6 address, and the destination server didn't 'speak' IPv6. By switching this to the 127.0.0.1 (IPv4's version of localhost), it ensures that IPv4 is used by default.