How to change ldap password using zend - zend-framework

I am working with zend framework, PHP , Ldap on Ubuntu. I am authenticating users from ldap using zend library. Now I want to change user's ldap passwords using zend. Any Idea?
This is the method that I am using to get zend authentication adapter. It is working perfectly and users are authenticated using this adapter.
public function getAuthAdapter(array $params)
{
$front = Zend_Controller_Front::getInstance();
$options = $front->getParam('bootstrap')->getOption('ldap');
$params['username'] = split( "#" , $params['username'] );
$username = 'cn=' . $params['username'][0] . ',' . $options['server1']['baseDn'];
$adapter = new Zend_Auth_Adapter_Ldap( $options, $username, $params['password']);
$adapter->setIdentity( $params['username'] );
$adapter->setCredential( $params['password'] );
return $adapter;
}
Now how to change ldap passwords? Thanks

$ldap=new Zend_Ldap($options);
$ldap->bind();
$entry=$ldap->getEntry($user->dn);
$entry['userpassword'][0]=$newpassword;
$ldap->save($user->dn, $entry);
This is how it worked form me! Note that I did not encript the password before sending but the server stored it with correct encription.

Use Zend_Auth_Adapter_Ldap for authenticating logins and such with an active directory.
For admin purposes of ldap, use Zend_Ldap.
Read the Zend documentation on the Zend_Ldap API, specifically the following
Zend_Ldap save(string|Zend_Ldap_Dn $dn, array $entry)
Saves the entry identified by $dn with
its attributes $entry to the LDAP
tree. Throws a Zend_Ldap_Exception if
the entry could not be saved. This
method decides by querying the LDAP
tree if the entry will be added or
updated.

Related

What is the best way to connect TYPO3 fe_users from an Azure AD with SAML 2?

