how to access my lan based postgresql db from my website - c#

We have lan based .Net application with Postgresql 8.1 , now i have task to provide interface on website to read and write two tables on LAN based database I don't know where to start Please help me to solve this problem.
Lan: Windows NT 2003
.Net
Postgresql 8.1
Website:
PHP 5.3
Mysql

You need to enable remote connections on Postgres. But be wary of security implications.
Haven't read it all, but this should give you an idea on the steps to take on the server. For the connector, you generally just need to point the connect function at the remote IP.

Here is how to do the trick. Copied from here:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
in the above code, replace localhost by the IP-address of your Postgres host.

On Linux, two files need to be modified to allow connections other than from localhost:
postgresql.conf, change the listen_addresses = "*" to accept connections from anywhere. Then add a line to the pg_hba.conf file to allow access to the database from a particular IP or network. If you are not worried about security, entering:
host all all 192.168.1.0/24 trust
will allow anyone on the 192.168.1.0/24 network access to any database. Obviously this should only be used to test you can reach the database. Constrain this to the web servers IP address and use md5 so encrypted password authentication is used.

Related

Client having issues connecting to Azure SQL Database

I have built a C# application for my client and I am hosting the database using Microsoft Azure. I found that in order for the client to access the database I need to add their client IP into the firewall configurations. Is there any way that this could be done automatically once they launch the application or if there is another more efficient authentication method which could be used since the application will be download from a website and used by anyone so I would need a method to grant access to anyone who downloads my application. I am fairly new to Microsoft Azure so forgive me if I come off as stupid I just need some advice. Thanks in advance.
Programmatically adding each ip address:
using tsql:
If you want to add ip address to database firewall programatically, you can run the below stored proecedure in the your Azure database.
sp_set_database_firewall_Rule at MSDN
-- Create database-level firewall setting for only IP 0.0.0.4
EXECUTE sp_set_database_firewall_rule N'Example DB Setting 1', '0.0.0.4', '0.0.0.4';
Using Commandline:
You can use SQLCMD.exe to execute stored procedure sp_set_daabase_firewall_rule
Using ADO.NET:Reference Blog Post
String clientIPAddress = Request.UserHostAddress;
using(SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlAzureMaster"].ConnectionString)) {
sqlConnection.Open();
using(SqlCommand sqlCommand = new SqlCommand("sp_set_firewall_rule", sqlConnection)) {
sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlCommand.Parameters.Add("#name", SqlDbType.NVarChar).Value = clientIPAddress;
sqlCommand.Parameters.Add("#start_ip_address", SqlDbType.VarChar).Value = clientIPAddress;
sqlCommand.Parameters.Add("#end_ip_address", SqlDbType.VarChar).Value = clientIPAddress;
sqlCommand.ExecuteNonQuery();
}
}
2.Refreshing the cache post the firewall rules change
Once, you programmatically add the firewall rules, you have to update the authentication cache which is holding logins, firewall rules for the database.
You need to call below command. DBCC FLUSTHAUTHCACHE on msdn
DBCC FLUSHAUTHCACHE
Note: Adding range of ip address for a office network:
If your client will be working from an office network, you can get the range of ip addresses for that office network and add them. It will avoid you to add the ip address every time to the database. Database supports 128 IP configurations at a time. Make sure that you are not going beyond 128 limit.
There's no way can add the client IP into Azure SQL database firewall automatically.
But you can set the firewall range to allow the all database user connect Azure SQL database from any client IP: set the firewall range from:
0.0.0.0---255.255.255.255
But as #Caurav Mantri mentioned, you must need think about the database security issue to protect the SQL database.
Please reference:
ransparent data encryption for SQL Database and Azure Synapse
Always Encrypted: Protect sensitive data and store encryption keys
in Azure Key Vault
Hope this helps.

How to run mysqldump on a remote server via SSH.NET without a password warning?

