H2 database login issues - database

I am using a local file based H2 Hibernate database with Grails.
I have two separate file type dBs setup in dataSource.groovy:
dataSource {
logSql = false
pooled = true
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:h2:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
}
and
dataSource_publish {
logSql = false
pooled = true
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:h2:/dbmak/devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE"
}
They both produce files in the project root directory:
devDb.h2.db and dbmak.h2.db
The last thing I did in the dB was to modify the 'sa' password - preferring to set it to a non-null value.
I did this by logging into the dbconsole via user 'sa' and then using the command:
set password 'newPassword'
Which seemed to work fine.
However, when I now try and restart the application in the GGTS I get the error:
org.h2.jdbc.JdbcSQLException: Wrong user name or password [28000-173]
I've tried the original null password as well as other login/password combinations that have worked in the past but still get the above error.
One other thing I've done is to replace the h2.db files with recent backed-up copies but still no success. I was wondering if the hibernate system data, containg the 'sa' password, resides elsewhere rather than these individual application databases. If I have a copy of the h2.db files when the system worked I can simply replace it with the modified one that is now failing.
One more thing - when I compare the size of the current (failing - which is 230kb in size) debdb.h2.db file with the backed-up one (which is 1252kb in size) I notice that they are significantly different in size, and when I try and restart the application with the backed-up copy of the db file. After the application fails to start the size goes back to failed size of 230kb.

I have resolved this login issue - as I have two separate Dbs and having set the sa both passwords to a non-null value I have to explicitly define the password for each separate Db.
So, in the DataSource.groovy I now have two sets of login/ password definitions:
dataSource {
username = "sa"
password = "value01"
}
dataSource_publish {
username = "sa"
password = "value02"
}
Without this I believe the login & password is automatically set to 'sa' and "" (i.e: null). And so without the dataSource_publish block on startup the app was attempting, unsuccessfully, to login into the dataSource_publish dB with a null password.
Once you see it it's obvious.

Related

LDAP Error: The user has insufficient access rights. : LdapErr: DSID-0C09099D, comment: Error processing control,

I want to get incremental changes from Active Directory using C# and for that I am trying to build a solution as mentioned in the following article (using DirSync Control).
https://learn.microsoft.com/en-us/windows/win32/ad/polling-for-changes-using-the-dirsync-control
However, I am facing following problems:
When using following code, I am getting exception that The user has insufficient access rights. The user is part of administrators group.
What more permission needs to be given to that account? And how?
LdapConnection connection = new LdapConnection("adfs.fed.zzz.com");
connection.SessionOptions.ProtocolVersion = 3;
connection.Credential = new System.Net.NetworkCredential("adfsfed\\username", "password");
connection.AuthType = AuthType.Basic;
connection.Bind();
var filter = "(&(objectClass=*))";
var searchRequest = new SearchRequest("", filter, SearchScope.Subtree, properties);
DirSyncRequestControl dirSyncRC = new DirSyncRequestControl(null, DirectorySynchronizationOptions.None);
searchRequest.Controls.Add(dirSyncRC);
var response = connection.SendRequest(searchRequest) as SearchResponse;
If I am using below code, then I am not getting any exception but getting empty result in cookie.
String[] properties = { "objectGUID", "sAMAccountName", "displayName", "mail", "member" };
String filter = "(|(objectClass=group)(objectClass=user))";
DirectorySearcher directorySearcher = new DirectorySearcher(myLdapConnection, filter, properties);
var dSynch = new DirectorySynchronization(System.DirectoryServices.DirectorySynchronizationOptions.None);
directorySearcher.DirectorySynchronization = dSynch;
directorySearcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
var results = directorySearcher.FindAll();
var cookie = dSynch.GetDirectorySynchronizationCookie();
Considerations:
I have only one Domain Controller
I am system admin. So, I can assign appropriate permissions to the user.
Please help.
• Your user ID will need the "Replicating Directory Changes" permission and should be a member of ‘Domain Administrators’ group to use the DirSync LDAP control extension. But please note that it pretty much can read anything in the directory partition, regardless of standard permissions. Though they cannot change anything.
However - you may have some attributes that are sensitive in your directory. Please refer the powershell script in the below link and execute it with the user ID after giving appropriate permissions using C#. It is a dirsync code that will retrieve even attributes like ‘userAccountControl, userparameters, msexchuseraccountcontrol, pwdlastset, unicodePwd (BLANK, So no hashed domain password is returned), lockouttime, accountexpires, unixuserpassword(Its Hash is returned).
http://dloder.blogspot.com/2012/01/powershell-dirsync-sample.html
Based on the response given by #KartikBhiwapurkar-MT, I figured out the bug.
The error The user has insufficient access rights is completely misleading (User had already Replicating Directory Changes rights and was part of Domain Administrators group). The error was happening in System.DirectoryServices.Protocols is that I was passing out "" as first parameter (distinguishedName)
new SearchRequest("", filter, SearchScope.Subtree, properties);
but it should have been passed as
new SearchRequest("DC=adfs,DC=fed,DC=zzz,DC=com", filter, SearchScope.Subtree, properties);
I was getting empty cookie in System.DirectoryServices because of bug in latest nuget package (6.0.0). At the time of writing this answer, the bug is still open.
Reference to bug