I need to implement SSO on a TYPO3 intranet, where the fe_users are synchronized from an Azure AD. the platform will be in V9.
Is there a compatible extension that I haven't found yet ?
If no, what would be the best way to implement the automatic authentication with SAML 2.0 ?
thanks in advance,
Rachel
Thanks to #Rakel (and others) I managed to finally solve my SAML authentication requirement. Still I used a slightly different and more direct approach then described in her solution.
I used an Authentication Service to implement the SAML Login Process.
For handling the SAML login itself I used the library SimpleSamlPHP, which I can truly recommend. Its really simple and the provided frontend to test the SAML configuration comes really handy to test the Identity Provider (Idp) configuration without dealing with TYPO3.
For details please look into this: https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html
First you need to create a class which extends TYPO3\CMS\Core\Authentication\AuthenticationService. This class must implement the methods "getUser" and "authUser".
namespace Vendor\Extension\Service;
use SimpleSAML\Auth\Simple;
use TYPO3\CMS\Core\Authentication\AuthenticationService;
class SamlAuth extends AuthenticationService
{
public function getUser() {
// Create new Simple Auth with SimpleSamlPHP
$as = new Simple($config['sp']);
// Require authentication, this redirects you to the Idp and then comes back
$as->requireAuth();
// Get the attributes provides by your Idp
$attributes = $as->getAttributes();
// Please consult the API for details on fetchUserRecord
// Also the SAML attributes may vary depending on your Idp implementation
$user = $this->fetchUserRecord($attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'];
}
public function authUser(array $user): int {
return is_array($user) ? 200 : 0;
}
}
Then you need to register the service in your extensions "ext_localconf.php".
...
TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService(
'my_extension',
'auth',
Vendor\Extension\Service\SamlAuth::class,
[
'title' => 'Saml Authentication for Frontend Users',
'description' => 'Authenticates FeUsers via Saml',
'subtype' => 'authUserFE,getUserFE',
'available' => true,
'priority' => 80,
'quality' => 80,
'os' => '',
'exec' => '',
'className' => Vendor\Extension\Service\SamlAuth::class
]
);
...
Please note:
This is just a over simplified version of my final code. Just to get you started on the idea.
Also you need to configure SimpleSamlPHP correctly. Please look at their documentation for details.
The method "getUser" is supposed to return an array holding the to be logged in FeUser with all its parameters.
The method "authUser" is only to return 200 or 0. Take a look at this link to understand which number are there to return: https://docs.typo3.org/m/typo3/reference-services/7.6/en-us/Authentication/Index.html#authentication-service-chain
After returning "200" the FeUser object is created and the user is logged in. No need to fiddle around with $GLOBALS['TSFE'] by yourself. This is a huge benefit, as it makes your code shorter and easier to read.
Nethertheless I learned a lot from reading through all the documentations and responses here and on Slacks TYPO3 channel.
Thanks to everybody who helped me. Greatly appreciated.
Yes we solved that requirements. We used SimpleSAMLphp to implement the authentication, following this great tutorial :
https://www.lewisroberts.com/2015/09/05/single-sign-on-to-azure-ad-using-simplesamlphp/.
When you are able to connect then you just have to implement a process to auto connect a fe_user when you get the saml user attributes.
Here is a simplified summary of the process:
if we reach a TYPO3 site url without being authenticated then redirection to a script like this :
// SimpleSamlPHP library
require_once (dirname(__FILE__) . /../../../../../../simplesamlphp/lib/_autoload.php');
//instanciation of a simple authentication
$as = new SimpleSAML_Auth_Simple('default-sp');
//requires authentication from Office 365
$as->requireAuth();
//retrieving information from the logged-in user
$attributes = $as->getAttributes();
//retrieve original url
$returnURL = $_GET['returnURL'];
//if a user is well connected
if($attributes){
//redirection to the TYPO3 site with the username
header('Location: /auth/?samlUident='.$attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'][0].'&recupURL='.$returnURL);
}
and here's a simplified summary of what the auth page does:
//if a get saml is in the url
if(\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('samlUident')){
//recovering username for TYPO3 authentication
$loginData = array(
'uname' => \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('samlUident'), //username
'status' => 'login'
);
//TYPO3 session creation
$frontendUserAuthentication = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Authentication\\FrontendUserAuthentication');
$frontendUserAuthentication->checkPid = false;
$info = $frontendUserAuthentication->getAuthInfoArray();
$user_db = $frontendUserAuthentication->fetchUserRecord($info['db_user'], $loginData['uname']);
//if a user exists
if ($user_db){
//authentication
$GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
$GLOBALS['TSFE']->fe_user->dontSetCookie = false;
$GLOBALS['TSFE']->fe_user->start();
$GLOBALS['TSFE']->fe_user->createUserSession($user_db);
$GLOBALS['TSFE']->fe_user->user = $user_db;
$GLOBALS['TSFE']->fe_user->setAndSaveSessionData('dummy', TRUE);
$GLOBALS['TSFE']->fe_user->loginUser = 1;
}
}
Cheers,
Rachel

ejabberd: Saving of roster not working with external Authentication Script enabled

I have successfully configured an ejabberd server with an extauth script (perl).
It is working correctly and only allowing users from my mysql DB.
But following features are not working anymore: roster management, adding users to rosters, authorization of users (for adding them to the roster)
With the internal auth it works. Both times ejabberd is configured to use the internal amnesia db.
Please help me figure out, why it is not working with extauth enabled. Do I have to write my own methods in the extauth script? (That I don't really want...)
So after doing some research on my problem, I think that switching to the external authentication will not support roster management.
What I ended up doing is swichting back to internal authentication and using mod_admin_extra to add users and update passwords with this php script:
<?php
class Jabber
{
public static function registerAndAddToSharedRoster($userId, $sessionToken)
{
$url = "http://localhost:5280/rest";
$register = "register $userId jabber.YOUR_DOMAIN.com $sessionToken";
sendRESTRequest($url, $register);
$sharedRoster = "srg_user_add $userId jabber.YOUR_DOMAIN.com shared jabber.YOUR_DOMAIN.com";
sendRESTRequest($url, $sharedRoster);
}
public static function updatePassword($userId, $newPassword)
{
$url = "http://localhost:5280/rest";
$register = "change_password $userId jabber.YOUR_DOMAIN.com $newPassword";
sendRESTRequest($url, $register);
}
}
function sendRESTRequest ($url, $request)
{
// Create a stream context so that we can POST the REST request to $url
$context = stream_context_create (array ('http' => array ('method' => 'POST'
,'header' => "Host: localhost:5280\nContent-Type: text/html; charset=utf-8\nContent-Length: ".strlen($request)
,'content' => $request)));
$result = file_get_contents($url, false, $context);
return $result;
}
?>
Hope this helps someone!
This answer is late but it could help someone:
Contrary to #ben-marten's answer, Switching to the external authentication does support roster management.
When you add someone to the roster, ejabberd is 'calling' the isuser operation - check if it’s a valid user - you have to provide that method in the script: see ejabberd Developers Guide - External Authentication
I ignored that operation, and I could not add a user to the roster.
For other script examples see Authentication Scripts

Zend framework : Cannot access database configuration through application.ini

I am new to Zend. The problem i am getting is that i am not able to access resources.db.* configurations from application.ini
The way i am using to access is
$application->getOptions()
. It does not shows the resource.db.* properties.
Can any one help me ?
Do this instead
$params = Zend_Db_Table::getDefaultAdapter()->getConfig(); //return associative array
To do it the way you asked about, the easiest way I've found is to put everything in the registry during bootstrap:
//bootstrap.php
public function _initConfig {
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
}
to use these configs elsewhere in your application:
$db = Zend_Registry::get('config')->resources->db;
although if you are just trying to access the adapter registered in the application.ini:
$db = Zend_Db_Table::getDefaultAdapter();

How to verify a login through LDAP in Perl?

I writed a small script that binds to an LDAP server and retrieves all users and user informations. Now I'd like to write another one that binds to the LDAP server and then tests a given login. How can I do that?
my $ldap = ldapConnect();
my $user = 'user';
my $pwd = 'pwd';
# TEST USER AND PWD BUT HOW?
sub ldapConnect {
my $ldap = Net::LDAP->new('192.168.*.*');
my $password = '***';
$ldap->bind('cn=Administrator,cn=Users,DC=***,DC=***', password=> $password);
return $ldap;
}
my $ldap = ldapConnect(); # Connect
my $search = $ldap->search( # Search for the user
base => 'DC=***,DC=***',
scope => 'sub',
filter => "(&(uid=$user))",
attrs => ['dn']
);
die "not found" if not $search->count;
# Get the user's dn and try to bind:
my $user_dn = $search->entry->dn;
$ldap->bind( $user_dn, password => $pass );
print +($ldap->error ? "Bad credentials" : "Success!"), "\n";
Instead of binding as an LDAP administrator, just bind as the user you want to test. If the bind succeeds, the login tests fine. If it fails, it doesn't. This way, you don't have to worry about re-implementing all the authentication logic the LDAP server does in Perl.
Alternatively, as David W. points out, if you need to search for the DN for the user (because the user name isn't the DN), you can first bind either anonymously (if the LDAP server is configured to accept that) or as a known user, search for the DN, then rebind as the user whose account you're trying to check. I suggest using a non-privileged user for the initial search, but of course your administrative user would work too.

Adding authentication functionality to soap server (Using Zend)?

I have a soap server that is created like so:
class ServerController extends Zend_Controller_Action
{
public function serverAction()
{
memcache_flush();
Zend_Registry::get('cache')->clean(Zend_Cache::CLEANING_MODE_ALL);
$server = new SoapServer("http://####/services/soap-server/wsdl");
$server->setClass('SOAP_Server_Map');
$server->handle();
}
}
I want to add authentication to it so that whenever anyone makes a call to a function in "SOAP_Server_Map", it checks that the credentials supplied in the SoapClient options array('login' and 'password') are valid.
Does anyone have any suggestions/help?
To add authentication to either Zend_Soap_Server or Zend_Json_Server, simply specify the HTTP authentication in either your HTTP server (ie: Apache) config or .htaccess file. The following .htaccess file should work:
AuthType Basic
AuthName "Supreme Data Services"
AuthUserFile /var/www/localhost/passwd
Require valid-user
Make sure you keep your password file out of the docroot for security purposes. The password file can be made by using htpasswd that comes with Apache. Naturally, you can use more advanced authentication types.
In order to make use of the service(s), you must now specify a username and password when making a request. If you are using Zend Framework to create your client, you can do the following for SOAP:
$client = new Zend_Soap_Client($wsdl, array('login' => $username, 'password' => $password));
And the following for JSONRPC:
$http = new Zend_Http_Client();
$http->setAuth($username, $password);
$client = new Zend_Json_Client($uri, $http);
Try this: http://pt.php.net/manual/en/soapclient.soapclient.php#101503
I have exactly the same problem and I have the following thoughts:
I do not know if SOAP is/should be state-full or stateless, can we open a session and if the user has supplied some form of credential keep her logged in for some period of time?
The other way I am thinking of solving this is through API-keys, say for example giving a key: ABCDKEY and having the url as:
http://####/services/soap-server/ABCDKEY
This introduces security risks (the magic link attack), but I've seen it implemented in RSS personalized feeds etc.
Any comments?