I'm using the following code to export a copy of MySql database on a remove server using SSH.NET:
using (SshClient client = new SshClient(sshConnectionInfo))
{
client.Connect();
//strCmd is:
// mysqldump -h "<server>.dreamhosters.com" -u "<dbuser>" -p"<actual_password>" "<dbid>" > "/home/<user_name>/<temp_file_name>.sql"
//
// with <...> parts are obviously filled in with correct credentials
SshCommand resCmd = client.RunCommand(strCmd);
//Check result
string strExpDesc = resCmd.Error;
if (string.IsNullOrWhiteSpace(strExpDesc))
{
Console.WriteLine("Exported OK");
}
else
{
Console.WriteLine("Error: " + strExpDesc);
}
}
This worked really well until this month when the shared hosting company (that my database is hosted with) had upgraded their version of Ubuntu server, so the mysqldump command above started returning the following warning:
[Warning] Using a password on the command line interface can be
insecure.
Which my script interprets as an error and fails.
I contacted the hosting company, but their tech support was less than useful. They told me to type in the password instead of specifying it in the command line. Thus my questions:
How to use SSH.NET to interact with the remote server via SSH and send it the password after its prompt?
Otherwise, can I mute that warning from my script w/o having access to the server configuration?
The normal approach to suppressing that warning from MySQL is to put the username and password in an options file, and include the options file in in place of the -u and -p , using the --defaults-extra-file option, e.g.
mysqldump --defaults-extra-file=/path/config.cnf -h "myhost" "<dbid>"
(NOTE: if it's provided, the --defaults-extra-file option must be first option.)
The file would have the user and password options under the [mysqldump] section, something like:
[mysqldump]
user=jonsnow
password=kn0wsn0thing
The credentials could be provided in the [client] section of the optionas file. Since mysqldump is a "standard client" it reads the [client] section.
[client]
user=alannister
password=alwayspayshisdebts
The options file should be properly protected, since it contains credentials. Read permission should be restricted, only the unix user that is connecting via ssh.
chown sshuser /path/config.cnf
chmod 600 /path/config.cnf
(where sshuser is the username used in the ssh connection)
I think there may also be some specific paths and filenames that are automatically included as options files, if they are found, when mysqldump starts. Similar to how MySQL server finds the my.cnf file when it starts. It might be possible to leverage that, in place of explicit --defaults-extra-file option.
MySQL Reference Manual explains usage of options files here:
https://dev.mysql.com/doc/refman/8.0/en/option-files.html
You can write the credentials to input of the remote mysqldump process. But SSH.NET unfortunately does not support providing an input with the CreateCommand interface.
You have to open a shell session (what is otherwise a not recommended approach for automating a command execution).
Use SshClient.CreateShellStream or SshClient.CreateShell and send the mysqldump command and credentials to its input:
"mysqldump ...\nusername\npassword"
For a sample code see C# send Ctrl+Y over SSH.NET.
See also Providing input/subcommands to a command (cli) executed with SSH.NET SshClient.RunCommand.

Windows Service SQL Server error - "Login failed for user"

I have a Windows Service written in C# being run on a Windows Server 2012 R2 machine which connects to a remote SQL Server 2012 instance also on a Windows Server 2012 R2 Server.
The SQL Connection String is defined in the App Config as follows:
<connectionStrings>
<add name="destinationConnectionString" providerName="System.Data.SqlClient"
connectionString="Server=10.42.42.10;Database=mydb;User ID=myuser;Password=mypass" />
</connectionStrings>
When running the service, the output error log shows:
System.Data.SqlClient.SqlException (0x80131904): Login failed for user
'myuser'.
Error Number:18456, State:1, Class:14
So I check the SQL Server Logs to find out more information about the error and find this
Login failed for user myuser Reason: Password did not match for the
login provided"
Source: Logon Message: Error: 18456, Severity: 14, State: 8.
The problem is I know these credentials are correct. I've checked and double checked.
I am able to prove the credentials work by opening SQL Server Management Studio on the source machine, and connecting to the remote SQL Server using the exact same Server, User ID and Password with "SQL Server Authentication" authentication mode.
In fact I have 2 different users that I'm able to connect with using SSMS, but that fail using the Windows service. If I am able to connect to the remote machine using mixed mode auth directly in SSMS. Why not in my Windows service?
I'm at a loss here, could anyone suggest what the issue might be?
Edit: I can even successfully connect to the remote machine using the following command:
sqlcmd -S 10.42.42.10 -U myuser -P mypass -d mydb
The proper syntax for specifying the initial database is:
Server=10.42.42.10;Initial Catalog=mydb;User ID=myuser;Password=mypass
My best guess is that it is ignoring the "Database" in your string and possibly trying to connect to the default database setting for the login (possibly master maybe?) and doesn't have at least public role to it. Although I've found out that "Database" is a valid alternative.
It's possible there is a character in your password that is tripping it up. Semicolons and equal signs will be particularly problematic. Try putting double quotes around your User ID and Password like:
Server=10.42.42.10;Initial Catalog=mydb;User ID="myuser";Password="mypass"
If there's a quotation mark in your password you will have to replace it with two of them for each occurrence.
Once you get your connection string built, then you have to ensure that it will parse properly in XML. Which means escaping control characters and the other special characters such as:
< with <
> with >
& with &
' with &apos;
" with "
If you open up your app config file in a browser it should show you if it looks proper.
I recommend adding the contents of your entire connection string to our output log of your service. That way you can see what it looks like. At the point before you attempt to open the connection, get it with:
string connStr = ConfigurationSettings.AppSettings("myConnectionString");
Then output the connStr value to the log. It will show you what values are being used at least.
You might use some special character in password, that is reserved for XML. If so, you'll need to use escape character as a replacement.
For instance, if your password is PASS<WORD the valid entry in config file would be: PASS<WORD
I have used this site to find the correct pattern
What you have is valid:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Are you trying to connect to an instanced sql server? Server=10.42.42.10/SomeInstance
I suggest adding the semicolon, ;, after the password in the connection string. Perhaps it's being parsed weirdly.
I also wonder whether: is a semicolon in your actual password?
Maybe you're attempting a Windows account but there's also a SQL account named the same way. If so, make sure you prefix the Windows account with the domain name. E.g. you might have Windows account of MYDOMAIN\sa with P#ssword, whilst SQL server account is sa and its password is P#ssw0rd.
To make sure what accounts exists, log in the SQL server as an admin and check what accounts are listed under "Security" node of both the server itself and the database of interest.
I had the same problem and here is my solution:
I found out that I was using named instance of an SQL server and changed Server of my connection string from Server=localhost to Server=localhost\SQLEXPRESS and everything worked just fine for me! :)

