Wordpress MySQL database query - mysql

I am in the process of setting up a wordpress website that connects to a relay chatroom with an integrated login system, I have connected the database which is working fine however its not allowing the authentication for the users to happen.
The query that i am running in the configuration is:
"SELECT `user_email` AS `email` FROM `wp_users` WHERE `user_login` = #a# AND `user_pass` = MD5(#p#)"
What i am wanting to do is basically have the query check that the user_login exists and then authenticates with the password.
The error that i am currently receiving is as follows:
COMMAND: username#host.host used IDENTIFY and failed to identify to nonexistent account username
This is totally puzzling me now

WordPress doesn't use MD5. So your query is wrong. You can't do it with MySQL only. But you can do it with PHP.
Here is one simple way to achieve it:
Step 1:
Grab class-phpass.php file from WordPress installation (wp-includes directory) and paste it to the neighbour to your request sender file. And use this piece of code there:
require_once("class-phpass.php");
$wp_hasher = new PasswordHash(8, true);
$password='open_password_to_check_here';
$hashed_password='hashed_password_from_mysql'; //select user_pass from wp_users where user_login=#a#;
$result=$wp_hasher->CheckPassword($password,$hashed_password));
//if result is true, then auth is OK.
Alternatively (and the best way) you can use WP REST API, which contains auth process.

Related

Numbers change when querying MySQL/MariaDB through R (RMariaDB)/ Integer conversion in R

I was able to implement a connection from R through RMariaDB and DBI to a remote MariaDB-database. However, I am currently encountering a strange change of numbers when querying the database through R. I'll explain the differences:
I inserted one simple entry in my database with the following command:
INSERT INTO respondent ( id, name ) VALUES ( 2388793051, 'testuser' )
When I connect to this database directly on the remote server and execute a statement like this:
SELECT * FROM respondent;
it delivers these value
id: 2388793051, name: testuser
So I should also be able to connect to the database via R and receive the same results. So when I execute the following code in R, I expect to receive this inserted and saved information displayed above:
library(DBI)
library(RMariaDB)
conn <- DBI::dbConnect(drv=RMariaDB::MariaDB(), user="myusername", password="mypassword", host="127.0.0.1", port="1111", dbname="mydbname")
res <- dbGetQuery(conn, "SELECT * FROM respondent")
print(res)
However, the result of this query is the following
id name
-1906174245 testuser
As you can see, the id is now -1906174245 instead of the saved 2388793051 in the database. I don't understand this weird conversion of integers in the id-field. Can someone explain how this problem emerges and how I might solve it?
EDIT: I don't expect this to be a problem, but just to inform you: I am using an SSH tunnel to enable a connection via these specified ports from my local to my remote machine.
SOLUTION: What made the difference was to specify the id of a respondent in the database specification already as BIGINT instead of INT. Thanks to #JonnyCrunch

Shiro - Cannot authenticate using hashed passwords