How can I prevent accidentally overwriting an already existing database?

I'm adding BaseX to an existing web application and currently writing code to import data into it. The documentation is crystal-clear that
An existing database will be overwritten.
Finding this behavior mindboggingly dangerous, I tried it with the hope that the documentation was wrong but unfortunately my test confirmed it. For instance, using basexclient I can do this:
> create db test
Database 'test' created in 12.03 ms.
> create db test
Database 'test' created in 32.43 ms.
>
I can also replicate this behavior with the Python client, which is I what I'm actually using for my application. Reducing my code to the essentials:
session = BaseXClient.Session("127.0.0.1", 1984, "admin", "admin")
session.create("test", "")
It does not matter whether test exists or not, the whole thing is overwritten if it exists.
How can I work around this dangerous default behavior? I'd would like to prevent the possibility of missteps in production.
You can issue a list command before you create your database. For instance with the command line client if the database does not exist:
> list foo
Database 'foo' was not found.
Whereas if the database exists:
> list test
Input Path Type Content-Type Size
------------------------------------
This is a database that is empty so it does not show any contents but at least you do not get the error message. When you use a client you have to check whether it errors out or not. With the Python client you could do:
def exists(session, db):
try:
session.execute("list " + db)
except IOError as ex:
if ex.message == "Database '{0}' was not found.".format(db):
return False
raise
return True
The client raises IOError if the server raises an error, which is a very generic way to report a problem. So you have to test the error message to figure out what is going on. We reraise if it happens that the error message is not the one which pertains to our test. This way we don't swallow exceptions caused by unrelated issues.
With that function you could do:
session = BaseXClient.Session("127.0.0.1", 1984, "admin", "admin")
if exists(session, "test"):
raise SomeRelevantException("Oi! You are about to overwrite your database!")
session.create("test", "")

Yii Dynamic DB Connection according to user with master database

My project is on the basis of multi-tenent SaaS.
I have multiple clients (companies) and each client has multiple users - they all will use the same database layout.
Each client has their own database, so during user authentication, I want to Build a master database that associates the user with a company database for that user.
The structure of each database is identical... only the data is different.
So that we can keep the different database for the different company, that will not going to mix in data in database.
The number of clients (and therefor the number of databases) is unknown when the application is written, so it is not possible to include all the connections in the bootstrap script.
Now, what I want to do is, dynamically alter the DB connection that is in the bootstrap or have the ability to dynamically create a new connection for the user signing in. Is there a simple solution for this in Yii and still use AR , query builder ?
I saw this solution but not working for me http://www.yiiframework.com/forum/index.php?/topic/5385-dynamic-db-connection/
This is how my config file looks today for the script running one database, i want to call a master database that controls which database the user belongs to and the app uses in Yii, any idea?
<? php
$language = 'en';
$currencyBaseCode = 'USD';
$theme = 'default';
$connectionString = 'mysql:host=localhost;port=3306;dbname=master';
$username = 'root';
$password = 'YOUR PASS';
$memcacheServers = array( // An empty array means memcache is not used.
array(
'host' => '127.0.0.1',
'port' => 11211, // This is the default memcached port.
'weight' => 100,
),
);
$adminEmail = 'EMAIL ADDRESS';
$installed = true; // Set to true by the installation process.
$maintenanceMode = false; // Set to true during upgrade process or other maintenance tasks.
$instanceConfig = array(); //Set any parameters you want to have merged into configuration array.
//#see CustomManagement
$instanceConfig['components']['request']['hostInfo'] = 'website url';
$instanceConfig['components']['request']['scriptUrl'] = '/app/index.php';
$urlManager = array (); // Set any parameters you want to customize url manager.
? >
Define the master database in the config file, and use the normal AR class to connect to it to retrieve the credentials. Then, close the connection.
Then extend the AR class, specifically the getDbConnection() method. Get the relevant credentials, and pass them as a parameters to a new CDbConnection object.
The initial DB request to get the credentials is going to be a huge performance drag, so you should really store them in-memory with Redis or Memcached. Yii doesn't do that natively.
There are a few different ways around this:
Different front controllers loading different config files, each of which is dynamically generated or destroyed by a separate app.
One big database. Each record has a key to define which client it belongs to.
One big database. Tables can be duplicated by using a client name as part of the table name.
None of these will be easy with Yii, as this is not really something Yii was designed to do.

