Background
A html page will ask the user to type their username and password. These are credentials for a MySQL database (i.e. they will be used in JDBC connection so that no password is physically stored in the files).
On submit a servlet will be called which tries to connect to the database. If it can, the credentials are correct and a JSP page will load. If not, an error will be displayed.
If the login was a success, the web application will then use servlets perforimng SQL queries/updates on the database and returning Java Beans to JSP pages.
Questions
For memory purposes I'm guessing the JDBC will need to be closed meaning subsequent pages will need to restart the connection using the credentials provided earlier. Obviously the user doesn't want to be providing a password everytime so it's going to have to be stored anyway. If they are stored in a Java object/bean for that session (considering it would have to be plaintext so it could be retrieved and used)...are they susceptible to attack? Is that just a bad as storing it as text within the code?
I'm assuming someone could hack into the session and call the object (if they know this?) with the details in and voila?
What alternatives are there?
Since starting a new connection is so expensive, the connection is saved in the session. Therefore subsequent pages get the same connection object.
As for the security of this: this is as secure as your webserver. If someone can get access to the host and login as the user under which the webserver runs or as root, they can get access to the process.
This doesn't give them access to the credentials, though, since the JDBC driver doesn't save them either (unless you use a global datasource which you don't). They could try to invoke methods on the connection object but that's equivalent to hacking a running Java VM and that's pretty hard to do unless you fail to install all the available security updates.
Related
Is it possible to cache database connections when using PHP like you would in a J2EE container? If so, how?
There is no connection pooling in php.
mysql_pconnect and connection pooling are two different things.
There are many problems connected with mysql_pconnect and first you should read the manual and carefully use it, but this is not connection pooling.
Connection pooling is a technique where the application server manages the connections. When the application needs a connection it asks the application server for it and the application server returns one of the pooled connections if there is one free.
We can do connection scaling in php for that please go through following link: http://www.oracle.com/technetwork/articles/dsl/white-php-part1-355135.html
So no connection pooling in php.
As Julio said apache releases all resources when the request ends for the current reques. You can use mysql_pconnect but you are limited with that function and you must be very careful. Other choice is to use singleton pattern, but none of this is pooling.
This is a good article: https://blogs.oracle.com/opal/highly-scalable-connection-pooling-in-php
Also read this one http://www.apache2.es/2.2.2/mod/mod_dbd.html
Persistent connections are nothing like connection pooling. A persistent connection in php will only be reused if you make multiple db connects within the same request/script execution context. In most typical web dev scenarios you'll max out your connections way faster if you use mysql_pconnect because your script will have no way to get a reference to any open connections on your next request. The best way to use db connections in php is to make a singleton instance of a db object so that the connection is reused within the context of your script execution. This still incurs at least 1 db connect per request, but it's better than making multiple db connects per reqeust.
There is no real db connection pooling in php due to the nature of php. Php is not an application server that can sit there in between requests and manage references to a pool of open connections, at least not without some kind of major hack. I think in theory you could write an app server in php and run it as a commandline script that would just sit there in the background and keep a bunch of db connections open and pass references to them to your other scripts, but I don't know if that would be possible in practice, how you'd pass the references from your commandline script to other scripts, and I sort of doubt it would perform well even if you could pull it off. Anyway that's mostly speculation. I did just notice the link someone else posted to an apache module to allow connection pooling for prefork servers such as php. Looks interesting:
https://github.com/junamai2000/mod_namy_pool#readme
I suppose you're using mod_php, right?
When a PHP file finishes executing all it's state is killed so there's no way (in PHP code) to do connection pooling. Instead you have to rely on extensions.
You can mysql_pconnect so that your connections won't get closed after the page finishes, that way they get reused in the next request.
This might be all that you need but this isn't the same as connection pooling as there's no way to specify the number of connections to maintain opened.
You can use MySQLi.
For more info, scroll down to Connection pooling section # http://www.php.net/manual/en/mysqli.quickstart.connections.php#example-1622
Note that Connection pooling is also dependent on your server (i.e. Apache httpd) and its configuration.
If an unused persistent connection for a given combination of "host, username, password, socket, port and default database can not be found" in the open connection pool, then only mysqli opens a new connection otherwise it would reuse already open available persistent connections, which is in a way similar to the concept of connection pooling. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links (this may be interesting to you to address max_user_connections issue hitting hosting server's limit). The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent.
In wider programming context, it's a task of web/app server however in this context, it's being handled by mysqli directive of PHP itself in a way supporting connection re-usability. You may also implement a singleton class to get a static instance of connection to reuse just like in Java. Just want to remind that java also doesn't support connection pooling as part of its standard JDBC, they're being different module/layers on top of JDBC drivers.
Coming to PHP, the good thing is that for the common databases in the PHP echosystem it does support Persistent Database Connections which persists the connection for 500 requests (config of max_requests in php.ini) and this avoids creating a new connection in each request. So check it out in docs in detail, it solves most of your challenges. Please note that PHP is not so much sophisticated in terms of extensive multi-threading mechanism and concurrent processing together with powerful asynchronous event handling, when compared to strictly object oriented Java. So in a way it is very less effective for PHP to have such in-built mechanism like pooling.
You cannot instantiate connection pools manually.
But you can use the "built in" connection pooling with the mysql_pconnect function.
I would like to suggest PDO::ATTR_PERSISTENT
Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link.
Connection pooling works at MySQL server side like this.
If persistence connection is enabled into MySQL server config then MySQL keep a connection open and in sleep state after requested client (php script) finises its work and die.
When a 2nd request comes with same credential data (Same User Name, Same Password, Same Connection Parameter, Same Database name, Maybe from same IP, I am not sure about the IP) Then MySQL pool the previous connection from sleep state to active state and let the client use the connection. This helps MySQL to save time for initial resource for connection and reduce the total number of connection.
So the connection pooling option is actually available at MySQL server side. At PHP code end there is no option. mysql_pconnect() is just a wrapper that inform PHP to not send connection close request signal at the end of script run.
For features such as connection pooling - you need to install swoole extension first: https://openswoole.com/
It adds async features to php.
After that its trivial to add mysql and redis connection pooling:
https://github.com/open-smf/connection-pool
Some PHP frameworks come with pooling built-in: https://hyperf.wiki/2.2/#/en/pool
Can I Use My Browser to Access MySQL server by sending requests in URL?
I have Tried giving URL of my Server and port to which it is bound send the user name and password in URL as properties and value
http://127.0.0.1:3306/?user=root&password=password
But it gives error like (J���
5.5.28����/,-<&Hv;�ÿ÷�€����������ca>OR08fzTsi�mysql_native_password�!��ÿ„#08S01Got packets out of order)
Does using Any protocol Work?
You are attempting to access a server bound on a port that does not speak the protocol of http, but the socket open request is naturally granted.
Mysql responds in non-http and non-html output, and your browser displays the gobbly-gook. As your browser is naturally not a mysql client with baked in mysql library calls to deal with that handshake, the train just went off the tracks.
Instead of trying to craft an extension to mysql to perform this, it is best to redirect one's focus to the likes of PHP, asp.net, a java back-end middle-ware, etc.
As for passing values like you are in the URL, I suggest you read This Blog Here and jump down to the text showing:
Doesn’t look too bad? Let’s take a look at the URL:
A_URL?domain=&subdomain=sdjflsdhkfhds&name=asdasdf&email=aaaaa#letthemeatspam.com&pass1=ThisIsMyPassword&pass2=ThisIsMyPassword&aggree=yes&error_multiple=&error_domain=&error_subdomain=&error_name=&error_email=&error_pass=2&error_tos=&error_number=&error_js=&error_disposable=1&error_bad_gmail=
Not only is that information sitting in your users cache, it is visible along the way between the user and server (perhaps half a dozen hops) and is logged. If that doesn't raise an eyebrow of concern, I don't know what more to say.
You cannot use your browser to access MySQL without installing a browser-based tool such as phpMyAdmin. I do not recommend this.
Instead, just use the MySQL command line client. From a shell prompt:
mysql -h127.0.0.1 -uroot -p
You will be prompted for your password.
I have an access database that sits on server x iis is running on server y. One of my web pages access data from the access database. If someone has the access database open say a end user on our network the web pages fail with a ...already opened exclusively by another user error message.
I created a local access database and used linked tables in order to access the tables that way. Even still I get the already opened exclusively by another user error. If I go through windows explorer and browse out to server x and open the database I can without issue. So my question is how can I simulate the same type of connectivity to the database without the error being thrown is it a matter of permissions to the access database or something within my connectionstring that would allow me to access the database.
Since it throws the error during my connection.open command I am figuring it is either permission related or something additional I need to add to my connection string. I have granted full control for the IIS AppPool\ on the local directory in which my local instance of the access database resides in but didn't seem to make a difference.
My connection string looks like:
Private Shared connSheriff As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\serverx\directory\Access\MyDatabase.mdb;Jet OLEDB:Database Password=property;")
There are some options within the mdb that change how the database is opened by default, these should be your first port of call particularly setting the "default open mode" to "shared".
You've already split the database (data tables in the shared back-end, linked tables and the rest in the front-end). Make sure that each user uses a separate copy of the front-end mdb, otherwise you'll get locking issues on this.
There is a command line switch (/excl) that sets exclusive mode, but you just omit this to open the db shared so I doubt this is a problem.
You probably already know this but the "Shared" modifier has nothing to do with sharing between applications or users, but shares the connection variable between instances of your class (the c# equivalent is "static")
I have a dilemma which is completely and utterly baffling me...
We have a Classic ASP site which has been running for about a year, its powered via a local Win2008 SQL database (The SQL Express engine is on the same server as IIS). This is the connection string we currently use
Provider=SQLNCLI10;Server=SERVERNAME\SQLEXPRESS;Database=dbname;user id=username;password=password;
We now have a need to move the database to a dedicated DB server, and connect to it remotely - We restored the DB on the server, and checked everything looked ok (All data is present in all tables)
So we changed the server name to the IP address and was unable to get it to connect, in the end the only way we could get it to connect was using this connection string.
driver={SQL Server Native Client 10.0};server=IPADDRESS\SQLEXPRESS,1433;uid=user;pwd=password;database=dbname;
HOWEVER... Now it's randomly missing product names and SKU's and prices in the front and back end, even though the data is present in the DB AND it is REALLY slow to display the webpages? If I use the same DB locally with the previous connection string its fine and all data is appearing?
I know this DB server is fine as it powers other ASP.NET sites with via a remote connection and they are very fast to connect?
Any hints... or help on why this new connection string is causing problems with reading data from the DB???
To update the native client on the web server to the most recent public version, go here:
http://support.microsoft.com/hotfix/KBHotfix.aspx?kbnum=2567714
Check the box for "2008R2_SP1_SNAC_CU2_2567714_10_50_2772_x86" if your web server is an X86 machine, and "2008R2_SP1_SNAC_CU2_2567714_10_50_2772_x64" if it is 64-bit. Enter your e-mail address, fill in the captcha, hit "Request hotfix" and the download link will be e-mailed to you. Download it to the web server, run the installer (using the password sent to you in the e-mail) and restart the web server. Now try your original connection string again.
EDIT
Adding some other sample connection strings that I have used in the past (I've been a classic ASP guy since the 90s, founding and writing 95% of the content on aspfaq.com, including this article on connection strings). As requested in a comment to the original question.
Note that "srv" could be IP address, or localhost, or servername, or . and it could be followed by \INSTANCE_NAME (e.g. \SQLEXPRESS). I would try them in this order, and pay attention to the parameter names as well as the values - you seem to mixing modern parameter names (e.g. Provider) with less modern ones (e.g. Database).
Provider=SQLNCLI10;Data Source=srv;Initial Catalog=db;User ID=user;Password=pwd;
Provider=SQLOLEDB.1;Data Source=srv;Initial Catalog=db;User ID=user;Password=pwd;
Provider=SQLOLEDB;Data Source=srv;Initial Catalog=db;User ID=user;Password=pwd;
Driver={SQL Server};Server=srv;Database=db;UID=user;PWD=pwd;
Sometimes if you are having issues with Named Pipes or Shared Memory it can help to enforce TCP/IP by adding the following parameter:
NETWORK=DBMSSOCN;
You can get a lot more information over at Carl Prothman's site or ConnectionStrings.com. They no longer cater to classic ASP specifically, for obvious reasons, but you can still glean a lot of information from the samples they provide for other languages.
In the web-application I'm developing I currently use a naive solution when connecting to the database:
Connection c = DriverManager.getConnection("url", "username", "password");
This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?
You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:
http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html
In .NET, the convention is to store connectionstrings in a separate config file.
Thereon, the config file can be encrypted.
If you are using Microsoft SQL Server, this all becomes irrelevant if you use a domain account to run the application, which then uses a trusted connection to the database. The connectionstring will not contain any usernames and passwords in that case.
I can recommend these techniques for .NET programmers:
Encrypt password\connection string in config file
Setup trusted connection between client and server (i.e. use windows auth, etc)
Here is useful articles from CodeProject:
Encrypt and Decrypt of ConnectionString in app.config and/or web.config
Unless I am missing the point the connection should be managed by the server via a connection pool, therefore the connection credentials are held by the server and not by the app.
Taking this further I generally build to a convention where the frontend web application (in a DMZ) only talks to the DB via a web service (in domain), therefore providing complete separation and enhanced DB security.
Also, never give priviliges to the db account over or above what is essentially needed.
An alternative approach is to perform all operations via stored procedures, and grant the application user access only to these procs.
Assuming that you are using MS SQL, you can take advantage of windows authentication which requires no ussername/pass anywhere in source code. Otherwise I would have to agree with the other posters recommending app.config + encryption.
Create an O/S user
Put the password in an O/S environment variable for that user
Run the program as that user
Advantages:
Only root or that user can view that user's O/S environment variables
Survives reboot
You never accidentally check password in to source control
You don't need to worry about screwing up file permissions
You don't need to worry about where you store an encryption key
Works x-platform