I'm attempting to use Shiro for Authentication and Authorization for a JSF Web Application I'm building. Unfortunately, I'm still having some difficulty wrapping my head around how it all fits together.
I've been successful (100% using the shiro.ini file) configuring authentication back to a JDBC realm where a test set of credentials are stored. It has worked perfectly for me when credentials are stored in plaintext.
My ultimate goal is to unify an existing credential set in a MySQL database. The passwords are stored as SHA-256 salted hashes. I've spent an entire day reading over the documentation (minus Javadocs) that is available, but I'm still having some difficulty understanding exactly how to set it up.
In an attempt to implement in stages, I've modified my shiro.ini as follows with the intention of simply using SHA-256 hashes:
[main]
dataSource = org.apache.shiro.jndi.JndiObjectFactory
dataSource.resourceName = jdbc/Communicator_dev
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.dataSource = $dataSource
dataSource.resourceRef = true;
jdbcRealm.authenticationQuery = select password from account where site_id = ?
jdbcRealm.userRolesQuery = select user_role from web_roles where site_id = ?
# From https://stackoverflow.com/questions/20742666/shiro-with-jdbc-and-hashed-passwords.
#
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
#configure the passwordService to use the settings you desire
#...
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordMatcher.passwordService = $passwordService
#...
# Finally, set the matcher on a realm that requires password matching for account authentication:
jdbcRealm.credentialsMatcher = $passwordMatcher
The actual login logic is programmatic in a page backing bean. Here's the simple test source I'm currently using:
// Create auth token
UsernamePasswordToken token = new UsernamePasswordToken(this.siteID, this.password);
// Get the current subject
Subject currentUser = SecurityUtils.getSubject();
// Attempt to login
try {
currentUser.login(token);
} catch (AuthenticationException e) {
System.out.println("Invalid creds.");
return "";
}
return "authenticated.xhtml?faces-redirect=true";
This code works perfectly with plaintext passwords stored in my RDBMS, but now that I've hashed them, It's failing.
From my understanding of the framework, I believe the problem lies with the AuthenticationToken. I know that I need to use a different token to ultimately implement the Salted Hashes stored in my RDBMS, but I'm confused on how to proceed.
(1) I don't want to reinvent the wheel. Does Shiro have something that does this natively? I've checked out Les' links to PasswordMatcher and PasswordService (from link shiro with jdbc and hashed passwords) but this still isn't clear. Do I need to sub-classingPasswordMatcher?
(2) An architecture question: Who actually calls the doCredentialsMatch(..) method? Is it the Realm during the execution of the login(...) method?
(3) The AuthenticationInfo parameter of the doCredentialsMap(...) method .. Is that supplied by the Realm? Since Realms encapsulate the actual security data, is this an object created from, in my case, the SQL queries that return the password from the RDBMS?
Thank you very much for your time! I'm hoping to be able to contribute to the documentation when I get my head wrapped around it all.
Item 1:
I suspect you may be running into this issue involving the "salt style" parameter of the JdbcRealm which defaults to "NO_SALT". This causes hashing to work but if you're adding a salt to your password the realm will be unable to properly match them.
Here are your steps afterwards:
The default query for a COLUMN based salt style is as follows, "select password, password_salt from users where username = ?". If you cannot use that structure you need to provide a new query via your 'shiro.ini' with a similar structure.
jdbcRealm.authenticationQuery=select password, salt_column_here from users where username = ?
Here is a related question.
Item 2: Yes, the realm calls the doCredentialsMatch(..) method.
Item 3: Yes, the realm supplies the AuthenticationInfo to the doCredentialsMatch(..) method.

Backup database(s) using query without using mysqldump

I'd like to dump my databases to a file.
Certain website hosts don't allow remote or command line access, so I have to do this using a series of queries.
All of the related questions say "use mysqldump" which is a great tool but I don't have command line access to this database.
I'd like CREATE and INSERT commands to be created at the same time - basically, the same performance as mysqldump. Is SELECT INTO OUTFILE the right road to travel, or is there something else I'm overlooking - or maybe it's not possible?
Use mysqldump-php a pure-PHP solution to replicate the function of the mysqldump executable for basic to med complexity use cases - I understand you may not have remote CLI and/or mysql direct access, but so long as you can execute via an HTTP request on a httpd on the host this will work:
So you should be able to just run the following purely PHP script straight from a secure-directory in /www/ and have an output file written there and grab it with a wget.
mysqldump-php - Pure PHP mysqldump on GitHub
PHP example:
<?php
require('database_connection.php');
require('mysql-dump.php')
$dumpSettings = array(
'include-tables' => array('table1', 'table2'),
'exclude-tables' => array('table3', 'table4'),
'compress' => CompressMethod::GZIP, /* CompressMethod::[GZIP, BZIP2, NONE] */
'no-data' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true
);
$dump = new MySQLDump('database','database_user','database_pass','localhost', $dumpSettings);
$dump->start('forum_dump.sql.gz');
?>
With your hands tied by your host, you may have to take a rather extreme approach. Using any scripting option your host provides, you can achieve this with just a little difficulty. You can create a secure web page or strait text dump link known only to you and sufficiently secured to prevent all unauthorized access. The script to build the page/text contents could be written to follow these steps:
For each database you want to back up:
Step 1: Run SHOW TABLES.
Step 2: For each table name returned by the above query, run SHOW CREATE TABLE to get the create statement that you could run on another server to recreate the table and output the results to the web page. You may have to prepend "DROP TABLE X IF EXISTS;" before each create statement generated by the results of these queryies (!not in your query input!).
Step 3: For each table name returned from step 1 again, run a SELECT * query and capture full results. You will need to apply a bulk transformation to this query result before outputing to screen to convert each line into an INSERT INTO tblX statement and output the final transformed results to the web page/text file download.
The final web page/text download would have an output of all create statements with "drop table if exists" safeguards, and insert statements. Save the output to your own machine as a ".sql" file, and execute on any backup host as needed.
I'm sorry you have to go through with this. Note that preserving mysql user accounts that you need is something else entirely.
Use / Install PhpMySQLAdmin on your web server and click export. Many web hosts already offer you this as a service pre-configured, and it's easy to install if you don't already have it (pure php): http://www.phpmyadmin.net/
This allows you to export your database(s), as well as perform other otherwise tedious database operations very quickly and easily -- and it works for older versions of PHP < 5.3 (unlike the Mysqldump.php offered as another answer here).
I am aware that the question states 'using query' but I believe the point here is that any means necessary is sought when shell access is not available -- that is how I landed on this page, and PhpMyAdmin saved me!