Drupal Password set

I have to reset my password direct through database for that I used query
UPDATE users SET pass = md5('NEWPASSWORD') WHERE name = 'admin'
but still I am not able to login.
Can you please tell me where I am going wrong?
With drupal 7, password are no more encrypted through md5.
There are several way to reset a password in drupal7.
Using drush :
drush upwd admin --password="newpassword"
Without drush, if you have a cli access to the server :
cd <drupal root directory>
php scripts/password-hash.sh 'myPassword'
Now copy the resultant hash and paste it into the query:
update users set name='admin', pass='pasted_big_hash_from_above' where uid=1;
If you are working on a remote environment on which you cannot connect, you can put this specified code in a file such as password.php such as this one:
<?php
if (isset($_GET['p'])) {
require_once dirname(__FILE__) . '/includes/bootstrap.inc';
require_once dirname(__FILE__) . '/includes/password.inc';
print _password_crypt('sha512', $_GET['p'], _password_generate_salt(DRUPAL_HASH_COUNT));
exit();
}
print "No password to hash.";
And then hit your site using: http://domain.tld/password.php?p=MyPassword. The hash will appear on your browser's tab.
Don't forget to remove it once you done it.
Are you locked out of your account? If you've got DB access then try clearing out the "flood" table.

Need help debugging a custom authentication plugin for Moodle

I'm trying to authenticate against the user db of my website (CMS based) and it uses a slightly different approach at storing hashed passwords. It uses a randomly generated salt for each user. The salt is stored in the user db along with the hashed passwords. Hence, direct field-mapped authentication (as the External DB plugin does) won't work for me.
To start off, I just mirrored the DB plugin and modified the user_login() procedure to read the hashed password and the salt from the database and then hash the entered password again with the salt and match it up with the password in the database. Here's the code for my user_login() function
function user_login($username, $password) {
global $CFG;
$textlib = textlib_get_instance();
$extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->extencoding);
$extpassword = $textlib->convert(stripslashes($password), 'utf-8', $this->config->extencoding);
$authdb = $this->db_init();
// normal case: use external db for passwords
// Get user data
$sql = "SELECT
*
FROM {$this->config->table}
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ";
$authdb->SetFetchMode(ADODB_FETCH_ASSOC);
// No DB Connection
if ( !$rs = $authdb->Execute( $sql ) ) {
$authdb->Close();
print_error('auth_dbcantconnect','auth');
return false;
}
// No records returned
if( $rs->EOF ) {
$rs->Close();
$authdb->Close();
return false;
}
// Get password
$db_password = $rs->fields['user_password'];
$salt = $rs->fields['user_salt'];
// Close DB Conn
$rs->Close();
$authdb->Close();
// Return match
return sha1( $extpassword . $salt ) == $db_password;
}
But when I try to login, username / passwords corresponding to the website (CMS) database are failing. However, the password (for the same user) that was stored in Moodle earlier on (before I tried using this custom plugin) is getting me through.
That means, either my authentication routine is failing or moodle's internal db based auth mechanism is taking precedence over it.
I've enabled ADODB debug mode - but that isn't helping either. When I enable the debug output from Server settings, the error messages are being sent prior to the page headers. Thus the login page won't display at all.
I have all other forms of authentication turned off (except for Manual which can't be turned off) and my own.
Any ideas on how to solve this issue?
Can you confirm the order that the authentication pluggins are displayed? This will determine the order in which they are used. See..
http://docs.moodle.org/en/Manage_authentication
Either way, the behaviour you're seeing suggests that your code is returning false and the fall through logic described here...
http://moodle.org/mod/forum/discuss.php?d=102070
... and here...
http://docs.moodle.org/en/Development:Authentication_plugins
... is kicking in.
Have you tried returning "true" always from your plugin to ensure that it's being called. Then, you can start returning "true" based upon other things (hard coded usernames etc). This approach will allow you to get to the point where you are either continuing to fail or seeing more targetted failures. Are you sure, for example, that it's the user_login function and not the subsequent call to update_user_record that is failing?
Finally, are you sure you're generating the salted password in the exact same way that it was created in the first place? This would be, for me, the most likely cause of the problem. Can you take control of the creation of the salted password so that you own both creation of new users and authentication of users - this would ensure that you were in sync with how the salted password and hash were generated.

Resources