MySQL client that can not connect to a database

I'm trying to write a MySQL client in c# to acces a MySQl remote server to get some data and I keep getting this error:
host 192.168.2.1 is not allowed to connect to this mysql server
and I found a solution :
mysql> GRANT ALL ON *.* to root#'192.168.2.1' IDENTIFIED BY 'your-root-password';
mysql> FLUSH PRIVILEGES;
This means that for every IP I should do the same?
I'm will use this in a game so isn't there a better solution?
Use % for all IPs.
GRANT ALL ON *.* to root#'%' IDENTIFIED BY 'your-root-password';
You should consider creating/using other user than root. May be create one specific to your application with access limited to a particular database.
You really should not have root#'%' user. Except that, you can use % as a wildcard character in hosts.
If you want all hosts, use 'user'#'%', if you want all hosts begining with host1 use 'user'#'host1-%', etc.

Database connection troubleshooting

I recently picked up C# programming and am hoping to read in tables from mySQL tables and display them in DataGridView controls. The tables are generated using PHP scripts and I am able to login to my database. In PHP I am using the following connection string:
#mysql_connect('localhost:3307','root','password_string');
In C#, I am using the following connection string:
string MyConString = #"Server=localhost;Database=database_name;User ID=root;Password=password_string";
When I run the program, I get the following message in the console:
"Access denied for user 'root'#'localhost' "
I've tried making countless changes to the connection string by using single quotes, using localhost:3307, etc. I've granted privileges for user root, so I don't think that is the issue. How do I get past this? Is there some problem with the connector I have. Any ideas would be much appreciated.
In PHP you are connecting to the non standard port 3307. You can specify this in the .NET connection string with port=3307:
string MyConString = #"Server=localhost;Database=database_name;User ID=root;Password=password_string;port=3307";
This may be due to PRIVILEGES may be user name do'nt have the required PRIVILEGES
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'#'localhost'
Other reason may be
This is not possible, as the client always uses a socket to connect to "localhost" (which is the default host). For a sucessful connection either the combination of localhost + socket or 127.0.0.1 + port must be specified.
kimiko:~ # mysql -h127.0.0.1 -P3307 -ptest
kimiko:~ # mysql -S/path/to/mysql.sock -ptest

Categories