Wordpress / codeigniter transfer sql database password

I am on a problem which need a quick solution. I will try to explain it.
I have the table wp_user (from WordPress), where all the members have password encrypted with a wordpress encrypting function. And I have to transfer this table to a new Mysql Database on a new web site working with Codeigniter.
For new members on the new site which works under codeigniter, I use the MD5 function in order to mask password.
But the problem is that the two functions are different, so when an older user try to connect on my new web site, that doesn't work because the passwords don't match ...
So, how I can do for translate the wordpress encrpyting in a normal MD5 password?
Or maybe it's not possible?
Unfortunately you'll have to perform both checks, or just change CI to use the same hashing scheme as WP. That's probably the easier option. If you really want to start using the default CI hashing scheme, you could store both hashes and update the new hash on successful login (when you have the plaintext password).
I'm not familiar with what kind of hashing Wordpress uses for passwords, but I assume that it is secure and irreversible. The hashed passwords cannot be converted to their MD5 equivalent because hashing is a one-way algorithm.
Here is my suggestion for you:
Add a using_md5_flag boolean column to the users table in your new website with default value 0. Copy the passwords over from Wordpress into a column wppassword and also create a column called md5password When users log into the system perform the following code (assumes Datamapper ORM, convert to Active Record if you need to):
$u = new User();
$u->where('username', $this->input->post('username'))->get();
$y = new User();
$y->where('username', $this->input->post('username'));
if($u->using_md5_flag){
/*the flag is 1*/
$y->where('md5password', md5($this->input->post('password')));
$y->get();
if($y->exists()) echo "setting cookie and redirecting to logged in area";
else echo "Wrong credentials!";
}
else{
/*the flag is 0, use wordpress's hashing algorithm (not sure what this is)*/
$y->where('wppassword', wp_hashing_algo($this->input->post('password')));
$y->get();
if($y->exists()){
/*set the using_md5_flag flag so next time they log in it will ignore wp's*/
$y->using_md5_flag = 1;
/*set the new md5 password.*/
$y->md5password = md5($this->input->post('password'));
$y->save();
echo "setting cookie and redirecting to logged in area";
}
else{
echo "Wrong credentials.";
}
}
This code hasn't been tested, I wrote it inside StackOverflow's editor... but It's the method I'd take to perform slow conversion to a more secure hash. Lastly, if you're looking for a really secure hash, check out Bcrypt (phpass), it's more resistant to rainbow table attacks.
Update 1: If you need to use the Phpass library with CodeIgniter, you can find a copy I modified here (I added a constructor). Put this in libraries/Phpass.php You can use the library in your controllers using:
$this->load->library("phpass", array("iteration_count_log2" => 8, "portable_hashes" => FALSE));
$check = $this->phpass->CheckPassword($this->input->post('password'), $u->password);
if($check) /*logged in*/
else /*wrong credentials.*/
When you download the Phpass file it comes with a test.php file which demos how the functions work. I suggest reviewing it.

MYSQL Query in Database View

SELECT `aversio`.`module`.`module` AS `module`
FROM
`projectmodule`
JOIN `module` ON `aversio`.`projectmodule`.`moduleID` = `aversio`.`module`.`moduleID`
JOIN `project` ON `aversio`.`project`.`projectID` = `aversio`.`projectmodule`.`projectID`
WHERE `aversio`.`module`.`actief` = _utf8'1'
AND `aversio`.`projectmodule`.`verwijderd` = _utf8'0'
AND `aversio`.`projectmodule`.`verwijderd` = _utf8'0'
MYSQL Error : There is no 'aversio'#'%' registered
What this error mean
That actually looks like a permissions issue, like you are trying to connect as aversio to a MySQL server instance which is not configured to allow that user from any (%) domain.
The syntax 'aversio'#'%' looks like the format 'username'#'host', and mysql uses % as the catch-all (any) host wildcard.
Make sure that you create the MySQL user named aversio, and give them the correct permissions on your DB.
EDIT:
IIRC, a user of that name may exist, but with a different domain (i.e. the users table is keyed on the combo of user and host. I've seen this kind of thing happen when I move code from a dev server to a staging server and try to connect fro mthe new host, having forgotten to modify the permissions in MySQL.