Compare commits

..

4 Commits

Author SHA1 Message Date
Deon George
bc6a3bea7a RELEASE 0.9.6c 2009-06-30 19:25:54 +10:00
Deon George
0074652abf RELEASE 0.9.6b 2009-06-30 19:25:27 +10:00
Deon George
e126518f60 RELEASE 0.9.6a 2009-06-30 19:25:05 +10:00
Deon George
7ff3528665 RELEASE 0.9.6 2009-06-30 19:24:29 +10:00
792 changed files with 44015 additions and 52022 deletions

View File

@ -1,14 +0,0 @@
.dockerignore
.editorconfig
.env.testing
.idea
.git*
.phpunit.result.cache
.styleci.yml
node_modules/
package.json
package-lock.json
phpunit.xml
vendor/
webpack.mix.js
yarn.lock

View File

@ -1,18 +0,0 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = tab
insert_final_newline = false
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

View File

@ -1,17 +0,0 @@
APP_NAME=Laravel
APP_ENV=production
APP_KEY=
APP_DEBUG=false
LOG_CHANNEL=daily
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
LDAP_HOST=
LDAP_USERNAME=
LDAP_PASSWORD=
LDAP_CACHE=false
LDAP_ALERT_ROOTDN=true

View File

@ -1,16 +0,0 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
LOG_CHANNEL=stderr
CACHE_DRIVER=array
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
LDAP_HOST=openldap
LDAP_USERNAME="cn=admin,dc=Test"
LDAP_PASSWORD="test"
LDAP_CACHE=false

5
.gitattributes vendored
View File

@ -1,5 +0,0 @@
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore

View File

@ -1,202 +0,0 @@
name: Create Docker Image
run-name: ${{ gitea.actor }} Building Docker Image 🐳
on: [push]
env:
DOCKER_HOST: tcp://127.0.0.1:2375
ASSETS: 2d732e5
jobs:
test:
strategy:
matrix:
arch:
- x86_64
# arm64
name: Test Application
runs-on: docker-${{ matrix.arch }}
container:
image: docker:dind
privileged: true
steps:
- name: Environment Setup
run: |
# If we have a proxy use it
if [ -n "${HTTP_PROXY}" ]; then echo "HTTP PROXY [${HTTP_PROXY}]"; sed -i -e s'/https/http/' /etc/apk/repositories; fi
# Some pre-reqs
apk add git nodejs npm tar zstd
## Some debugging info
# env|sort
- name: Code Checkout
uses: actions/checkout@v4
- name: Build Assets
run: |
# Build assets
npm i
npm run prod
# - name: Run Tests
# run: |
# mv .env.testing .env
# # Install Composer and project dependencies.
# mkdir -p ${COMPOSER_HOME}
# if [ -n "${{ secrets.COMPOSER_GITHUB_TOKEN }}" ]; then composer config github-oauth.github.com ${{ secrets.COMPOSER_GITHUB_TOKEN }}; fi
# composer install
# # Generate an application key. Re-cache.
# php artisan key:generate
# php artisan migrate
# php artisan db:seed
# # run laravel tests
# # XDEBUG_MODE=coverage php vendor/bin/phpunit --coverage-text --colors=never
- name: Cache page assets
id: cache-page-assets
uses: actions/cache@v3
# env:
# cache-name: page-assets
with:
path: |
public/css/app.css
public/fonts
public/images
public/js/app.js
public/js/manifest.js
public/js/vendor.js
#key: build-pla-page-assets-${{ hashFiles('**/package-lock.json') }}
key: build-pla-page-assets-${{ env.ASSETS }}
#restore-keys: |
# build-pla-page-assets-
build:
strategy:
matrix:
arch:
- x86_64
- arm64
needs: [test]
name: Build Docker Image
runs-on: docker-${{ matrix.arch }}
container:
image: docker:dind
privileged: true
env:
ARCH: ${{ matrix.arch }}
steps:
- name: Environment Setup
run: |
# If we have a proxy use it
if [ -n "${HTTP_PROXY}" ]; then echo "HTTP PROXY [${HTTP_PROXY}]"; sed -i -e s'/https/http/' /etc/apk/repositories; fi
# Some pre-reqs
apk add git curl nodejs npm tar zstd
# Start docker
( dockerd --host=tcp://0.0.0.0:2375 --tls=false & ) && sleep 3
## Some debugging info
# docker info && docker version
# env|sort
- name: Registry FQDN Setup
id: registry
run: |
registry=${{ github.server_url }}
echo "registry=${registry##http*://}" >> "$GITHUB_OUTPUT"
- name: Container Registry Login
uses: docker/login-action@v2
with:
registry: ${{ steps.registry.outputs.registry }}
username: ${{ gitea.actor }}
password: ${{ secrets.PKG_WRITE_TOKEN }}
- name: Code Checkout
uses: actions/checkout@v4
- name: Cache page assets
id: cache-page-assets
uses: actions/cache@v3
# env:
# cache-name: page-assets
with:
path: |
public/css/app.css
public/fonts
public/images
public/js/app.js
public/js/manifest.js
public/js/vendor.js
#key: build-pla-page-assets-${{ hashFiles('**/package-lock.json') }}
key: build-pla-page-assets-${{ env.ASSETS }}
#restore-keys: |
# build-pla-page-assets-
- if: ${{ steps.cache-page-assets.outputs.cache-hit != 'true' }}
name: List the state of page assets
continue-on-error: false
run: |
echo CACHE-MISS:${{ steps.cache-page-assets.outputs.cache-hit }}
ls -al public/css/
ls -al public/js/
- name: Record version and Delete Unnecessary files
id: prebuild
run: |
echo ${GITHUB_SHA::8} > VERSION
# [ "${GITHUB_REF_TYPE}" -eq "tag" ] && echo v${GITHUB_REF_NAME}-rel > public/VERSION
rm -rf .git* tests/ storage/app/test/
cat VERSION public/VERSION
# ls -al public/css/
# ls -al public/js/
- name: Build and Push Docker Image
uses: docker/build-push-action@v5
with:
context: .
file: docker/Dockerfile
push: true
tags: "${{ steps.registry.outputs.registry }}/${{ env.GITHUB_REPOSITORY }}:${{ env.GITHUB_REF_NAME }}-${{ env.ARCH }}"
build-args: |
BUILD_REVISION=${{ env.GITHUB_SHA }}
BUILD_VERSION=v${{ env.GITHUB_REF_NAME }}
manifest:
name: Final Docker Image Manifest
runs-on: docker-x86_64
container:
image: docker:dind
privileged: true
needs: [build]
steps:
- name: Environment Setup
run: |
# If we have a proxy use it
if [ -n "${HTTP_PROXY}" ]; then echo "HTTP PROXY [${HTTP_PROXY}]"; sed -i -e s'/https/http/' /etc/apk/repositories; fi
# Some pre-reqs
apk add git curl nodejs
# Start docker
( dockerd --host=tcp://0.0.0.0:2375 --tls=false & ) && sleep 3
- name: Registry FQDN Setup
id: registry
run: |
registry=${{ github.server_url }}
echo "registry=${registry##http*://}" >> "$GITHUB_OUTPUT"
- name: Container Registry Login
uses: docker/login-action@v2
with:
registry: ${{ steps.registry.outputs.registry }}
username: ${{ gitea.actor }}
password: ${{ secrets.PKG_WRITE_TOKEN }}
- name: Build Docker Manifest
run: |
docker manifest create ${{ steps.registry.outputs.registry }}/${{ env.GITHUB_REPOSITORY }}:${{ env.GITHUB_REF_NAME }} \
${{ steps.registry.outputs.registry }}/${{ env.GITHUB_REPOSITORY }}:${{ env.GITHUB_REF_NAME }}-x86_64 \
${{ steps.registry.outputs.registry }}/${{ env.GITHUB_REPOSITORY }}:${{ env.GITHUB_REF_NAME }}-arm64
docker manifest push --purge ${{ steps.registry.outputs.registry }}/${{ env.GITHUB_REPOSITORY }}:${{ env.GITHUB_REF_NAME }}
echo "Built container: ${{ steps.registry.outputs.registry }}/${{ env.GITHUB_REPOSITORY }}:${{ env.GITHUB_REF_NAME }}"

13
.github/FUNDING.yml vendored
View File

@ -1,13 +0,0 @@
# These are supported funding model platforms
github: [leenooks]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: ['https://www.buymeacoffee.com/dege']

View File

@ -1,41 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is. (One issue per report please.)
**Version of PLA**
What version of PLA are you using. Are you using the docker container, an distribution package or running from GIT source?
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem. Also include any logs or backtrace information
**LDAP Server details (please complete the following information):**
- OS: [e.g. iOS]
- Server Name [e.g. OpenLDAP, Windows AD,...]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@ -1 +0,0 @@
blank_issues_enabled: false

19
.gitignore vendored
View File

@ -1,19 +0,0 @@
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
public/css/app.css
public/js/app.js
public/js/vendor.js
public/js/manifest.js
public/fonts/vendor
public/images/vendor
public/mix-manifest.json

37
INSTALL Normal file
View File

@ -0,0 +1,37 @@
For install instructions in non-English languages, see the files
in the "doc" directory.
* Requirements
phpLDAPadmin requires the following:
a. A web server (Apache, IIS, etc).
b. PHP 4.1.0 or newer (with LDAP support)
* To install
1. Unpack the archive (if you're reading this, you already did that).
2. Put the resulting 'phpldapadmin' directory somewhere in your webroot.
3. Copy 'config.php.example' to 'config.php' and edit to taste.
4. Then, point your browser to the phpldapadmin directory.
* For additional help
See the files in the "doc" directory.
Join our mailing list:
https://lists.sourceforge.net/lists/listinfo/phpldapadmin-devel
* Platform specific notes
* OpenBSD with chroot'ed Apache:
For jpeg photos to work properly, you must do this:
# mkdir /var/www/tmp, and then
# chown root:daemon /var/www/tmp
# chmod 1755 /var/www/tmp
Where tmp is the $jpeg_temp_dir configured in config.php
* Windows
For jpeg photos to work properly, be sure to change $jpeg_temp_dir
from "/tmp" to "c:\\temp" or similar.

View File

@ -1,95 +0,0 @@
# phpLDAPadmin
![GitHub commit activity](https://img.shields.io/github/commit-activity/m/leenooks/phpldapadmin)
![Docker Pulls](https://img.shields.io/docker/pulls/phpldapadmin/phpldapadmin)
![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/leenooks/phpldapadmin/total)
![GitHub Release Date](https://img.shields.io/github/release-date/leenooks/phpldapadmin)
![GitHub commits since latest release](https://img.shields.io/github/commits-since/leenooks/phpldapadmin/latest)
phpLDAPadmin is a web based LDAP data management tool for system administrators. It is commonly known and referred by many as "PLA".
PLA is designed to be compliant with LDAP RFCs, enabling it to be used with any LDAP server.
If you come across an LDAP server, where PLA exhibits problems, please open an issue with full details of the problem so that we can have it fixed.
For up to date information on PLA, please head to the [wiki](https://github.com/leenooks/phpLDAPadmin/wiki).
> **NOTE**
> PLA v2 is a complete rewrite of PLA.
>
> PLA v1.2 was written well over 10 years ago for PHP 5, and over time has been patched to work with later versions of PHP. There are logged vulnerabilities with v1.2 that have not been addressed.
>
> Not all PLA v1.2 functionality has been included in v2 (yet) - see below for details
>
> **The release of PHP v2 officially deprecates v1.2, which is no longer supported or enhanced/fixed.** It is recommended to upgrade to v2.
## Demo
If you havent seen PLA in action, you can head here to the [demo](https://demo.phpldapadmin.org) site.
## Running PLA
PLA v2 is now available as a docker container. You can also download the code and install it yourself on your PHP server, or even build your own docker container.
Take a look at the [Docker Container](https://github.com/leenooks/phpLDAPadmin/wiki/Docker-Container) page for more details.
> If you come across any bugs/issues, it would be helpful if you could reproduce those issues using the docker container (or the demo website). This should help confirm that there isnt a site related issue with the issue you are having.
>
> Open an issue (details below) with enough information for me to be able to recreate the problem. An `LDIF` will be invaluable if it is not handling data correctly.
## Templates
Starting with v2.2, PLA reintroduces the template engine. Each point release going forward will improve the template
functionality. Check [releases](https://github.com/leenooks/phpLDAPadmin/releases) for details.
Templates in v2 are in JSON format (in v1 they were XML format). If you want to create your own templates you can use
the [example.json](/templates/example.json) template as a guide. Place your custom templates in a subdirectory
under `templates`, eg: `templates/custom`, and they wont be overwritten by an update.
## Outstanding items
Compare to v1.x, there are a couple of outstanding items to address
Entry Editing:
- [ ] JpegPhoto Create/Delete
- [ ] Binary attribute upload
- [ ] If removing an objectClass, remove all attributes that only that objectclass provided
- [ ] Move an entry
- [ ] Group membership selection
- [ ] Attribute tag creation
Templates Engine
- [ ] Enforcing attribute uniqueness
Raise a [feature request](https://github.com/leenooks/phpLDAPadmin/issues/new) if there is a capability that you would like to see added to PLA.
Other items [under consideration](https://github.com/leenooks/phpLDAPadmin/issues?q=state%3Aopen%20label%3Aenhancement)
## Support is known for these LDAP servers:
- [X] OpenLDAP
- [X] OpenDJ
- [ ] Microsoft Active Directory
- [X] 389 Directory Server
If there is an LDAP server that you have that you would like to have supported, please open an issue to request it.
You might need to provide access, provide a copy or instructions to get an environment for testing. If you have enabled
support for an LDAP server not listed above, please provide a pull request for consideration.
## Getting Help
The best place to get help with PLA (new and old) is on [Stack Overflow](https://stackoverflow.com/tags/phpldapadmin/info).
## Found a bug?
If you have found a bug, and can provide detailed instructions so that it can be reproduced, please open an [issue](https://github.com/leenooks/phpLDAPadmin/issues) and provide those details.
Before opening a ticket, please check to see if it hasnt already been reported, and if it has, please provide any additional information that will help it be fixed.
*TIP*: Issues opened with:
* details enabling the problem to be reproduced,
* including (if appropriate) an LDIF with the data that exhibits the problem,
* a patch (or a git pull request) to fix the problem
will be looked at first :)
## THANK YOU
Over the years, many, many, many people have supported PLA with either their time, their coding or with financial donations.
I have tried to send an email to acknowledge each contribution, and if you havent seen anything personally from me, I am sorry, but please know that I do appreciate all the help I get, in whatever form it is provided.
Again, Thank You.
## License
[LICENSE](LICENSE)

View File

@ -1 +1 @@
00000000 0.9.6c

167
add_attr.php Normal file
View File

@ -0,0 +1,167 @@
<?php
// $Header: /cvsroot/phpldapadmin/phpldapadmin/add_attr.php,v 1.13 2005/04/15 11:46:41 wurley Exp $
/**
* Adds an attribute/value pair to an object
*
* Variables that come in as POST vars:
* - dn
* - server_id
* - attr
* - val
* - binary
*
* @package phpLDAPadmin
*/
/**
*/
require './common.php';
require 'templates/template_config.php';
$server_id = (isset($_POST['server_id']) ? $_POST['server_id'] : '');
$ldapserver = new LDAPServer($server_id);
if( $ldapserver->isReadOnly() )
pla_error( $lang['no_updates_in_read_only_mode'] );
if( ! $ldapserver->haveAuthInfo())
pla_error( $lang['not_enough_login_info'] );
$attr = $_POST['attr'];
$val = isset( $_POST['val'] ) ? $_POST['val'] : false;;
$dn = $_POST['dn'] ;
$is_binary_val = isset( $_POST['binary'] ) ? true : false;
$encoded_dn = rawurlencode( $dn );
$encoded_attr = rawurlencode( $attr );
if( ! $is_binary_val && $val == "" ) {
pla_error( $lang['left_attr_blank'] );
}
// special case for binary attributes (like jpegPhoto and userCertificate):
// we must go read the data from the file and override $val with the binary data
// Secondly, we must check if the ";binary" option has to be appended to the name
// of the attribute.
// Check to see if this is a unique Attribute
if( $badattr = checkUniqueAttr( $ldapserver, $dn, $attr, array($val) ) ) {
$search_href = sprintf('search.php?search=true&form=advanced&server_id=%s&filter=%s=%s',$server_id,$attr,$badattr);
pla_error(sprintf( $lang['unique_attr_failed'],$attr,$badattr,$dn,$search_href ) );
}
if( $is_binary_val ) {
if( 0 == $_FILES['val']['size'] )
pla_error( $lang['file_empty'] );
if( ! is_uploaded_file( $_FILES['val']['tmp_name'] ) ) {
if( isset( $_FILES['val']['error'] ) )
switch($_FILES['val']['error']) {
case 0: //no error; possible file attack!
pla_error( $lang['invalid_file'] );
break;
case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
pla_error( $lang['uploaded_file_too_big'] );
break;
case 2: //uploaded file exceeds the MAX_FILE_SIZE directive specified in the html form
pla_error( $lang['uploaded_file_too_big'] );
break;
case 3: //uploaded file was only partially uploaded
pla_error( $lang['uploaded_file_partial'] );
break;
case 4: //no file was uploaded
pla_error( $lang['left_attr_blank'] );
break;
default: //a default error, just in case! :)
pla_error( $lang['invalid_file'] );
break;
}
else
pla_error( $lang['invalid_file'] );
}
$file = $_FILES['val']['tmp_name'];
$f = fopen( $file, 'r' );
$binary_data = fread( $f, filesize( $file ) );
fclose( $f );
$val = $binary_data;
if( is_binary_option_required( $ldapserver, $attr ) )
$attr .= ";binary";
}
// Automagically hash new userPassword attributes according to the
// chosen in config.php.
if( 0 == strcasecmp( $attr, 'userpassword' ) ) {
if( isset( $servers[$server_id]['default_hash'] ) &&
$servers[$server_id]['default_hash'] != '' ) {
$enc_type = $servers[$server_id]['default_hash'];
$val = password_hash( $val, $enc_type );
}
}
elseif( in_array( $attr,array('sambantpassword','sambalmpassword') ) ){
$mkntPassword = new MkntPasswdUtil();
$mkntPassword->createSambaPasswords( $val );
$val = $mkntPassword->valueOf($attr);
}
$new_entry = array( $attr => $val );
$result = @ldap_mod_add( $ldapserver->connect(), $dn, $new_entry );
if( $result )
header( "Location: edit.php?server_id=$server_id&dn=$encoded_dn&modified_attrs[]=$encoded_attr" );
else
pla_error( $lang['failed_to_add_attr'],ldap_error($ldapserver->connect()),ldap_errno($ldapserver->connect()) );
/**
* Check if we need to append the ;binary option to the name
* of some binary attribute
*
* @param int $server_id Server ID that the attribute is in.
* @param attr $attr Attribute to test to see if it requires ;binary added to it.
* @return bool
*/
function is_binary_option_required( $ldapserver, $attr ) {
// list of the binary attributes which need the ";binary" option
$binary_attributes_with_options = array(
// Superior: Ldapv3 Syntaxes (1.3.6.1.4.1.1466.115.121.1)
'1.3.6.1.4.1.1466.115.121.1.8' => "userCertificate",
'1.3.6.1.4.1.1466.115.121.1.8' => "caCertificate",
'1.3.6.1.4.1.1466.115.121.1.10' => "crossCertificatePair",
'1.3.6.1.4.1.1466.115.121.1.9' => "certificateRevocationList",
'1.3.6.1.4.1.1466.115.121.1.9' => "authorityRevocationList",
// Superior: Netscape Ldap attributes types (2.16.840.1.113730.3.1)
'2.16.840.1.113730.3.1.40' => "userSMIMECertificate"
);
// quick check by attr name (short circuits the schema check if possible)
//foreach( $binary_attributes_with_options as $oid => $name )
//if( 0 == strcasecmp( $attr, $name ) )
//return true;
$schema_attr = get_schema_attribute( $ldapserver, $attr );
if( ! $schema_attr )
return false;
$syntax = $schema_attr->getSyntaxOID();
if( isset( $binary_attributes_with_options[ $syntax ] ) )
return true;
return false;
}
?>

199
add_attr_form.php Normal file
View File

@ -0,0 +1,199 @@
<?php
// $Header: /cvsroot/phpldapadmin/phpldapadmin/add_attr_form.php,v 1.11 2005/03/05 06:27:06 wurley Exp $
/**
* Displays a form for adding an attribute/value to an LDAP entry.
*
* Variables that come in as GET vars:
* - dn (rawurlencoded)
* - server_id
*
* @package phpLDAPadmin
*/
/**
*/
require './common.php';
$server_id = (isset($_GET['server_id']) ? $_GET['server_id'] : '');
$ldapserver = new LDAPServer($server_id);
if( $ldapserver->isReadOnly() )
pla_error( $lang['no_updates_in_read_only_mode'] );
if( ! $ldapserver->haveAuthInfo())
pla_error( $lang['not_enough_login_info'] );
$dn = $_GET['dn'];
$encoded_dn = rawurlencode( $dn );
$rdn = get_rdn( $dn );
$friendly_attrs = process_friendly_attr_table();
include './header.php'; ?>
<body>
<h3 class="title"><?php echo sprintf( $lang['add_new_attribute'], htmlspecialchars( $rdn ) ); ?></b></h3>
<h3 class="subtitle"><?php echo $lang['server']; ?>: <b><?php echo $ldapserver->name; ?></b> &nbsp;&nbsp;&nbsp; <?php echo $lang['distinguished_name']; ?>: <b><?php echo htmlspecialchars( ( $dn ) ); ?></b></h3>
<?php $attrs = get_object_attrs( $ldapserver, $dn );
$oclasses = get_object_attr( $ldapserver, $dn, 'objectClass' );
if( ! is_array( $oclasses ) )
$oclasses = array( $oclasses );
$avail_attrs = array();
$schema_oclasses = get_schema_objectclasses( $ldapserver, $dn );
foreach( $oclasses as $oclass ) {
$schema_oclass = get_schema_objectclass( $ldapserver, $oclass, $dn );
if( $schema_oclass && 0 == strcasecmp( 'objectclass', get_class( $schema_oclass ) ) )
$avail_attrs = array_merge( $schema_oclass->getMustAttrNames( $schema_oclasses ),
$schema_oclass->getMayAttrNames( $schema_oclasses ),
$avail_attrs );
}
$avail_attrs = array_unique( $avail_attrs );
$avail_attrs = array_filter( $avail_attrs, "not_an_attr" );
sort( $avail_attrs );
$avail_binary_attrs = array();
foreach( $avail_attrs as $i => $attr ) {
if( is_attr_binary( $ldapserver, $attr ) ) {
$avail_binary_attrs[] = $attr;
unset( $avail_attrs[ $i ] );
}
}
?>
<br />
<center>
<?php echo $lang['add_new_attribute'];
if( is_array( $avail_attrs ) && count( $avail_attrs ) > 0 ) { ?>
<br />
<br />
<form action="add_attr.php" method="post">
<input type="hidden" name="server_id" value="<?php echo $server_id; ?>" />
<input type="hidden" name="dn" value="<?php echo htmlspecialchars($dn); ?>" />
<select name="attr">
<?php $attr_select_html = '';
usort($avail_attrs,"sortAttrs");
foreach( $avail_attrs as $a ) {
// is there a user-friendly translation available for this attribute?
if( isset( $friendly_attrs[ strtolower( $a ) ] ) ) {
$attr_display = htmlspecialchars( $friendly_attrs[ strtolower( $a ) ] ) . " (" .
htmlspecialchars($a) . ")";
} else {
$attr_display = htmlspecialchars( $a );
}
echo $attr_display;
$attr_select_html .= "<option>$attr_display</option>\n";
echo "<option value=\"" . htmlspecialchars($a) . "\">$attr_display</option>";
} ?>
</select>
<input type="text" name="val" size="20" />
<input type="submit" name="submit" value="<?php echo $lang['add']; ?>" class="update_dn" />
</form>
<?php } else { ?>
<br />
<br />
<small>(<?php echo $lang['no_new_attrs_available']; ?>)</small>
<br />
<br />
<?php } ?>
<?php echo $lang['add_new_binary_attr'];
if( count( $avail_binary_attrs ) > 0 ) { ?>
<!-- Form to add a new BINARY attribute to this entry -->
<form action="add_attr.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="server_id" value="<?php echo $server_id; ?>" />
<input type="hidden" name="dn" value="<?php echo $dn; ?>" />
<input type="hidden" name="binary" value="true" />
<br />
<select name="attr">
<?php $attr_select_html = '';
usort($avail_binary_attrs,"sortAttrs");
foreach( $avail_binary_attrs as $a ) {
// is there a user-friendly translation available for this attribute?
if( isset( $friendly_attrs[ strtolower( $a ) ] ) ) {
$attr_display = htmlspecialchars( $friendly_attrs[ strtolower( $a ) ] ) . " (" .
htmlspecialchars($a) . ")";
} else {
$attr_display = htmlspecialchars( $a );
}
echo $attr_display;
$attr_select_html .= "<option>$attr_display</option>\n";
echo "<option value=\"" . htmlspecialchars($a) . "\">$attr_display</option>";
} ?>
</select>
<input type="file" name="val" size="20" />
<input type="submit" name="submit" value="<?php echo $lang['add']; ?>" class="update_dn" />
<?php if( ! ini_get( 'file_uploads' ) )
echo "<br><small><b>" . $lang['warning_file_uploads_disabled'] . "</b></small><br>";
else
echo "<br><small><b>" . sprintf( $lang['max_file_size'], ini_get( 'upload_max_filesize' ) ) . "</b></small><br>";
?>
</form>
<?php } else { ?>
<br />
<br />
<small>(<?php echo $lang['no_new_binary_attrs_available']; ?>)</small>
<?php } ?>
</center>
</body>
</html>
<?php
/**
* Given an attribute $x, this returns true if it is NOT already specified
* in the current entry, returns false otherwise.
*
* @param attr $x
* @return bool
* @ignore
*/
function not_an_attr( $x ) {
global $attrs;
//return ! isset( $attrs[ strtolower( $x ) ] );
foreach( $attrs as $attr => $values )
if( 0 == strcasecmp( $attr, $x ) )
return false;
return true;
}
?>

70
add_oclass.php Normal file
View File

@ -0,0 +1,70 @@
<?php
// $Header: /cvsroot/phpldapadmin/phpldapadmin/add_oclass.php,v 1.14 2005/03/20 04:43:36 wurley Exp $
/**
* Adds an objectClass to the specified dn.
*
* Note, this does not do any schema violation checking. That is
* performed in add_oclass_form.php.
*
* Variables that come in as POST vars:
* - dn (rawurlencoded)
* - server_id
* - new_oclass
* - new_attrs (array, if any)
*
* @package phpLDAPadmin
*/
/**
*/
require './common.php';
$server_id = (isset($_POST['server_id']) ? $_POST['server_id'] : '');
$ldapserver = new LDAPServer($server_id);
if( $ldapserver->isReadOnly() )
pla_error( $lang['no_updates_in_read_only_mode'] );
if( ! $ldapserver->haveAuthInfo())
pla_error( $lang['not_enough_login_info'] );
$dn = rawurldecode( $_POST['dn'] );
$new_oclass = $_POST['new_oclass'];
$new_attrs = $_POST['new_attrs'];
$encoded_dn = rawurlencode( $dn );
if( is_attr_read_only( $ldapserver, 'objectClass' ) )
pla_error( "ObjectClasses are flagged as read only in the phpLDAPadmin configuration." );
$new_entry = array();
$new_entry['objectClass'] = $new_oclass;
$new_attrs_entry = array();
$new_oclass_entry = array( 'objectClass' => $new_oclass );
if( is_array( $new_attrs ) && count( $new_attrs ) > 0 )
foreach( $new_attrs as $attr => $val ) {
// Check to see if this is a unique Attribute
if( $badattr = checkUniqueAttr( $ldapserver, $dn, $attr, array($val) ) ) {
$search_href = sprintf('search.php?search=true&form=advanced&server_id=%s&filter=%s=%s',$server_id,$attr,$badattr);
pla_error(sprintf( $lang['unique_attr_failed'],$attr,$badattr,$dn,$search_href ) );
}
$new_entry[ $attr ] = $val;
}
//echo "<pre>";
//print_r( $new_entry );
//exit;
$add_res = @ldap_mod_add( $ldapserver->connect(), $dn, $new_entry );
if( ! $add_res ) {
pla_error( $lang['could_not_perform_ldap_mod_add'],ldap_error($ldapserver->connect()),ldap_errno($ldapserver->connect()) );
} else {
header( "Location: edit.php?server_id=$server_id&dn=$encoded_dn&modified_attrs[]=objectclass" );
}
?>

132
add_oclass_form.php Normal file
View File

@ -0,0 +1,132 @@
<?php
// $Header: /cvsroot/phpldapadmin/phpldapadmin/add_oclass_form.php,v 1.18 2005/03/12 14:03:36 wurley Exp $
/**
* This page may simply add the objectClass and take you back to the edit page,
* but, in one condition it may prompt the user for input. That condition is this:
*
* If the user has requested to add an objectClass that requires a set of
* attributes with 1 or more not defined by the object. In that case, we will
* present a form for the user to add those attributes to the object.
*
* Variables that come in as REQUEST vars:
* - dn (rawurlencoded)
* - server_id
* - new_oclass
*
* @package phpLDAPadmin
*/
/**
*/
require './common.php';
$server_id = (isset($_REQUEST['server_id']) ? $_REQUEST['server_id'] : '');
$ldapserver = new LDAPServer($server_id);
if( $ldapserver->isReadOnly() )
pla_error( $lang['no_updates_in_read_only_mode'] );
if( ! $ldapserver->haveAuthInfo())
pla_error( $lang['not_enough_login_info'] );
$new_oclass = $_REQUEST['new_oclass'];
$dn = rawurldecode( $_REQUEST['dn'] );
$encoded_dn = rawurlencode( $dn );
/* Ensure that the object has defined all MUST attrs for this objectClass.
* If it hasn't, present a form to have the user enter values for all the
* newly required attrs. */
$entry = get_object_attrs( $ldapserver, $dn, true );
$current_attrs = array();
foreach( $entry as $attr => $junk )
$current_attrs[] = strtolower($attr);
// grab the required attributes for the new objectClass
$oclass = get_schema_objectclass( $ldapserver, $new_oclass );
if( $oclass )
$must_attrs = $oclass->getMustAttrs();
else
$must_attrs = array();
// We don't want any of the attr meta-data, just the string
//foreach( $must_attrs as $i => $attr )
//$must_attrs[$i] = $attr->getName();
// build a list of the attributes that this new objectClass requires,
// but that the object does not currently contain
$needed_attrs = array();
foreach( $must_attrs as $attr ) {
$attr = get_schema_attribute( $ldapserver, $attr->getName() );
//echo "<pre>"; var_dump( $attr ); echo "</pre>";
// First, check if one of this attr's aliases is already an attribute of this entry
foreach( $attr->getAliases() as $alias_attr_name )
if( in_array( strtolower( $alias_attr_name ), $current_attrs ) )
// Skip this attribute since it's already in the entry
continue;
if( in_array( strtolower($attr->getName()), $current_attrs ) )
continue;
// We made it this far, so the attribute needs to be added to this entry in order
// to add this objectClass
$needed_attrs[] = $attr;
}
if( count( $needed_attrs ) > 0 ) {
include './header.php'; ?>
<body>
<h3 class="title"><?php echo $lang['new_required_attrs']; ?></h3>
<h3 class="subtitle"><?php echo $lang['requires_to_add'] . ' ' . count($needed_attrs) .
' ' . $lang['new_attributes']; ?></h3>
<small>
<?php echo $lang['new_required_attrs_instructions'];
echo ' ' . count( $needed_attrs ) . ' ' . $lang['new_attributes'] . ' ';
echo $lang['that_this_oclass_requires']; ?>
</small>
<br />
<br />
<form action="add_oclass.php" method="post">
<input type="hidden" name="new_oclass" value="<?php echo htmlspecialchars( $new_oclass ); ?>" />
<input type="hidden" name="dn" value="<?php echo $encoded_dn; ?>" />
<input type="hidden" name="server_id" value="<?php echo $server_id; ?>" />
<table class="edit_dn" cellspacing="0">
<tr><th colspan="2"><?php echo $lang['new_required_attrs']; ?></th></tr>
<?php foreach( $needed_attrs as $count => $attr ) { ?>
<tr><td class="attr"><b><?php echo htmlspecialchars($attr->getName()); ?></b></td></tr>
<tr><td class="val"><input type="text" name="new_attrs[<?php echo htmlspecialchars($attr->getName()); ?>]" value="" size="40" /></tr>
<?php } ?>
</table>
<br />
<br />
<center><input type="submit" value="<?php echo $lang['add_oclass_and_attrs']; ?>" /></center>
</form>
</body>
</html>
<?php } else {
$add_res = @ldap_mod_add( $ldapserver->connect(), $dn, array( 'objectClass' => $new_oclass ) );
if( ! $add_res )
pla_error( "Could not perform ldap_mod_add operation.",
ldap_error( $ldapserver->connect() ),ldap_errno( $ldapserver->connect() ) );
else
header( "Location: edit.php?server_id=$server_id&dn=$encoded_dn&modified_attrs[]=objectClass" );
}
?>

75
add_value.php Normal file
View File

@ -0,0 +1,75 @@
<?php
// $Header: /cvsroot/phpldapadmin/phpldapadmin/add_value.php,v 1.17 2005/03/12 10:42:27 wurley Exp $
/**
* Adds a value to an attribute for a given dn.
*
* Variables that come in as POST vars:
* - dn (rawurlencoded)
* - attr (rawurlencoded) the attribute to which we are adding a value
* - server_id
* - new_value (form element)
* - binary
*
* On success, redirect to the edit_dn page. On failure, echo an error.
*
* @package phpLDAPadmin
*/
/**
*/
require './common.php';
$server_id = (isset($_POST['server_id']) ? $_POST['server_id'] : '');
$ldapserver = new LDAPServer($server_id);
if( $ldapserver->isReadOnly() )
pla_error( $lang['no_updates_in_read_only_mode'] );
if( ! $ldapserver->haveAuthInfo())
pla_error( $lang['not_enough_login_info'] );
$attr = $_POST['attr'];
$new_value = $_POST['new_value'];
$dn = rawurldecode( $_POST['dn'] );
$is_binary_val = isset( $_POST['binary'] ) ? true : false;
$encoded_dn = rawurlencode( $dn );
$encoded_attr = rawurlencode( $attr );
if( is_attr_read_only( $ldapserver, $attr ) )
pla_error(sprintf($lang['attr_is_read_only'],htmlspecialchars( $attr )));
// special case for binary attributes:
// we must go read the data from the file.
if( $is_binary_val ) {
$file = $_FILES['new_value']['tmp_name'];
$f = fopen( $file, 'r' );
$binary_value = fread( $f, filesize( $file ) );
fclose( $f );
$new_value = $binary_value;
}
$new_entry = array( $attr => $new_value );
// Check to see if this is a unique Attribute
if( $badattr = checkUniqueAttr( $ldapserver, $dn, $attr, $new_entry ) ) {
$search_href = sprintf('search.php?search=true&form=advanced&server_id=%s&filter=%s=%s',$server_id,$attr,$badattr);
pla_error(sprintf( $lang['unique_attr_failed'],$attr,$badattr,$dn,$search_href ) );
}
// Call the custom callback for each attribute modification
// and verify that it should be modified.
if( run_hook ( 'pre_attr_add', array ( 'server_id' => $server_id, 'dn' => $dn, 'attr_name' => $attr,
'new_value' => $new_entry ) ) ) {
$add_result = @ldap_mod_add( $ldapserver->connect(), $dn, $new_entry );
if( ! $add_result )
pla_error( $lang['could_not_perform_ldap_mod_add'], ldap_error( $ldapserver->connect() ), ldap_errno( $ldapserver->connect() ) );
}
header( "Location: edit.php?server_id=$server_id&dn=$encoded_dn&modified_attrs[]=$encoded_attr" );
?>

213
add_value_form.php Normal file
View File

@ -0,0 +1,213 @@
<?php
// $Header: /cvsroot/phpldapadmin/phpldapadmin/add_value_form.php,v 1.29 2005/03/12 14:03:36 wurley Exp $
/**
* Displays a form to allow the user to enter a new value to add
* to the existing list of values for a multi-valued attribute.
*
* Variables that come in as GET vars:
* - dn (rawurlencoded)
* - attr (rawurlencoded) the attribute to which we are adding a value
* - server_id
*
* @package phpLDAPadmin
*/
/**
*/
require './common.php';
$server_id = (isset($_GET['server_id']) ? $_GET['server_id'] : '');
$ldapserver = new LDAPServer($server_id);
if( $ldapserver->isReadOnly() )
pla_error( $lang['no_updates_in_read_only_mode'] );
if( ! $ldapserver->haveAuthInfo())
pla_error( $lang['not_enough_login_info'] );
$attr = $_GET['attr'];
$dn = isset( $_GET['dn'] ) ? $_GET['dn'] : null;
$encoded_dn = rawurlencode( $dn );
$encoded_attr = rawurlencode( $attr );
if( null != $dn ) {
$rdn = get_rdn( $dn );
} else {
$rdn = null;
}
$current_values = get_object_attr( $ldapserver, $dn, $attr );
$num_current_values = ( is_array($current_values) ? count($current_values) : 0 );
$is_object_class = ( 0 == strcasecmp( $attr, 'objectClass' ) ) ? true : false;
$is_jpeg_photo = is_jpeg_photo( $ldapserver, $attr ); //( 0 == strcasecmp( $attr, 'jpegPhoto' ) ) ? true : false;
if( $is_object_class ) {
// fetch all available objectClasses and remove those from the list that are already defined in the entry
$schema_oclasses = get_schema_objectclasses( $ldapserver );
foreach( $current_values as $oclass )
unset( $schema_oclasses[ strtolower( $oclass ) ] );
} else {
$schema_attr = get_schema_attribute( $ldapserver, $attr );
}
include './header.php'; ?>
<body>
<h3 class="title">
<?php echo $lang['add_new']; ?>
<b><?php echo htmlspecialchars($attr); ?></b>
<?php echo $lang['value_to']; ?>
<b><?php echo htmlspecialchars($rdn); ?></b></h3>
<h3 class="subtitle">
<?php echo $lang['server']; ?>:
<b><?php echo $ldapserver->name; ?></b> &nbsp;&nbsp;&nbsp;
<?php echo $lang['distinguished_name']; ?>: <b><?php echo htmlspecialchars( $dn ); ?></b></h3>
<?php echo $lang['current_list_of']; ?> <b><?php echo $num_current_values; ?></b>
<?php echo $lang['values_for_attribute']; ?> <b><?php echo htmlspecialchars($attr); ?></b>:
<?php if ($num_current_values) { ?>
<?php if( $is_jpeg_photo ) { ?>
<table><tr><td>
<?php draw_jpeg_photos( $ldapserver, $dn, $attr, false ); ?>
</td></tr></table>
<!-- Temporary warning until we find a way to add jpegPhoto values without an INAPROPRIATE_MATCHING error -->
<p><small>
<?php echo $lang['inappropriate_matching_note']; ?>
</small></p>
<!-- End of temporary warning -->
<?php } else if( is_attr_binary( $ldapserver, $attr ) ) { ?>
<ul>
<?php if( is_array( $vals ) ) {
for( $i=1; $i<=count($vals); $i++ ) {
$href = sprintf('download_binary_attr.php?server_id=%s&amp;dn=%s&amp;attr=%s&amp;value_num=%s',
$server_id,$encoded_dn,$attr,$i-1); ?>
<li><a href="<?php echo $href; ?>"><img src="images/save.png" /> <?php echo $lang['download_value'] . ' ' . $i; ?>)</a></li>
<?php }
} else {
$href = sprintf('download_binary_attr.php?server_id=%s&amp;dn=%s&amp;attr=%s',$server_id,$encoded_dn,$attr); ?>
<li><a href="<?php echo $href; ?>"><img src="images/save.png" /> <?php echo $lang['download_value']; ?></a></li>
<?php } ?>
</ul>
<!-- Temporary warning until we find a way to add jpegPhoto values without an INAPROPRIATE_MATCHING error -->
<p><small>
<?php echo $lang['inappropriate_matching_note']; ?>
</small></p>
<!-- End of temporary warning -->
<?php } else { ?>
<ul class="current_values">
<?php if( is_array( $current_values ) ) /*$num_current_values > 1 )*/ {
foreach( $current_values as $val ) { ?>
<li><nobr><?php echo htmlspecialchars(($val)); ?></nobr></li>
<?php } ?>
<?php } else { ?>
<li><nobr><?php echo htmlspecialchars(($current_values)); ?></nobr></li>
<?php } ?>
</ul>
<?php } ?>
<?php } else { ?>
<br />
<br />
<?php } ?>
<?php echo $lang['enter_value_to_add']; ?>
<br />
<br />
<?php if( $is_object_class ) { ?>
<form action="add_oclass_form.php" method="post" class="new_value">
<input type="hidden" name="server_id" value="<?php echo $server_id; ?>" />
<input type="hidden" name="dn" value="<?php echo $encoded_dn; ?>" />
<select name="new_oclass">
<?php foreach( $schema_oclasses as $name => $oclass ) {
// exclude any structural ones, as they'll only generate an LDAP_OBJECT_CLASS_VIOLATION
if ($oclass->type == "structural") continue; ?>
<option value="<?php echo $oclass->getName(); ?>"><?php echo $oclass->getName(); ?></option>
<?php } ?>
</select>
<input type="submit" value="<?php echo $lang['add_new_objectclass']; ?>" />
<br />
<?php if( show_hints() ) { ?>
<small>
<br />
<img src="images/light.png" /><span class="hint"><?php echo $lang['new_required_attrs_note']; ?></span>
</small>
<?php }
} else { ?>
<form action="add_value.php" method="post" class="new_value" name="new_value_form"<?php
if( is_attr_binary( $ldapserver, $attr ) ) echo "enctype=\"multipart/form-data\""; ?>>
<input type="hidden" name="server_id" value="<?php echo $server_id; ?>" />
<input type="hidden" name="dn" value="<?php echo $encoded_dn; ?>" />
<input type="hidden" name="attr" value="<?php echo $encoded_attr; ?>" />
<?php if( is_attr_binary( $ldapserver, $attr ) ) { ?>
<input type="file" name="new_value" />
<input type="hidden" name="binary" value="true" />
<?php } else {
if( is_multi_line_attr( $attr, $server_id ) ) { ?>
<textarea name="new_value" rows="3" cols="30"></textarea>
<?php } else { ?>
<input type="text" <?php if( $schema_attr->getMaxLength() ) echo "maxlength=\"" . $schema_attr->getMaxLength() . "\" "; ?>name="new_value" size="40" value="" />
<?php // draw the "browse" button next to this input box if this attr houses DNs:
if( is_dn_attr( $ldapserver, $attr ) )
draw_chooser_link( "new_value_form.new_value", false ); ?>
<?php }
} ?>
<input type="submit" name="submit" value="<?php echo $lang['add_new_value']; ?>" />
<br />
<?php if( $schema_attr->getDescription() ) { ?>
<small><b><?php echo $lang['desc']; ?>:</b> <?php echo $schema_attr->getDescription(); ?></small><br />
<?php } ?>
<?php if( $schema_attr->getType() ) { ?>
<small><b><?php echo $lang['syntax']; ?>:</b> <?php echo $schema_attr->getType(); ?></small><br />
<?php } ?>
<?php if( $schema_attr->getMaxLength() ) { ?>
<small><b><?php echo $lang['maximum_length']; ?>:</b> <?php echo number_format( $schema_attr->getMaxLength() ); ?> <?php echo $lang['characters']; ?></small><br />
<?php } ?>
</form>
<?php } ?>
</body>
</html>

3
app/.gitignore vendored
View File

@ -1,3 +0,0 @@
q*
!public/
!.gitignore

View File

@ -1,425 +0,0 @@
<?php
namespace App\Classes\LDAP;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use App\Classes\LDAP\Schema\AttributeType;
use App\Classes\Template;
use App\Exceptions\InvalidUsage;
use App\Ldap\Entry;
/**
* Represents an attribute of an LDAP Object
*/
class Attribute implements \Countable, \ArrayAccess
{
// Is this attribute an internal attribute
protected ?bool $_is_internal = NULL;
protected(set) bool $no_attr_tags = FALSE;
// MIN/MAX number of values
protected(set) int $min_values_count = 0;
protected(set) int $max_values_count = 0;
// The schema's representation of this attribute
protected(set) ?AttributeType $schema;
// The DN this object is in
protected(set) string $dn;
// The old values for this attribute - helps with isDirty() to determine if there is an update pending
private Collection $_values_old;
// Current Values
private Collection $_values;
// The objectclasses of the entry that has this attribute
protected(set) Collection $oc;
private const SYNTAX_CERTIFICATE = '1.3.6.1.4.1.1466.115.121.1.8';
private const SYNTAX_CERTIFICATE_LIST = '1.3.6.1.4.1.1466.115.121.1.9';
/*
# Has the attribute been modified
protected $modified = false;
# Is the attribute being deleted because of an object class removal
protected $forcedelete = false;
# Is the attribute visible
protected $visible = false;
protected $forcehide = false;
# Is the attribute modifiable
protected $readonly = false;
# LDAP attribute type MUST/MAY
protected $ldaptype = null;
# Attribute property type (eg password, select, multiselect)
protected $type = '';
# Attribute value to keep unique
protected $unique = false;
# Display parameters
protected $display = '';
protected $icon = '';
protected $hint = '';
# Helper details
protected $helper = array();
protected $helpervalue = array();
# Onchange details
protected $onchange = array();
# Show spacer after this attribute is rendered
protected $spacer = false;
protected $verify = false;
# Component size
protected $size = 0;
# Value max length
protected $maxlength = 0;
# Text Area sizings
protected $cols = 0;
protected $rows = 0;
# Public for sorting
public $page = 1;
public $order = 255;
public $ordersort = 255;
# Schema Aliases for this attribute (stored in lowercase)
protected $aliases = array();
# Configuration for automatically generated values
protected $autovalue = array();
protected $postvalue = array();
*/
/**
* Create an Attribute
*
* @param string $dn DN this attribute is used in
* @param string $name Name of the attribute
* @param array $values Current Values
* @param array $oc The objectclasses that the DN of this attribute has
* @throws InvalidUsage
*/
public function __construct(string $dn,string $name,array $values,array $oc=[])
{
$this->dn = $dn;
$this->_values = collect($values);
$this->_values_old = collect($values);
$this->schema = config('server')
->schema('attributetypes',$name);
$this->oc = collect();
// Get the objectclass heirarchy for required attribute determination
foreach ($oc as $objectclass) {
$soc = config('server')->schema('objectclasses',$objectclass);
if ($soc) {
$this->oc->push($soc->oid);
$this->oc = $this->oc->merge($soc->getParents()->pluck('oid'));
}
}
/*
# Should this attribute be hidden
if ($server->isAttrHidden($this->name))
$this->forcehide = true;
# Should this attribute value be read only
if ($server->isAttrReadOnly($this->name))
$this->readonly = true;
# Should this attribute value be unique
if ($server->isAttrUnique($this->name))
$this->unique = true;
*/
}
public function __call(string $name,array $arguments)
{
abort(555,'Method not handled: '.$name);
}
public function __get(string $key): mixed
{
return match ($key) {
// Can this attribute have more values
'can_addvalues' => $this->schema && (! $this->schema->is_single_value) && ((! $this->max_values_count) || ($this->values->count() < $this->max_values_count)),
// Schema attribute description
'description' => $this->schema ? $this->schema->{$key} : NULL,
// Attribute hints
'hints' => $this->hints(),
// Attribute language tags
'langtags' => ($this->no_attr_tags || (! $this->_values->count()))
? collect(Entry::TAG_NOTAG)
: $this->_values
->keys()
->filter(fn($item)=>($item === Entry::TAG_NOTAG) || preg_match(sprintf('/%s;?/',Entry::TAG_CHARS_LANG),$item))
->sortBy(fn($item)=>($item === Entry::TAG_NOTAG) ? NULL : $item),
// Can this attribute be edited
'is_editable' => $this->schema ? $this->schema->{$key} : NULL,
// Is this an internal attribute
'is_internal' => is_null($this->_is_internal) ? ($this->used_in->count() === 0) : $this->_is_internal,
// Objectclasses that required this attribute for an LDAP entry
'required' => $this->required(),
// Is this attribute an RDN attribute
'is_rdn' => $this->isRDN(),
// We prefer the name as per the schema if it exists
'name' => $this->schema->{$key},
// Attribute name in lower case
'name_lc' => strtolower($this->name),
// Required by Object Classes
'required_by' => $this->schema?->required_by_object_classes ?: collect(),
// Used in Object Classes
'used_in' => $this->schema?->used_in_object_classes ?: collect(),
// For single value attributes
'value' => $this->schema?->is_single_value ? $this->values->first() : NULL,
// The current attribute values
'values' => ($this->no_attr_tags || $this->is_internal) ? $this->tagValues() : $this->_values,
// The original attribute values
'values_old' => ($this->no_attr_tags || $this->is_internal) ? $this->tagValuesOld() : $this->_values_old,
default => throw new \Exception('Unknown key:' . $key),
};
}
public function __set(string $key,mixed $values): void
{
switch ($key) {
case 'values':
$this->_values = $values;
break;
case 'values_old':
$this->_values_old = $values;
break;
default:
throw new \Exception('Unknown key:'.$key);
}
}
public function __toString(): string
{
return $this->name;
}
/* INTERFACE */
public function count(): int
{
return $this->_values
->dot()
->count();
}
public function offsetExists(mixed $offset): bool
{
return $this->_values
->dot()
->has($offset);
}
public function offsetGet(mixed $offset): mixed
{
return $this->_values
->dot()
->get($offset);
}
public function offsetSet(mixed $offset, mixed $value): void
{
// We cannot set new values using array syntax
}
public function offsetUnset(mixed $offset): void
{
// We cannot clear values using array syntax
}
/* METHODS */
public function addValue(string $tag,array $values): void
{
$this->_values->put(
$tag,
array_unique(array_merge($this->_values
->get($tag,[]),$values)));
}
public function addValueOld(string $tag,array $values): void
{
$this->_values_old->put(
$tag,
array_unique(array_merge($this->_values_old
->get($tag,[]),$values)));
}
/**
* Return the hints about this attribute, ie: RDN, Required, etc
*
* @return Collection
*/
public function hints(): Collection
{
$result = collect();
if ($this->is_internal)
return $result;
// Is this Attribute an RDN
if ($this->is_rdn)
$result->put(__('rdn'),__('This attribute is required for the RDN'));
if ($this->required()->count())
$result->put(__('required'),sprintf('%s: %s',__('Required Attribute by ObjectClass(es)'),$this->required()->join(', ')));
// If this attribute is a dynamic attribute
if ($this->isDynamic())
$result->put(__('dynamic'),__('These are dynamic values present as a result of another attribute'));
return $result;
}
/**
* Determine if this attribute has changes
*
* @return bool
*/
public function isDirty(): bool
{
return (($a=$this->values_old->dot()->filter())->keys()->count() !== ($b=$this->values->dot()->filter())->keys()->count())
|| ($a->count() !== $b->count())
|| ($a->diff($b)->count() !== 0);
}
/**
* Are these values as a result of a dynamic attribute
*
* @return bool
*/
public function isDynamic(): bool
{
return $this->schema->used_in_object_classes
->keys()
->intersect($this->oc)
->count() === 0;
}
/**
* Work out if this attribute is an RDN attribute
*
* @return bool
*/
public function isRDN(): bool
{
// If we dont have an DN, then we cant know
if (! $this->dn)
return FALSE;
$rdns = collect(explode('+',substr($this->dn,0,strpos($this->dn,','))));
return $rdns->filter(fn($item) => str_starts_with($item,$this->name.'='))->count() > 0;
}
/**
* Display the attribute value
*
* @param bool $edit Render an edit form
* @param bool $old Use old value
* @param bool $new Enable adding values
* @param bool $updated Has the entry been updated (uses rendering highlights))
* @param Template|null $template
* @return View
*/
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
if ($this->is_internal)
// @note Internal attributes cannot be edited
return view('components.attribute.internal')
->with('o',$this);
$view = match ($this->schema?->syntax_oid) {
self::SYNTAX_CERTIFICATE => view('components.syntax.certificate'),
self::SYNTAX_CERTIFICATE_LIST => view('components.syntax.certificatelist'),
default => view()->exists($x='components.attribute.'.$this->name_lc)
? view($x)
: view('components.attribute'),
};
return $view
->with('o',$this)
->with('edit',$edit)
->with('old',$old)
->with('new',$new)
->with('template',$template)
->with('updated',$updated);
}
/**
* Return the value of the original old values
*
* @param string $dotkey
* @return string|null
*/
public function render_item_old(string $dotkey): ?string
{
return match ($this->schema->syntax_oid) {
self::SYNTAX_CERTIFICATE => join("\n",str_split(base64_encode(Arr::get($this->values_old->dot(),$dotkey)),80)),
self::SYNTAX_CERTIFICATE_LIST => join("\n",str_split(base64_encode(Arr::get($this->values_old->dot(),$dotkey)),80)),
default => Arr::get($this->values_old->dot(),$dotkey),
};
}
/**
* Return the value of the new values, which would include any pending udpates
*
* @param string $dotkey
* @return string|null
*/
public function render_item_new(string $dotkey): ?string
{
return Arr::get($this->values->dot(),$dotkey);
}
/**
* Work out if this attribute is required by an objectClass the entry has
*
* @return Collection
*/
private function required(): Collection
{
// If we dont have any objectclasses then we cant know if it is required
return $this->oc->count()
? $this->oc->intersect($this->required_by->keys())->sort()
: collect();
}
/**
* Return the new values for this attribute, which would include any pending updates
*
* @param string $tag
* @return Collection
*/
public function tagValues(string $tag=Entry::TAG_NOTAG): Collection
{
return collect($this->_values
->filter(fn($item,$key)=>($key===$tag))
->get($tag,[]));
}
/**
* Return the original values for this attribute, as stored in the LDAP server
*
* @param string $tag
* @return Collection
*/
public function tagValuesOld(string $tag=Entry::TAG_NOTAG): Collection
{
return collect($this->_values_old
->filter(fn($item,$key)=>($key===$tag))
->get($tag,[]));
}
}

View File

@ -1,12 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use App\Classes\LDAP\Attribute;
/**
* Represents an attribute whose values are binary
*/
abstract class Binary extends Attribute
{
}

View File

@ -1,28 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Binary;
use Illuminate\Contracts\View\View;
use App\Classes\LDAP\Attribute\Binary;
use App\Classes\Template;
use App\Traits\MD5Updates;
/**
* Represents an JpegPhoto Attribute
*/
final class JpegPhoto extends Binary
{
use MD5Updates;
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
return view('components.attribute.binary.jpegphoto')
->with('o',$this)
->with('edit',$edit)
->with('old',$old)
->with('new',$new)
->with('updated',$updated)
->with('f',new \finfo);
}
}

View File

@ -1,61 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use App\Classes\LDAP\Attribute;
use App\Traits\MD5Updates;
/**
* Represents an attribute whose values is a binary user certificate
*/
final class Certificate extends Attribute
{
use MD5Updates;
private array $_object = [];
public function authority_key_identifier(int $key=0): string
{
$data = collect(explode("\n",$this->cert_info('extensions.authorityKeyIdentifier',$key)));
return $data
->filter(fn($item)=>Str::startsWith($item,'keyid:'))
->map(fn($item)=>Str::after($item,'keyid:'))
->first();
}
public function certificate(int $key=0): string
{
return sprintf("-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----",
join("\n",str_split(base64_encode(Arr::get($this->values_old,'binary.'.$key)),80))
);
}
public function cert_info(string $index,int $key=0): mixed
{
if (! array_key_exists($key,$this->_object))
$this->_object[$key] = openssl_x509_parse(openssl_x509_read($this->certificate($key)));
return Arr::get($this->_object[$key],$index);
}
public function expires(int $key=0): Carbon
{
return Carbon::createFromTimestampUTC($this->cert_info('validTo_time_t',$key));
}
public function subject(int $key=0): string
{
$subject = collect($this->cert_info('subject',$key))->reverse();
return $subject->map(fn($item,$key)=>sprintf("%s=%s",$key,$item))->join(',');
}
public function subject_key_identifier(int $key=0): string
{
return $this->cert_info('extensions.subjectKeyIdentifier',$key);
}
}

View File

@ -1,14 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use App\Classes\LDAP\Attribute;
use App\Traits\MD5Updates;
/**
* Represents an attribute whose values is a binary user certificate
*/
final class CertificateList extends Attribute
{
use MD5Updates;
}

View File

@ -1,63 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use Illuminate\Support\Arr;
use App\Classes\LDAP\Attribute;
/**
* This factory is used to return LDAP attributes as an object
*
* If there is no specific Attribute defined, then the default Attribute::class is return
*/
class Factory
{
private const LOGKEY = 'LAf';
/**
* Map of attributes to appropriate class
*/
public const map = [
'authorityrevocationlist' => CertificateList::class,
'cacertificate' => Certificate::class,
'certificaterevocationlist' => CertificateList::class,
'createtimestamp' => Internal\Timestamp::class,
'configcontext' => Schema\Generic::class,
'krblastfailedauth' => Attribute\NoAttrTags\Generic::class,
'krblastpwdchange' => Attribute\NoAttrTags\Generic::class,
'krblastsuccessfulauth' => Attribute\NoAttrTags\Generic::class,
'krbpasswordexpiration' => Attribute\NoAttrTags\Generic::class,
'krbloginfailedcount' => Attribute\NoAttrTags\Generic::class,
'krbprincipalkey' => KrbPrincipalKey::class,
'krbticketflags' => KrbTicketFlags::class,
'gidnumber' => GidNumber::class,
'jpegphoto' => Binary\JpegPhoto::class,
'modifytimestamp' => Internal\Timestamp::class,
'monitorcontext' => Schema\Generic::class,
'namingcontexts' => Schema\Generic::class,
'objectclass' => ObjectClass::class,
'supportedcontrol' => Schema\OID::class,
'supportedextension' => Schema\OID::class,
'supportedfeatures' => Schema\OID::class,
'supportedldapversion' => Schema\Generic::class,
'supportedsaslmechanisms' => Schema\Mechanisms::class,
'usercertificate' => Certificate::class,
'userpassword' => Password::class,
];
/**
* Create the new Object for an attribute
*
* @param string $dn
* @param string $attribute
* @param array $values
* @param array $oc
* @return Attribute
*/
public static function create(string $dn,string $attribute,array $values,array $oc=[]): Attribute
{
$class = Arr::get(self::map,strtolower($attribute),Attribute::class);
return new $class($dn,$attribute,$values,$oc);
}
}

View File

@ -1,12 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use App\Classes\LDAP\Attribute;
/**
* Represents an GidNumber Attribute
*/
final class GidNumber extends Attribute
{
}

View File

@ -1,14 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use App\Classes\LDAP\Attribute;
/**
* Represents an attribute whose values are internal
*/
abstract class Internal extends Attribute
{
protected ?bool $_is_internal = TRUE;
protected(set) bool $no_attr_tags = TRUE;
}

View File

@ -1,21 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Internal;
use Illuminate\Contracts\View\View;
use App\Classes\LDAP\Attribute\Internal;
use App\Classes\Template;
/**
* Represents an attribute whose values are timestamps
*/
final class Timestamp extends Internal
{
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
// @note Internal attributes cannot be edited
return view('components.attribute.internal.timestamp')
->with('o',$this);
}
}

View File

@ -1,43 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use Illuminate\Contracts\View\View;
use App\Classes\LDAP\Attribute;
use App\Classes\Template;
use App\Traits\MD5Updates;
/**
* Represents an attribute whose values are passwords
*/
final class KrbPrincipalKey extends Attribute
{
use MD5Updates;
protected(set) bool $no_attr_tags = TRUE;
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
return view('components.attribute.krbprincipalkey')
->with('o',$this)
->with('edit',$edit)
->with('old',$old)
->with('new',$new)
->with('updated',$updated);
}
public function render_item_old(string $dotkey): ?string
{
return parent::render_item_old($dotkey)
? str_repeat('*',16)
: NULL;
}
public function render_item_new(string $dotkey): ?string
{
return parent::render_item_new($dotkey)
? str_repeat('*',16)
: NULL;
}
}

View File

@ -1,63 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use App\Classes\LDAP\Attribute;
use App\Classes\Template;
/**
* Represents an attribute whose value is a Kerberos Ticket Flag
* See RFC4120
*/
final class KrbTicketFlags extends Attribute
{
protected(set) bool $no_attr_tags = TRUE;
private const DISALLOW_POSTDATED = 0x00000001;
private const DISALLOW_FORWARDABLE = 0x00000002;
private const DISALLOW_TGT_BASED = 0x00000004;
private const DISALLOW_RENEWABLE = 0x00000008;
private const DISALLOW_PROXIABLE = 0x00000010;
private const DISALLOW_DUP_SKEY = 0x00000020;
private const DISALLOW_ALL_TIX = 0x00000040;
private const REQUIRES_PRE_AUTH = 0x00000080;
private const REQUIRES_HW_AUTH = 0x00000100;
private const REQUIRES_PWCHANGE = 0x00000200;
private const DISALLOW_SVR = 0x00001000;
private const PWCHANGE_SERVICE = 0x00002000;
private static function helpers(): Collection
{
$helpers = collect([
log(self::DISALLOW_POSTDATED,2) => __('KRB_DISALLOW_POSTDATED'),
log(self::DISALLOW_FORWARDABLE,2) => __('KRB_DISALLOW_FORWARDABLE'),
log(self::DISALLOW_TGT_BASED,2) => __('KRB_DISALLOW_TGT_BASED'),
log(self::DISALLOW_RENEWABLE,2) => __('KRB_DISALLOW_RENEWABLE'),
log(self::DISALLOW_PROXIABLE,2) => __('KRB_DISALLOW_PROXIABLE'),
log(self::DISALLOW_DUP_SKEY,2) => __('KRB_DISALLOW_DUP_SKEY'),
log(self::DISALLOW_ALL_TIX,2) => __('KRB_DISALLOW_ALL_TIX'),
log(self::REQUIRES_PRE_AUTH,2) => __('KRB_REQUIRES_PRE_AUTH'),
log(self::REQUIRES_HW_AUTH,2) => __('KRB_REQUIRES_HW_AUTH'),
log(self::REQUIRES_PWCHANGE,2) => __('KRB_REQUIRES_PWCHANGE'),
log(self::DISALLOW_SVR,2) => __('KRB_DISALLOW_SVR'),
log(self::PWCHANGE_SERVICE,2) => __('KRB_PWCHANGE_SERVICE'),
])
->replace(config('pla.krb.bits',[]));
return $helpers;
}
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
return view('components.attribute.krbticketflags')
->with('o',$this)
->with('edit',$edit)
->with('old',$old)
->with('new',$new)
->with('updated',$updated)
->with('helper',static::helpers());
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\NoAttrTags;
use App\Classes\LDAP\Attribute;
/**
* Represents an Attribute that doesnt have Lang Tags
*/
class Generic extends Attribute
{
protected(set) bool $no_attr_tags = TRUE;
}

View File

@ -1,89 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use App\Classes\LDAP\Attribute;
use App\Classes\Template;
/**
* Represents an ObjectClass Attribute
*/
final class ObjectClass extends Attribute
{
protected(set) bool $no_attr_tags = TRUE;
// The schema ObjectClasses for this objectclass of a DN
protected Collection $oc_schema;
/**
* Create an ObjectClass Attribute
*
* @param string $dn DN this attribute is used in
* @param string $name Name of the attribute
* @param array $values Current Values
* @param array $oc The objectclasses that the DN of this attribute has (ignored for objectclasses)
*/
public function __construct(string $dn,string $name,array $values,array $oc=[])
{
parent::__construct($dn,$name,$values,['top']);
$this->set_oc_schema($this->tagValuesOld());
}
public function __get(string $key): mixed
{
return match ($key) {
'structural' => $this->oc_schema->filter(fn($item)=>$item->isStructural()),
default => parent::__get($key),
};
}
public function __set(string $key,mixed $values): void
{
switch ($key) {
case 'values':
parent::__set($key,$values);
// We need to populate oc_schema, if we are a new OC and thus dont have any old values
if (! $this->values_old->count() && $this->values->count())
$this->set_oc_schema($this->tagValues());
break;
default: parent::__set($key,$values);
}
}
/**
* Is a specific value the structural objectclass
*
* @param string $value
* @return bool
*/
public function isStructural(string $value): bool
{
return $this->structural
->map(fn($item)=>$item->name)
->contains($value);
}
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
return view('components.attribute.objectclass')
->with('o',$this)
->with('edit',$edit)
->with('old',$old)
->with('new',$new)
->with('updated',$updated);
}
private function set_oc_schema(Collection $tv): void
{
$this->oc_schema = config('server')
->schema('objectclasses')
->filter(fn($item)=>$tv->contains($item->name));
}
}

View File

@ -1,114 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use App\Classes\LDAP\Attribute;
use App\Classes\Template;
use App\Traits\MD5Updates;
/**
* Represents an attribute whose values are passwords
*/
final class Password extends Attribute
{
use MD5Updates;
protected(set) bool $no_attr_tags = TRUE;
protected(set) int $max_values_count = 1;
private const password_helpers = 'Classes/LDAP/Attribute/Password';
public const commands = 'App\\Classes\\LDAP\\Attribute\\Password\\';
private static function helpers(): Collection
{
$helpers = collect();
foreach (preg_grep('/^([^.])/',scandir(app_path(self::password_helpers))) as $file) {
if (($file === 'Base.php') || (! str_ends_with(strtolower($file),'.php')))
continue;
$class = self::commands.preg_replace('/\.php$/','',$file);
$helpers = $helpers
->merge([$class::id()=>$class]);
}
return $helpers->sort();
}
/**
* Given an LDAP password syntax {xxx}yyyyyy, this function will return the object for xxx
*
* @param string $password
* @return Attribute\Password\Base|null
* @throws \Exception
*/
public static function hash(string $password): ?Attribute\Password\Base
{
$m = [];
preg_match('/^{([A-Z0-9]+)}(.*)$/',$password,$m);
$hash = Arr::get($m,1,'*clear*');
if (($potential=static::helpers()->filter(fn($hasher)=>str_starts_with($hasher::key,$hash)))->count() > 1) {
foreach ($potential as $item) {
if ($item::subid($password))
return new $item;
}
throw new \Exception(sprintf('Couldnt figure out a password hash for %s',$password));
} elseif (! $potential->count()) {
throw new \Exception(sprintf('Couldnt figure out a password hash for %s',$password));
}
return new ($potential->pop());
}
/**
* Return the object that will process a password
*
* @param string $id
* @return Attribute\Password\Base|null
*/
public static function hash_id(string $id): ?Attribute\Password\Base
{
return ($helpers=static::helpers())->has($id) ? new ($helpers->get($id)) : NULL;
}
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
return view('components.attribute.password')
->with('o',$this)
->with('edit',$edit)
->with('old',$old)
->with('new',$new)
->with('template',$template)
->with('updated',$updated)
->with('helpers',static::helpers()->map(fn($item,$key)=>['id'=>$key,'value'=>$key])->sort());
}
public function render_item_old(string $dotkey): ?string
{
$pw = parent::render_item_old($dotkey);
return $pw
? (((($x=$this->hash($pw)) && ($x::id() === '*clear*')) ? sprintf('{%s}',$x::shortid()) : '')
.str_repeat('*',16))
: NULL;
}
public function render_item_new(string $dotkey): ?string
{
$pw = parent::render_item_new($dotkey);
return $pw
? (((($x=$this->hash($pw)) && ($x::id() !== '*clear*')) ? sprintf('{%s}',$x::shortid()) : '')
.str_repeat('*',16))
: NULL;
}
}

View File

@ -1,25 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class Argon2i extends Base
{
public const key = 'ARGON2';
protected const subkey = 'argon2i';
protected const identifier = '$argon2i';
public static function subid(string $password): bool
{
return str_starts_with(self::password($password),self::identifier.'$');
}
public function compare(string $source,string $compare): bool
{
return password_verify($compare,$this->password($source));
}
public function encode(string $password): string
{
return sprintf('{%s}%s',self::key,password_hash($password,PASSWORD_ARGON2I));
}
}

View File

@ -1,25 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class Argon2id extends Base
{
public const key = 'ARGON2';
protected const subkey = 'argon2id';
protected const identifier = '$argon2id';
public static function subid(string $password): bool
{
return str_starts_with(base64_decode(self::password($password)),self::identifier.'$');
}
public function compare(string $source,string $compare): bool
{
return password_verify($compare,base64_decode($this->password($source)));
}
public function encode(string $password): string
{
return sprintf('{%s}%s',self::key,base64_encode(password_hash($password,PASSWORD_ARGON2ID)));
}
}

View File

@ -1,68 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
abstract class Base
{
protected const subkey = '';
abstract public function encode(string $password): string;
public static function id(): string
{
return static::subkey ? strtoupper(static::subkey) : static::key;
}
/**
* Remove the hash {TEXT}xxxx from the password
*
* @param string $password
* @return string
*/
protected static function password(string $password): string
{
return preg_replace('/^{'.static::key.'}/','',$password);
}
public static function shortid(): string
{
return static::key;
}
/**
* When multiple passwords share the same ID, this determines which hash is responsible for the presented password
*
* @param string $password
* @return bool
*/
public static function subid(string $password): bool
{
return FALSE;
}
/**
* Compare our password to see if it is the same as that stored
*
* @param string $source Encoded source password
* @param string $compare Password entered by user
* @return bool
*/
public function compare(string $source,string $compare): bool
{
return $source === $this->encode($compare);
}
protected function salted_hash(string $password,string $algo,int $salt_size=8,?string $salt=NULL): string
{
if (is_null($salt))
$salt = hex2bin(random_salt($salt_size));
return base64_encode(hash($algo,$password.$salt,true).$salt);
}
protected function salted_salt(string $source): string
{
$hash = base64_decode(substr($source,strlen(static::key)+2));
return substr($hash,strlen($hash)-static::salt/2);
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class Bcrypt extends Base
{
public const key = 'BCRYPT';
private const options = [
'cost' => 8,
];
public function compare(string $source,string $compare): bool
{
return password_verify($compare,base64_decode($this->password($source)));
}
public function encode(string $password): string
{
return sprintf('{%s}%s',self::key,base64_encode(password_hash($password,PASSWORD_BCRYPT,self::options)));
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class Blowfish extends Base
{
public const key = 'CRYPT';
protected const subkey = 'blowfish';
private const cost = 12;
protected const salt = 22;
private const identifier = '$2a$';
public static function subid(string $password): bool
{
return preg_match('/^\\$2.\\$/',self::password($password));
}
public function compare(string $source,string $compare): bool
{
return hash_equals($cp=self::password($source),crypt($compare,$cp));
}
public function encode(string $password,?string $salt=NULL): string
{
if (is_null($salt))
$salt = sprintf('%s%d$%s',self::identifier,self::cost,random_salt(self::salt));
return sprintf('{%s}%s',self::key,crypt($password,$salt));
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class Clear extends Base
{
public const key = '*clear*';
public function encode(string $password): string
{
return $password;
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class Crypt extends Base
{
public const key = 'CRYPT';
protected const subkey = 'crypt';
protected const salt = 2;
private const identifier = '';
public static function subid(string $password): bool
{
return preg_match('/^[\da-f]{2}/',self::password($password));
}
public function compare(string $source,string $compare): bool
{
return hash_equals($cp=self::password($source),crypt($compare,$cp));
}
public function encode(string $password,?string $salt=NULL): string
{
if (is_null($salt))
$salt = sprintf('%s%s',self::identifier,random_salt(self::salt));
return sprintf('{%s}%s',self::key,crypt($password,$salt));
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class ExtDes extends Base
{
public const key = 'CRYPT';
protected const subkey = 'ext_des';
protected const salt = 8;
private const identifier = '_';
public static function subid(string $password): bool
{
return str_starts_with(self::password($password),self::identifier);
}
public function compare(string $source,string $compare): bool
{
return hash_equals($cp=self::password($source),crypt($compare,$cp));
}
public function encode(string $password,?string $salt=NULL): string
{
if (is_null($salt))
$salt = sprintf('%s%s',self::identifier,random_salt(self::salt));
return sprintf('{%s}%s',self::key,crypt($password,$salt));
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class MD5 extends Base
{
public const key = 'MD5';
public function encode(string $password): string
{
return sprintf('{%s}%s',self::key,base64_encode(hash('md5',$password,true)));
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class MD5crypt extends Base
{
public const key = 'CRYPT';
protected const subkey = 'md5crypt';
protected const salt = 9;
private const identifier = '$1$';
public static function subid(string $password): bool
{
return str_starts_with(self::password($password),self::identifier);
}
public function compare(string $source,string $compare): bool
{
return hash_equals($cp=self::password($source),crypt($compare,$cp));
}
public function encode(string $password,?string $salt=NULL): string
{
if (is_null($salt))
$salt = sprintf('%s$%s',self::identifier,random_salt(self::salt));
return sprintf('{%s}%s',self::key,crypt($password,$salt));
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SASL extends Base
{
public const key = 'SASL';
public function encode(string $password): string
{
if (! str_contains($password,'@'))
return '';
// Ensure our id is lowercase, and realm is uppercase
list($id,$realm) = explode('@',$password);
return sprintf('{%s}%s@%s',self::key,strtolower($id),strtoupper($realm));
}
}

View File

@ -1,18 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SHA extends Base
{
public const key = 'SHA';
public function encode(string $password): string
{
return sprintf('{%s}%s',self::key,base64_encode(hash('sha1',$password,true)));
}
public static function subid(string $password): bool
{
return preg_match('/^{'.static::key.'}/',$password);
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SHA256 extends Base
{
public const key = 'SHA256';
public function encode(string $password): string
{
return sprintf('{%s}%s',self::key,base64_encode(hash('sha256',$password,true)));
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SHA256crypt extends Base
{
public const key = 'CRYPT';
protected const subkey = 'sha256crypt';
protected const salt = 5;
private const identifier = '$5$';
public static function subid(string $password): bool
{
return str_starts_with(self::password($password),self::identifier);
}
public function compare(string $source,string $compare): bool
{
return hash_equals($cp=self::password($source),crypt($compare,$cp));
}
public function encode(string $password,?string $salt=NULL): string
{
if (is_null($salt))
$salt = sprintf('%s%s',self::identifier,random_salt(self::salt));
return sprintf('{%s}%s',self::key,crypt($password,$salt));
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SHA384 extends Base
{
public const key = 'SHA384';
public function encode(string $password): string
{
return sprintf('{%s}%s',self::key,base64_encode(hash('sha384',$password,true)));
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SHA512 extends Base
{
public const key = 'SHA512';
public function encode(string $password): string
{
return sprintf('{%s}%s',self::key,base64_encode(hash('sha512',$password,true)));
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SHA512crypt extends Base
{
public const key = 'CRYPT';
protected const subkey = 'sha512crypt';
protected const salt = 2;
private const identifier = '$6$';
public static function subid(string $password): bool
{
return str_starts_with(self::password($password),self::identifier);
}
public function compare(string $source,string $compare): bool
{
return hash_equals($cp=self::password($source),crypt($compare,$cp));
}
public function encode(string $password,?string $salt=NULL): string
{
if (is_null($salt))
$salt = sprintf('%s%s',self::identifier,random_salt(self::salt));
return sprintf('{%s}%s',self::key,crypt($password,$salt));
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SMD5 extends Base
{
public const key = 'SMD5';
protected const salt = 8;
public function compare(string $source,string $compare): bool
{
return $source === $this->encode($compare,$this->salted_salt($source));
}
public function encode(string $password,?string $salt=NULL): string
{
if (is_null($salt))
$salt = hex2bin(random_salt(self::salt));
return sprintf('{%s}%s',self::key,$this->salted_hash($password,'md5',self::salt,$salt));
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SSHA extends Base
{
public const key = 'SSHA';
protected const salt = 8;
public function compare(string $source,string $compare): bool
{
return $source === $this->encode($compare,$this->salted_salt($source));
}
public function encode(string $password,?string $salt=NULL): string
{
return sprintf('{%s}%s',self::key,$this->salted_hash($password,'sha1',self::salt,$salt));
}
public static function subid(string $password): bool
{
return preg_match('/^{'.static::key.'}/',$password);
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SSHA256 extends Base
{
public const key = 'SSHA256';
protected const salt = 8;
public function compare(string $source,string $compare): bool
{
return $source === $this->encode($compare,$this->salted_salt($source));
}
public function encode(string $password,?string $salt=NULL): string
{
return sprintf('{%s}%s',self::key,$this->salted_hash($password,'sha256',self::salt,$salt));
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SSHA384 extends Base
{
public const key = 'SSHA384';
protected const salt = 8;
public function compare(string $source,string $compare): bool
{
return $source === $this->encode($compare,$this->salted_salt($source));
}
public function encode(string $password,?string $salt=NULL): string
{
return sprintf('{%s}%s',self::key,$this->salted_hash($password,'sha384',self::salt,$salt));
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Password;
final class SSHA512 extends Base
{
public const key = 'SSHA512';
protected const salt = 8;
public function compare(string $source,string $compare): bool
{
return $source === $this->encode($compare,$this->salted_salt($source));
}
public function encode(string $password,?string $salt=NULL): string
{
return sprintf('{%s}%s',self::key,$this->salted_hash($password,'sha512',self::salt,$salt));
}
}

View File

@ -1,53 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use App\Classes\LDAP\Attribute;
use App\Classes\Template;
/**
* Represents the RDN for an Entry
*/
final class RDN extends Attribute
{
private string $base;
protected(set) bool $no_attr_tags = TRUE;
private Collection $attrs;
public function __get(string $key): mixed
{
return match ($key) {
'base' => $this->base,
'attrs' => $this->attrs->pluck('name'),
default => parent::__get($key),
};
}
public function hints(): Collection
{
return collect([
'required' => __('RDN is required')
]);
}
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
return view('components.attribute.rdn')
->with('o',$this);
}
public function setAttributes(Collection $attrs): void
{
$this->attrs = $attrs;
}
public function setBase(string $base): void
{
$this->base = $base;
}
}

View File

@ -1,54 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use App\Classes\LDAP\Attribute;
/**
* Represents an attribute whose values are schema related
*/
abstract class Schema extends Attribute
{
protected bool $internal = TRUE;
protected(set) bool $no_attr_tags = TRUE;
protected static function _get(string $filename,string $string,string $key): ?string
{
$array = Cache::remember($filename,86400,function() use ($filename) {
try {
$f = fopen($filename,'r');
} catch (\Exception $e) {
return NULL;
}
$result = collect();
while (! feof($f)) {
$line = trim(fgets($f));
if ((! $line) || preg_match('/^#/',$line))
continue;
$fields = explode(':',$line);
$result->put($x=Arr::get($fields,0),[
'title'=>Arr::get($fields,1,$x),
'ref'=>Arr::get($fields,2),
'desc'=>Arr::get($fields,3,__('No description available, can you help with one?')),
]);
}
fclose($f);
return $result;
});
return Arr::get(($array ? $array->get($string) : []),
$key,
__('No description available, can you help with one?'));
}
}

View File

@ -1,21 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Schema;
use Illuminate\Contracts\View\View;
use App\Classes\LDAP\Attribute\Schema;
use App\Classes\Template;
/**
* Represents a Generic Schema Attribute
*/
class Generic extends Schema
{
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
// @note Schema attributes cannot be edited
return view('components.attribute.schema.generic')
->with('o',$this);
}
}

View File

@ -1,43 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Schema;
use Illuminate\Contracts\View\View;
use App\Classes\LDAP\Attribute\Schema;
use App\Classes\Template;
/**
* Represents a Mechanisms Attribute
*/
final class Mechanisms extends Schema
{
/**
* Given an SASL Mechanism name, returns a verbose description of the Mechanism.
* This function parses ldap_supported_saslmechanisms.txt and looks up the specified
* Mechanism, and returns the verbose message defined in that file.
*
* <code>
* "SCRAM-SHA-1" => array:3 [
* "title" => "Salted Challenge Response Authentication Mechanism (SCRAM) SHA1"
* "ref" => "RFC 5802"
* "desc" => "This specification describes a family of authentication mechanisms called the Salted Challenge Response Authentication Mechanism (SCRAM) which addresses the req ▶"
* ]
* </code>
*
* @param string $string The SASL Mechanism (ie, "SCRAM-SHA-1") of interest.
* @param string $key The title|ref|desc to return
* @return string|NULL
*/
public static function get(string $string,string $key): ?string
{
return parent::_get(config_path('ldap_supported_saslmechanisms.txt'),$string,$key);
}
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
// @note Schema attributes cannot be edited
return view('components.attribute.schema.mechanisms')
->with('o',$this);
}
}

View File

@ -1,44 +0,0 @@
<?php
namespace App\Classes\LDAP\Attribute\Schema;
use Illuminate\Contracts\View\View;
use App\Classes\LDAP\Attribute\Schema;
use App\Classes\Template;
/**
* Represents an OID Attribute
*/
final class OID extends Schema
{
/**
* Given an LDAP OID number, returns a verbose description of the OID.
* This function parses ldap_supported_oids.txt and looks up the specified
* OID, and returns the verbose message defined in that file.
*
* <code>
* "1.3.6.1.4.1.4203.1.5.1" => array:3 [
* [title] => All Operational Attribute
* [ref] => RFC 3673
* [desc] => An LDAP extension which clients may use to request the return of all operational attributes.
* ]
* </code>
*
* @param string $string The OID number (ie, "1.3.6.1.4.1.4203.1.5.1") of the OID of interest.
* @param string $key The title|ref|desc to return
* @return string|null
* @testedby TranslateOidTest::testRootDSE()
*/
public static function get(string $string,string $key): ?string
{
return parent::_get(config_path('ldap_supported_oids.txt'),$string,$key);
}
public function render(bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL): View
{
// @note Schema attributes cannot be edited
return view('components.attribute.schema.oid')
->with('o',$this);
}
}

View File

@ -1,53 +0,0 @@
<?php
namespace App\Classes\LDAP;
use Illuminate\Support\Facades\Auth;
use LdapRecord\Query\Collection;
/**
* Export Class
*
* This abstract classes provides all the common methods and variables for the
* export classes.
*/
abstract class Export
{
// Line Break
protected string $br = "\r\n";
// Item(s) being Exported
protected Collection $items;
// Type of export
protected const type = 'Unknown';
public function __construct(Collection $items)
{
$this->items = $items;
}
abstract public function __toString(): string;
protected function header(): string
{
$output = '';
$output .= sprintf('# %s %s',__(static::type.' for'),($x=$this->items->first())).$this->br;
$output .= sprintf('# %s: %s (%s)',
__('Server'),
$x->getConnection()->getConfiguration()->get('name'),
$x->getConnection()->getLdapConnection()->getHost()).$this->br;
//$output .= sprintf('# %s: %s',__('Search Scope'),$this->scope).$this->br;
//$output .= sprintf('# %s: %s',__('Search Filter'),$this->entry->dn).$this->br;
$output .= sprintf('# %s: %s',__('Total Entries'),$this->items->count()).$this->br;
$output .= '#'.$this->br;
$output .= sprintf('# %s %s (%s) on %s',__('Generated by'),config('app.name'),request()->root(),date('F j, Y g:i a')).$this->br;
$output .= sprintf('# %s %s',__('Exported by'),Auth::user() ?: 'Anonymous').$this->br;
$output .= sprintf('# %s: %s',__('Version'),config('app.version')).$this->br;
$output .= $this->br;
return $output;
}
}

View File

@ -1,91 +0,0 @@
<?php
namespace App\Classes\LDAP\Export;
use Illuminate\Support\Str;
use App\Classes\LDAP\Export;
use App\Ldap\Entry;
/**
* Export from LDAP using an LDIF format
*/
class LDIF extends Export
{
// The maximum length of the ldif line
private int $line_length = 76;
protected const type = 'LDIF Export';
public function __toString(): string
{
$result = parent::header();
$result .= 'version: 1';
$result .= $this->br;
$c = 1;
foreach ($this->items as $o) {
if ($c > 1)
$result .= $this->br;
$title = (string)$o;
if (strlen($title) > $this->line_length)
$title = Str::of($title)->limit($this->line_length-3-5,'...'.substr($title,-5));
$result .= sprintf('# %s %s: %s',__('Entry'),$c++,$title).$this->br;
// Display DN
$result .= $this->multiLineDisplay(
Str::isAscii($o)
? sprintf('dn: %s',$o)
: sprintf('dn:: %s',base64_encode($o))
,$this->br);
// Display Attributes
foreach ($o->getObjects() as $ao) {
if ($ao->no_attr_tags)
foreach ($ao->values as $value) {
$result .= $this->multiLineDisplay(
Str::isAscii($value)
? sprintf('%s: %s',$ao->name,$value)
: sprintf('%s:: %s',$ao->name,base64_encode($value))
,$this->br);
}
else
foreach ($ao->values as $tag => $tagvalues) {
foreach ($tagvalues as $value) {
$result .= $this->multiLineDisplay(
Str::isAscii($value)
? sprintf('%s: %s',$ao->name.(($tag !== Entry::TAG_NOTAG) ? ';'.$tag : ''),$value)
: sprintf('%s:: %s',$ao->name.(($tag !== Entry::TAG_NOTAG) ? ';'.$tag : ''),base64_encode($value))
,$this->br);
}
}
}
}
return $result;
}
/**
* Helper method to wrap LDIF lines
*
* @param string $str The line to be wrapped if needed.
*/
private function multiLineDisplay(string $str,string $br): string
{
$length_string = strlen($str);
$length_max = $this->line_length;
$output = '';
while ($length_string > $length_max) {
$output .= substr($str,0,$length_max).$br;
$str = ' '.substr($str,$length_max);
$length_string = strlen($str);
}
$output .= $str.$br;
return $output;
}
}

View File

@ -1,94 +0,0 @@
<?php
namespace App\Classes\LDAP;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use LdapRecord\LdapRecordException;
use App\Exceptions\Import\GeneralException;
use App\Ldap\Entry;
/**
* Import Class
*
* This abstract classes provides all the common methods and variables for the
* import classes.
*/
abstract class Import
{
private const LOGKEY = 'aI-';
// Valid LDIF commands
protected const LDAP_IMPORT_ADD = 1;
protected const LDAP_IMPORT_DELETE = 2;
protected const LDAP_IMPORT_MODRDN = 3;
protected const LDAP_IMPORT_MODDN = 4;
protected const LDAP_IMPORT_MODIFY = 5;
protected const LDAP_ACTIONS = [
'add' => self::LDAP_IMPORT_ADD,
'delete' => self::LDAP_IMPORT_DELETE,
'modrdn' => self::LDAP_IMPORT_MODRDN,
'moddn' => self::LDAP_IMPORT_MODDN,
'modify' => self::LDAP_IMPORT_MODIFY,
];
// The import data to process
protected string $input;
// The attributes the server knows about
protected Collection $server_attributes;
public function __construct(string $input) {
$this->input = $input;
$this->server_attributes = config('server')->schema('attributetypes');
}
/**
* Attempt to commit an entry and return the result.
*
* @param Entry $o
* @param int $action
* @return Collection
* @throws GeneralException
*/
final protected function commit(Entry $o,int $action): Collection
{
switch ($action) {
case static::LDAP_IMPORT_ADD:
try {
$o->save();
} catch (LdapRecordException $e) {
Log::error(sprintf('%s:Import Commit Error',self::LOGKEY),['e'=>$e->getMessage(),'detailed'=>$e->getDetailedError()]);
if ($e->getDetailedError())
return collect([
'dn'=>$o->getDN(),
'result'=>sprintf('%d: %s (%s)',
($x=$e->getDetailedError())->getErrorCode(),
$x->getErrorMessage(),
$x->getDiagnosticMessage(),
)
]);
else
return collect([
'dn'=>$o->getDN(),
'result'=>sprintf('%d: %s',
$e->getCode(),
$e->getMessage(),
)
]);
}
Log::debug(sprintf('%s:Import Commited',self::LOGKEY));
return collect(['dn'=>$o->getDN(),'result'=>__('Created')]);
default:
throw new GeneralException('Unhandled action during commit: '.$action);
}
}
abstract public function process(): Collection;
}

View File

@ -1,230 +0,0 @@
<?php
namespace App\Classes\LDAP\Import;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Nette\NotImplementedException;
use App\Classes\LDAP\Import;
use App\Exceptions\Import\{GeneralException,VersionException};
use App\Ldap\Entry;
/**
* Import LDIF to LDAP using an LDIF format
*
* The LDIF spec is described by RFC2849
* http://www.ietf.org/rfc/rfc2849.txt
*/
class LDIF extends Import
{
private const LOGKEY = 'ILF';
public function process(): Collection
{
$c = 0;
$action = NULL;
$attribute = NULL;
$base64encoded = FALSE;
$o = NULL;
$value = '';
$version = NULL;
$result = collect();
// @todo When renaming DNs, the hotlink should point to the new entry on success, or the old entry on failure.
foreach (preg_split('/(\r?\n|\r)/',$this->input) as $line) {
$c++;
Log::debug(sprintf('%s:LDIF Line [%s]',self::LOGKEY,$line));
$line = trim($line);
// If the line starts with a comment, ignore it
if (preg_match('/^#/',$line))
continue;
// If we have a blank line, then that completes this command
if (! $line) {
if (! is_null($o)) {
// Add the last attribute;
$o->addAttributeItem($attribute,$base64encoded ? base64_decode($value) : $value);
Log::debug(sprintf('%s:- Committing Entry [%s]',self::LOGKEY,$o->getDN()));
// Commit
$result->push($this->commit($o,$action));
$result->last()->put('line',$c);
$o = NULL;
$action = NULL;
$base64encoded = FALSE;
$attribute = NULL;
$value = '';
}
continue;
}
$m = [];
preg_match('/^([a-zA-Z0-9;-]+)(:+)\s+(.*)$/',$line,$m);
switch (Arr::get($m,1)) {
case 'changetype':
if ($m[2] !== ':')
throw new GeneralException(sprintf('ChangeType cannot be base64 encoded set at [%d]. (line %d)',$version,$c));
switch ($m[3]) {
// if (preg_match('/^changetype:[ ]*(delete|add|modrdn|moddn|modify)/i',$lines[0])) {
default:
throw new NotImplementedException(sprintf('Unknown change type [%s]? (line %d)',$m[3],$c));
}
break;
case 'version':
if (! is_null($version))
throw new VersionException(sprintf('Version has already been set at [%d]. (line %d)',$version,$c));
if ($m[2] !== ':')
throw new VersionException(sprintf('Version cannot be base64 encoded set at [%d]. (line %d)',$version,$c));
$version = (int)$m[3];
break;
// Treat it as an attribute
default:
// If $m is NULL, then this is the 2nd (or more) line of a base64 encoded value
if (! $m) {
$value .= $line;
Log::debug(sprintf('%s:- Attribute [%s] adding [%s] (%d)',self::LOGKEY,$attribute,$line,$c));
// add to last attr value
continue 2;
}
// We are ready to create the entry or add the attribute
if ($attribute) {
if ($attribute === 'dn') {
if (! is_null($o))
throw new GeneralException(sprintf('Previous Entry not complete? (line %d)',$c));
$dn = $base64encoded ? base64_decode($value) : $value;
Log::debug(sprintf('%s:Creating new entry:',self::LOGKEY,$dn));
//$o = Entry::find($dn);
// If it doesnt exist, we'll create it
//if (! $o) {
$o = new Entry;
$o->setDn($dn);
//}
$action = self::LDAP_IMPORT_ADD;
} else {
Log::debug(sprintf('%s:Adding Attribute [%s] value [%s] (%d)',self::LOGKEY,$attribute,$value,$c));
if ($value)
$o->addAttributeItem($attribute,$base64encoded ? base64_decode($value) : $value);
else
throw new GeneralException(sprintf('Attribute has no value [%s] (line %d)',$attribute,$c));
}
}
// Start of a new attribute
$base64encoded = ($m[2] === '::');
$attribute = $m[1];
$value = $m[3];
Log::debug(sprintf('%s:- New Attribute [%s] with [%s] (%d)',self::LOGKEY,$attribute,$value,$c));
}
if ($version !== 1)
throw new VersionException('LDIF import cannot handle version: '.($version ?: __('NOT DEFINED')));
}
// We may still have a pending action
if ($action) {
// Add the last attribute;
$o->addAttributeItem($attribute,$base64encoded ? base64_decode($value) : $value);
Log::debug(sprintf('%s:- Committing Entry [%s]',self::LOGKEY,$o->getDN()));
// Commit
$result->push($this->commit($o,$action));
$result->last()->put('line',$c);
}
return $result;
}
public function xreadEntry() {
static $haveVersion = FALSE;
if ($lines = $this->nextLines()) {
$server = $this->getServer();
# The first line should be the DN
if (preg_match('/^dn:/',$lines[0])) {
list($text,$dn) = $this->getAttrValue(array_shift($lines));
# The second line should be our changetype
if (preg_match('/^changetype:[ ]*(delete|add|modrdn|moddn|modify)/i',$lines[0])) {
$attrvalue = $this->getAttrValue($lines[0]);
$changetype = $attrvalue[1];
array_shift($lines);
} else
$changetype = 'add';
$this->template = new Template($this->server_id,NULL,NULL,$changetype);
switch ($changetype) {
case 'add':
$rdn = get_rdn($dn);
$container = $server->getContainer($dn);
$this->template->setContainer($container);
$this->template->accept();
$this->getAddDetails($lines);
$this->template->setRDNAttributes($rdn);
return $this->template;
break;
case 'modify':
if (! $server->dnExists($dn))
return $this->error(sprintf('%s %s',_('DN does not exist'),$dn),$lines);
$this->template->setDN($dn);
$this->template->accept(FALSE,TRUE);
return $this->getModifyDetails($lines);
break;
case 'moddn':
case 'modrdn':
if (! $server->dnExists($dn))
return $this->error(sprintf('%s %s',_('DN does not exist'),$dn),$lines);
$this->template->setDN($dn);
$this->template->accept();
return $this->getModRDNAttributes($lines);
break;
default:
if (! $server->dnExists($dn))
return $this->error(_('Unknown change type'),$lines);
}
} else
return $this->error(_('A valid dn line is required'),$lines);
} else
return FALSE;
}
}

View File

@ -1,355 +0,0 @@
<?php
namespace App\Classes\LDAP\Schema;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use App\Classes\LDAP\Attribute;
use App\Exceptions\InvalidUsage;
use App\Ldap\Entry;
/**
* Represents an LDAP AttributeType
*/
final class AttributeType extends Base
{
private const LOGKEY = 'SAT';
// An array of AttributeTypes which inherit from this one
private(set) Collection $children;
// The equality rule used
private(set) ?string $equality = NULL;
// This attribute has been forced a MAY attribute by the configuration.
private(set) bool $forced_as_may = FALSE;
// boolean: is collective?
private(set) bool $is_collective = FALSE;
// Is this a must attribute
private(set) bool $is_must = FALSE;
// boolean: can use modify?
private(set) bool $is_no_user_modification = FALSE;
// boolean: is single valued only?
private(set) bool $is_single_value = FALSE;
// The max number of characters this attribute can be
private(set) ?int $max_length = NULL;
// An array of names (including aliases) that this attribute is known by
private(set) Collection $names;
// The ordering of the attributeType
private(set) ?string $ordering = NULL;
// A list of object class names that require this attribute type.
private(set) Collection $required_by_object_classes;
// Which objectclass is defining this attribute for an Entry
public ?string $source = NULL;
// Supports substring matching?
private(set) ?string $sub_str_rule = NULL;
// The attribute from which this attribute inherits (if any)
private(set) ?string $sup_attribute = NULL;
// The full syntax string, ie 1.2.3.4{16}
private(set) ?string $syntax = NULL;
private(set) ?string $syntax_oid = NULL;
// The usage string set by the LDAP schema
private(set) ?string $usage = NULL;
// An array of objectClasses which use this attributeType (must be set by caller)
private(set) Collection $used_in_object_classes;
public function __get(string $key): mixed
{
return match ($key) {
'names_lc' => $this->names->map('strtolower'),
default => parent::__get($key)
};
}
/**
* Children of this attribute type that inherit from this one
*
* @param string $child
* @return void
*/
public function addChild(string $child): void
{
$this->children
->push($child);
}
/**
* Adds an objectClass name to this attribute's list of "required by" objectClasses,
* that is the list of objectClasses which must have this attribute.
*
* @param string $name The name of the objectClass to add.
* @param bool $structural
*/
public function addRequiredByObjectClass(string $name,bool $structural): void
{
if (! $this->required_by_object_classes->has($name))
$this->required_by_object_classes->put($name,$structural);
}
/**
* Adds an objectClass name to this attribute's list of "used in" objectClasses,
* that is the list of objectClasses which provide this attribute.
*
* @param string $name The name of the objectClass to add.
* @param bool $structural
*/
public function addUsedInObjectClass(string $name,bool $structural): void
{
if (! $this->used_in_object_classes->has($name))
$this->used_in_object_classes->put($name,$structural);
}
private function factory(): Attribute
{
return Attribute\Factory::create(
dn:'',
attribute:$this->name,
values:[]);
}
/**
* For a list of objectclasses return all parent objectclasses as well
*
* @param Collection $ocs
* @return Collection
*/
private function heirachy(Collection $ocs): Collection
{
$result = collect();
foreach ($ocs as $oc) {
$item = config('server')
->schema('objectclasses',$oc);
$result = $result
->merge($item
->getParents(TRUE)
->pluck('oid'))
->push($item->oid);
}
return $result;
}
/**
* Creates a new AttributeType object from a raw LDAP AttributeType string.
*
* eg: ( 2.5.4.0 NAME 'objectClass' DESC 'RFC4512: object classes of the entity' EQUALITY objectIdentifierMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.38 )
*/
protected function parse(string $line): void
{
Log::debug(sprintf('%s:Parsing AttributeType [%s]',self::LOGKEY,$line));
// Init
$this->names = collect();
$this->children = collect();
$this->used_in_object_classes = collect();
$this->required_by_object_classes = collect();
parent::parse($line);
}
protected function parse_chunk(array $strings,int &$i): void
{
switch ($strings[$i]) {
case 'NAME':
$name = '';
// @note Some schema's return a (' instead of a ( '
// @note This attribute format has no aliases
if ($strings[$i+1] !== '(' && ! preg_match('/^\(/',$strings[$i+1])) {
do {
$name .= ($name ? ' ' : '').$strings[++$i];
} while (! preg_match("/\'$/s",$strings[$i]));
} else {
$i++;
do {
// In case we came here because of a ('
if (preg_match('/^\(/',$strings[$i]))
$strings[$i] = preg_replace('/^\(/','',$strings[$i]);
else
$i++;
$name .= ($name ? ' ' : '').$strings[++$i];
} while (! preg_match("/\'$/s",$strings[$i]));
// Add alias names for this attribute
while ($strings[++$i] !== ')') {
$alias = preg_replace("/^\'(.*)\'$/",'$1',$strings[$i]);
$this->names->push($alias);
}
}
$this->names = $this->names->push(preg_replace("/^\'(.*)\'$/",'$1',$name))->sort();
$this->forced_as_may = $this->names_lc
->intersect(array_map('strtolower',config('pla.force_may',[])))
->count() > 0;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case NAME returned (%s)',self::LOGKEY,$this->name),['names'=>$this->names]);
break;
case 'SUP':
$this->sup_attribute = preg_replace("/^\'(.*)\'$/",'$1',$strings[++$i]);
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case SUP returned (%s)',self::LOGKEY,$this->sup_attribute));
break;
case 'EQUALITY':
$this->equality = $strings[++$i];
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case EQUALITY returned (%s)',self::LOGKEY,$this->equality));
break;
case 'ORDERING':
$this->ordering = $strings[++$i];
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case ORDERING returned (%s)',self::LOGKEY,$this->ordering));
break;
case 'SUBSTR':
$this->sub_str_rule = $strings[++$i];
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case SUBSTR returned (%s)',self::LOGKEY,$this->sub_str_rule));
break;
case 'SYNTAX':
$this->syntax = preg_replace("/^\'(.*)\'$/",'$1',$strings[++$i]);
$this->syntax_oid = preg_replace("/^\'?(.*){\d+}\'?$/",'$1',$this->syntax);
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:/ Evaluating SYNTAX returned (%s) [%s]',self::LOGKEY,$this->syntax,$this->syntax_oid));
// Does this SYNTAX string specify a max length (ie, 1.2.3.4{16})
$m = [];
$this->max_length = preg_match('/{(\d+)}$/',$this->syntax,$m)
? $m[1]
: NULL;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case SYNTAX returned (%s) [%s] {%d}',self::LOGKEY,$this->syntax,$this->syntax_oid,$this->max_length));
break;
case 'SINGLE-VALUE':
$this->is_single_value = TRUE;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case SINGLE-VALUE returned (%s)',self::LOGKEY,$this->is_single_value));
break;
case 'COLLECTIVE':
$this->is_collective = TRUE;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case COLLECTIVE returned (%s)',self::LOGKEY,$this->is_collective));
break;
case 'NO-USER-MODIFICATION':
$this->is_no_user_modification = TRUE;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case NO-USER-MODIFICATION returned (%s)',self::LOGKEY,$this->is_no_user_modification));
break;
case 'USAGE':
$this->usage = $strings[++$i];
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case USAGE returned (%s)',self::LOGKEY,$this->usage));
break;
default:
parent::parse_chunk($strings,$i);
}
}
/**
* Sets whether this attribute is single-valued.
*
* @param boolean $is
*/
public function setIsSingleValue(bool $is): void
{
$this->is_single_value = $is;
}
/**
* If this is a MUST attribute to the objectclass that defines it
*
* @return void
*/
public function setMust(): void
{
$this->is_must = TRUE;
}
/**
* Sets this attribute's name.
*
* @param string $name The new name to give this attribute.
* @throws InvalidUsage
*/
public function setName(string $name): void
{
// Quick validation
if ($this->names_lc->count() && (! $this->names_lc->contains(strtolower($name))))
throw new InvalidUsage(sprintf('Cannot set attribute name to [%s], its not an alias for [%s]',$name,$this->names->join(',')));
$this->name = $name;
}
/**
* Return Request validation array
*
* This will merge configured validation with schema required attributes
*
* @param array $array
* @return array|null
*/
public function validation(array $array): ?array
{
// For each item in array, we need to get the OC hierarchy
$heirachy = $this->heirachy(collect($array)
->flatten()
->filter());
// Get any config validation
$validation = collect(Arr::get(config('ldap.validation'),$this->name_lc,[]));
$nolangtag = sprintf('%s.%s.0',$this->name_lc,Entry::TAG_NOTAG);
// Add in schema required by conditions
if (($heirachy->intersect($this->required_by_object_classes->keys())->count() > 0)
&& (! collect($validation->get($this->name_lc))->contains('required'))) {
$validation
->prepend(array_merge(['required','min:1'],$validation->get($nolangtag,[])),$nolangtag)
->prepend(array_merge(['required','array','min:1',($this->factory()->no_attr_tags ? 'max:1' : NULL)],$validation->get($this->name_lc,[])),$this->name_lc);
}
return $validation->toArray();
}
}

View File

@ -1,150 +0,0 @@
<?php
namespace App\Classes\LDAP\Schema;
use Illuminate\Support\Facades\Log;
use App\Exceptions\InvalidUsage;
/**
* Generic parent class for all schema items.
*
* A schema item is an ObjectClass, an AttributeBype, a MatchingRule, or a Syntax.
* All schema items have at least two things in common: An OID and a Description.
*/
abstract class Base
{
private const LOGKEY = 'Sb-';
protected const DEBUG_VERBOSE = FALSE;
// Record the LDAP String
private(set) string $line;
// The schema item's name.
protected(set) string $name = '';
// The OID of this schema item.
protected(set) string $oid = '';
# The description of this schema item.
protected(set) string $description = '';
// Boolean value indicating whether this objectClass is obsolete
private(set) bool $is_obsolete = FALSE;
public function __construct(string $line)
{
$this->line = $line;
$this->parse($line);
}
public function __get(string $key): mixed
{
switch ($key) {
case 'name_lc': return strtolower($this->name);
default:
throw new InvalidUsage('Unknown key:'.$key);
}
}
public function __isset(string $key): bool
{
return isset($this->{$key});
}
public function __toString(): string
{
return $this->oid;
}
protected function parse(string $line): void
{
$strings = preg_split('/[\s,]+/',$line,-1,PREG_SPLIT_DELIM_CAPTURE);
for ($i=0; $i < count($strings); $i++) {
$this->parse_chunk($strings,$i);
}
}
protected function parse_chunk(array $strings,int &$i): void
{
switch ($strings[$i]) {
case '(':
case ')':
break;
case 'NAME':
if ($strings[$i+1] !== '(') {
do {
$this->name .= (strlen($this->name) ? ' ' : '').$strings[++$i];
} while (! preg_match('/\'$/s',$strings[$i]));
} else {
$i++;
do {
$this->name .= (strlen($this->name) ? ' ' : '').$strings[++$i];
} while (! preg_match('/\'$/s',$strings[$i]));
do {
$i++;
} while (! preg_match('/\)+\)?/',$strings[$i]));
}
$this->name = preg_replace("/^\'(.*)\'$/",'$1',$this->name);
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case NAME returned (%s)',self::LOGKEY,$this->name));
break;
case 'DESC':
do {
$this->description .= (strlen($this->description) ? ' ' : '').$strings[++$i];
} while (! preg_match('/\'$/s',$strings[$i]));
$this->description = preg_replace("/^\'(.*)\'$/",'$1',$this->description);
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case DESC returned (%s)',self::LOGKEY,$this->description));
break;
case 'OBSOLETE':
$this->is_obsolete = TRUE;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case OBSOLETE returned (%s)',self::LOGKEY,$this->is_obsolete));
break;
// @note currently not captured
case 'X-SUBST':
case 'X-ORDERED':
case 'X-EQUALITY':
case 'X-ORIGIN':
$value = '';
do {
$value .= ($value ? ' ' : '').preg_replace('/^\'(.+)\'$/','$1',$strings[++$i]);
} while (! preg_match("/\'$/s",$strings[$i]));
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case [%s] returned (%s) - IGNORED',self::LOGKEY,$strings[$i],$value));
break;
default:
if (preg_match('/[\d\.]+/i',$strings[$i]) && ($i === 1)) {
$this->oid = $strings[$i];
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case default returned OID (%s)',self::LOGKEY,$this->oid));
} elseif ($strings[$i])
Log::alert(sprintf('%s:! Case default discovered a value NOT parsed (%s)',self::LOGKEY,$strings[$i]));
}
}
}

View File

@ -1,54 +0,0 @@
<?php
namespace App\Classes\LDAP\Schema;
use Illuminate\Support\Facades\Log;
/**
* Represents an LDAP Syntax
*/
final class LDAPSyntax extends Base
{
private const LOGKEY = 'SLS';
// Is human readable?
private(set) ?bool $is_not_human_readable = NULL;
// Binary transfer required?
private(set) ?bool $binary_transfer_required = NULL;
/**
* Creates a new Syntax object from a raw LDAP syntax string.
*/
protected function parse(string $line): void
{
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:Parsing LDAPSyntax [%s]',self::LOGKEY,$line));
parent::parse($line);
}
protected function parse_chunk(array $strings,int &$i): void
{
for ($i=0; $i<count($strings); $i++) {
switch($strings[$i]) {
case 'X-BINARY-TRANSFER-REQUIRED':
$this->binary_transfer_required = (str_replace("'",'',$strings[++$i]) === 'TRUE');
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case X-BINARY-TRANSFER-REQUIRED returned (%s)',self::LOGKEY,$this->binary_transfer_required));
break;
case 'X-NOT-HUMAN-READABLE':
$this->is_not_human_readable = (str_replace("'",'',$strings[++$i]) === 'TRUE');
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case X-NOT-HUMAN-READABLE returned (%s)',self::LOGKEY,$this->is_not_human_readable));
break;
default:
parent::parse_chunk($strings,$i);
}
}
}
}

View File

@ -1,62 +0,0 @@
<?php
namespace App\Classes\LDAP\Schema;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
/**
* Represents an LDAP MatchingRule
*/
final class MatchingRule extends Base
{
private const LOGKEY = 'SMR';
// This rule's syntax OID
private(set) ?string $syntax = NULL;
// An array of attribute names who use this MatchingRule
private(set) Collection $used_by_attrs;
/**
* Adds an attribute name to the list of attributes who use this MatchingRule
*/
public function addUsedByAttr(string $name): void
{
$name = trim($name);
if (! $this->used_by_attrs->contains($name))
$this->used_by_attrs->push($name);
}
/**
* Creates a new MatchingRule object from a raw LDAP MatchingRule string.
*
* @param string $line
* @return void
*/
protected function parse(string $line): void
{
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:Parsing MatchingRule [%s]',self::LOGKEY,$line));
// Init
$this->used_by_attrs = collect();
parent::parse($line);
}
protected function parse_chunk(array $strings,int &$i): void
{
switch ($strings[$i]) {
case 'SYNTAX':
$this->syntax = $strings[++$i];
Log::debug(sprintf('- Case SYNTAX returned (%s)',$this->syntax));
break;
default:
parent::parse_chunk($strings,$i);
}
}
}

View File

@ -1,326 +0,0 @@
<?php
namespace App\Classes\LDAP\Schema;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use App\Classes\LDAP\Server;
use App\Exceptions\InvalidUsage;
/**
* Represents an LDAP Schema objectClass
*/
final class ObjectClass extends Base
{
private const LOGKEY = 'SOC';
// Array of objectClasses which inherit from this one
private(set) Collection $child_classes;
// Array of objectClass names from which this objectClass inherits
private(set) Collection $sup_classes;
// One of STRUCTURAL, ABSTRACT, or AUXILIARY
private int $type;
// Attributes that this objectclass defines
private(set) Collection $attributes;
public function __get(string $key): mixed
{
return match ($key) {
'all_attributes' => $this->getMustAttrs(TRUE)
->merge($this->getMayAttrs(TRUE)),
'type_name' => match ($this->type) {
Server::OC_STRUCTURAL => 'Structural',
Server::OC_ABSTRACT => 'Abstract',
Server::OC_AUXILIARY => 'Auxiliary',
default => throw new InvalidUsage('Unknown ObjectClass Type: ' . $this->type),
},
default => parent::__get($key),
};
}
/**
* Adds an objectClass to the list of objectClasses that inherit
* from this objectClass.
*
* @param String $name The name of the objectClass to add
*/
public function addChildObjectClass(string $name): void
{
if (! $this->child_classes->contains($name))
$this->child_classes->push($name);
}
/**
* Gets an array of AttributeType objects that entries of this ObjectClass may define.
* This differs from getMayAttrNames in that it returns an array of AttributeType objects
*
* @param bool $parents Also get the may attrs of our parents.
* @return Collection The array of allowed AttributeType objects.
*
* @throws InvalidUsage
* @see getMustAttrNames
* @see getMustAttrs
* @see getMayAttrNames
* @see AttributeType
*/
public function getMayAttrs(bool $parents=FALSE): Collection
{
$attrs = $this->attributes
->filter(fn($item)=>! $item->is_must)
->transform(function($item) {
$item->source = $this->name;
return $item;
});
if ($parents)
foreach ($this->getParents() as $object_class)
$attrs = $attrs->merge($object_class
->getMayAttrs($parents)
->transform(function($item) use ($object_class) {
$item->source = $item->source ?: $object_class->name;
return $item;
}));
// Return a sorted list
return $attrs
->unique(fn($item)=>$item->name)
->sortBy(fn($item)=>$item->name);
}
/**
* Gets an array of AttributeType objects that entries of this ObjectClass must define.
* This differs from getMustAttrNames in that it returns an array of AttributeType objects
*
* @param bool $parents Also get the must attrs of our parents.
* @return Collection The array of required AttributeType objects.
*
* @throws InvalidUsage
* @see getMustAttrNames
* @see getMayAttrs
* @see getMayAttrNames
*/
public function getMustAttrs(bool $parents=FALSE): Collection
{
$attrs = $this->attributes
->filter(fn($item)=>$item->is_must)
->transform(function($item) {
$item->source = $this->name;
return $item;
});
if ($parents)
foreach ($this->getParents() as $object_class)
$attrs = $attrs->merge($object_class
->getMustAttrs($parents)
->transform(function($item) use ($object_class) {
$item->source = $item->source ?: $object_class->name;
return $item;
}));
// Return a sorted list
return $attrs
->unique(fn($item)=>$item->name)
->sortBy(fn($item)=>$item->name);
}
/**
* This will return all our parent ObjectClass Objects
*/
public function getParents(): Collection
{
// If the only class is 'top', then we have no more parents
if (($this->sup_classes->count() === 1) && (strtolower($this->sup_classes->first()) === 'top'))
return collect();
$result = collect();
foreach ($this->sup_classes as $object_class) {
$oc = config('server')
->schema('objectclasses',$object_class);
if ($oc) {
$result->push($oc);
$result = $result->merge($oc->getParents());
}
}
return $result;
}
/**
* Return if this objectclass is auxiliary
*
* @return bool
*/
public function isAuxiliary(): bool
{
return $this->type === Server::OC_AUXILIARY;
}
public function isStructural(): bool
{
return $this->type === Server::OC_STRUCTURAL;
}
/**
* Creates a new ObjectClass object given a raw LDAP objectClass string.
*
* eg: ( 2.5.6.0 NAME 'top' DESC 'top of the superclass chain' ABSTRACT MUST objectClass )
*
* @param string $line Schema Line
*/
protected function parse(string $line): void
{
Log::debug(sprintf('%s:Parsing ObjectClass [%s]',self::LOGKEY,$line));
// Init
$this->attributes = collect();
$this->sup_classes = collect();
$this->child_classes = collect();
parent::parse($line);
}
protected function parse_chunk(array $strings,int &$i): void
{
switch ($strings[$i]) {
case 'SUP':
if ($strings[$i+1] !== '(') {
$this->sup_classes->push(preg_replace("/'/",'',$strings[++$i]));
} else {
$i++;
do {
$i++;
if ($strings[$i] !== '$')
$this->sup_classes->push(preg_replace("/'/",'',$strings[$i]));
} while (! preg_match('/\)+\)?/',$strings[$i+1]));
}
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case SUP returned (%s)',self::LOGKEY,$this->sup_classes->join(',')));
break;
case 'ABSTRACT':
$this->type = Server::OC_ABSTRACT;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case ABSTRACT returned (%s)',self::LOGKEY,$this->type));
break;
case 'STRUCTURAL':
$this->type = Server::OC_STRUCTURAL;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case STRUCTURAL returned (%s)',self::LOGKEY,$this->type));
break;
case 'AUXILIARY':
$this->type = Server::OC_AUXILIARY;
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case AUXILIARY returned (%s)',self::LOGKEY,$this->type));
break;
case 'MUST':
$attrs = collect();
$i = $this->parseList(++$i,$strings,$attrs);
foreach ($attrs as $string) {
$attr = clone config('server')->schema('attributetypes',$string);
if (! $attr->forced_as_may)
$attr->setMust();
$this->attributes->push($attr);
}
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case MUST returned (%s) (%s)',self::LOGKEY,$attrs->join(','),$this->forced_as_may ? 'FORCED MAY' : 'MUST'));
break;
case 'MAY':
$attrs = collect();
$i = $this->parseList(++$i,$strings,$attrs);
foreach ($attrs as $string)
$this->attributes->push(config('server')->schema('attributetypes',$string));
if (static::DEBUG_VERBOSE)
Log::debug(sprintf('%s:- Case MAY returned (%s)',self::LOGKEY,$attrs->join(',')));
break;
default:
parent::parse_chunk($strings,$i);
}
}
/**
* Parse an LDAP schema list
*
* A list starts with a ( followed by a list of attributes separated by $ terminated by )
* The first token can therefore be a ( or a (NAME or a (NAME)
* The last token can therefore be a ) or NAME)
* The last token may be terminated by more than one bracket
*/
private function parseList(int $i,array $strings,Collection &$attrs): int
{
$string = $strings[$i];
if (! preg_match('/^\(/',$string)) {
// A bareword only - can be terminated by a ) if the last item
if (preg_match('/\)+$/',$string))
$string = preg_replace('/\)+$/','',$string);
$attrs->push($string);
} elseif (preg_match('/^\(.*\)$/',$string)) {
$string = preg_replace('/^\(/','',$string);
$string = preg_replace('/\)+$/','',$string);
$attrs->push($string);
} else {
// Handle the opening cases first
if ($string === '(') {
$i++;
} elseif (preg_match('/^\(./',$string)) {
$string = preg_replace('/^\(/','',$string);
$attrs->push($string);
$i++;
}
// Token is either a name, a $ or a ')'
// NAME can be terminated by one or more ')'
while (! preg_match('/\)+$/',$strings[$i])) {
$string = $strings[$i];
if ($string === '$') {
$i++;
continue;
}
if (preg_match('/\)$/',$string))
$string = preg_replace('/\)+$/','',$string);
else
$i++;
$attrs->push($string);
}
}
$attrs = $attrs->sort();
return $i;
}
}

View File

@ -1,510 +0,0 @@
<?php
namespace App\Classes\LDAP;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use LdapRecord\LdapRecordException;
use LdapRecord\Models\Model;
use LdapRecord\Query\Builder;
use LdapRecord\Query\Collection as LDAPCollection;
use LdapRecord\Query\ObjectNotFoundException;
use App\Classes\LDAP\Schema\{AttributeType,Base,LDAPSyntax,MatchingRule,ObjectClass};
use App\Exceptions\InvalidUsage;
use App\Ldap\Entry;
final class Server
{
private const LOGKEY = 'SVR';
// This servers schema objectclasses
private Collection $attributetypes;
private Collection $ldapsyntaxes;
private Collection $matchingrules;
private Collection $objectclasses;
private Model $rootDSE;
/* ObjectClass Types */
public const OC_STRUCTURAL = 0x01;
public const OC_ABSTRACT = 0x02;
public const OC_AUXILIARY = 0x03;
public function __construct()
{
$this->rootDSE = self::rootDSE();
$this->attributetypes = collect();
$this->ldapsyntaxes = collect();
$this->matchingrules = collect();
$this->objectclasses = collect();
}
public function __get(string $key): mixed
{
return match($key) {
'config' => config(sprintf('ldap.connections.%s',config('ldap.default'))),
'name' => Arr::get($this->config,'name',__('No Server Name Yet')),
default => throw new Exception('Unknown key:'.$key),
};
}
/* STATIC METHODS */
/**
* Gets the root DN of the specified LDAPServer, or throws an exception if it
* can't find it.
*
* @param bool $objects Return a collection of Entry Models
* @return Collection
* @testedin GetBaseDNTest::testBaseDNExists();
*/
public static function baseDNs(bool $objects=TRUE): Collection
{
try {
$namingcontexts = collect(config('pla.base_dns') ?: self::rootDSE()?->namingcontexts);
/**
* LDAP Error Codes:
* https://ldap.com/ldap-result-code-reference/
* + success 0
* + operationsError 1
* + protocolError 2
* + timeLimitExceeded 3
* + sizeLimitExceeded 4
* + compareFalse 5
* + compareTrue 6
* + authMethodNotSupported 7
* + strongerAuthRequired 8
* + referral 10
* + adminLimitExceeded 11
* + unavailableCriticalExtension 12
* + confidentialityRequired 13
* + saslBindInProgress 14
* + noSuchAttribute 16
* + undefinedAttributeType 17
* + inappropriateMatching 18
* + constraintViolation 19
* + attributeOrValueExists 20
* + invalidAttributeSyntax 21
* + noSuchObject 32
* + aliasProblem 33
* + invalidDNSyntax 34
* + isLeaf 35
* + aliasDereferencingProblem 36
* + inappropriateAuthentication 48
* + invalidCredentials 49
* + insufficientAccessRights 50
* + busy 51
* + unavailable 52
* + unwillingToPerform 53
* + loopDetect 54
* + sortControlMissing 60
* + offsetRangeError 61
* + namingViolation 64
* + objectClassViolation 65
* + notAllowedOnNonLeaf 66
* + notAllowedOnRDN 67
* + entryAlreadyExists 68
* + objectClassModsProhibited 69
* + resultsTooLarge 70
* + affectsMultipleDSAs 71
* + virtualListViewError or controlError 76
* + other 80
* + serverDown 81
* + localError 82
* + encodingError 83
* + decodingError 84
* + timeout 85
* + authUnknown 86
* + filterError 87
* + userCanceled 88
* + paramError 89
* + noMemory 90
* + connectError 91
* + notSupported 92
* + controlNotFound 93
* + noResultsReturned 94
* + moreResultsToReturn 95
* + clientLoop 96
* + referralLimitExceeded 97
* + invalidResponse 100
* + ambiguousResponse 101
* + tlsNotSupported 112
* + intermediateResponse 113
* + unknownType 114
* + canceled 118
* + noSuchOperation 119
* + tooLate 120
* + cannotCancel 121
* + assertionFailed 122
* + authorizationDenied 123
* + e-syncRefreshRequired 4096
* + noOperation 16654
*
* LDAP Tag Codes:
* + A client bind operation 97
* + The entry for which you were searching 100
* + The result from a search operation 101
* + The result from a modify operation 103
* + The result from an add operation 105
* + The result from a delete operation 107
* + The result from a modify DN operation 109
* + The result from a compare operation 111
* + A search reference when the entry you perform your search on holds a referral to the entry you require.
* + Search references are expressed in terms of a referral.
* 115
* + A result from an extended operation 120
*/
// If we cannot get to our LDAP server we'll head straight to the error page
} catch (LdapRecordException $e) {
switch ($e->getDetailedError()?->getErrorCode()) {
case 49:
abort(401,$e->getDetailedError()->getErrorMessage());
default:
abort(597,$e->getDetailedError()?->getErrorMessage() ?: $e->getMessage());
}
}
if (! $objects)
return $namingcontexts;
return Cache::remember('basedns'.Session::id(),config('ldap.cache.time'),function() use ($namingcontexts) {
$result = collect();
// @note: Incase our rootDSE didnt return a namingcontext, we'll have no base DNs
foreach ($namingcontexts as $dn)
$result->push(self::get($dn)->read()->find($dn));
return $result->filter()->sort(fn($item)=>$item->sort_key);
});
}
/**
* Work out if we should flush the cache when retrieving an entry
*
* @param string $dn
* @return bool
* @note: We dont need to flush the cache for internal LDAP attributes, as we dont change them
*/
private static function cacheflush(string $dn): bool
{
$cache = (! config('ldap.cache.enabled'))
|| match (strtolower($dn)) {
'','cn=schema','cn=subschema' => FALSE,
default => TRUE,
};
Log::debug(sprintf('%s:%s - %s',self::LOGKEY,$cache ? 'DN CACHEABLE' : 'DN NOT cacheable',$dn));
return $cache;
}
/**
* Return our cache time as per the configuration
*
* @return Carbon
*/
private static function cachetime(): Carbon
{
return Carbon::now()
->addSeconds(Config::get('ldap.cache.time') ?: 0);
}
/**
* Generic Builder method to setup our queries consistently - mainly to ensure we cache results
*
* @param string $dn
* @param array $attrs
* @return Builder
*/
private static function get(string $dn,array $attrs=['*','+']): Builder
{
return Entry::query()
->setDN($dn)
->cache(
until: self::cachetime(),
flush: self::cacheflush($dn)
)
->select($attrs);
}
/**
* Obtain the rootDSE for the server, that gives us server information
*
* @return Model
* @throws ObjectNotFoundException
* @testedin TranslateOidTest::testRootDSE();
* @note While we are using a static variable for in session performance, we'll also cache the result normally
*/
public static function rootDSE(): Model
{
static $rootdse = NULL;
if (is_null($rootdse))
$rootdse = self::get('',['+','*'])
->read()
->firstOrFail();
return $rootdse;
}
/* METHODS */
/**
* Query the server for a DN and return its children and if those children have children.
*
* @param string $dn
* @param array $attrs
* @return LDAPCollection|NULL
*/
public function children(string $dn,array $attrs=['dn']): ?LDAPCollection
{
return $this
->get(
dn: $dn,
attrs: array_merge($attrs,[
'hassubordinates', // Needed for the tree to know if an entry has children
'c' // Needed for the tree to show icons for countries
]))
->list()
->get() ?: NULL;
}
/**
* Fetch a DN from the server
*
* @param string $dn
* @param array $attrs
* @return Model|null
*/
public function fetch(string $dn,array $attrs=['*','+']): ?Model
{
return $this->get($dn,$attrs)
->read()
->first() ?: NULL;
}
/**
* Get an attribute key for an attributetype name
*
* @param string $key
* @return int|bool
* @throws InvalidUsage
*/
public function get_attr_id(string $key): int|bool
{
static $attributes = $this->schema('attributetypes');
$attrid = $attributes->search(fn($item)=>$item->names->contains($key));
// Second chance search using lowercase items (our Entry attribute keys are lowercase)
if ($attrid === FALSE)
$attrid = $attributes->search(fn($item)=>$item->names_lc->contains(strtolower($key)));
return $attrid;
}
/**
* Given an OID, return the ldapsyntax for the OID
*
* @param string $oid
* @return LDAPSyntax|null
* @throws InvalidUsage
*/
public function get_syntax(string $oid): ?LDAPSyntax
{
return (($id=$this->schema('ldapsyntaxes')->search(fn($item)=>$item->oid === $oid)) !== FALSE)
? $this->ldapsyntaxes[$id]
: NULL;
}
/**
* Does this server support RFC3666 language tags
* OID: 1.3.6.1.4.1.4203.1.5.4
*
* @return bool
* @throws ObjectNotFoundException
*/
public function isLanguageTags(): bool
{
return in_array('1.3.6.1.4.1.4203.1.5.4',$this->rootDSE()->supportedfeatures);
}
/**
* Return the server's schema
*
* @param string $item Schema Item to Fetch
* @param string|null $key
* @return Collection|LDAPSyntax|Base|NULL
* @throws InvalidUsage
*/
public function schema(string $item,?string $key=NULL): Collection|LDAPSyntax|Base|NULL
{
// Ensure our item to fetch is lower case
$item = strtolower($item);
if (! $this->{$item}->count()) {
$this->{$item} = Cache::remember('schema.'.$item,config('ldap.cache.time'),function() use ($item) {
// Try to get the schema DN from the specified entry.
$schema_dn = $this->schemaDN();
// @note: 389DS does not return subschemaSubentry unless it is requested
$schema = $this->fetch($schema_dn,['*','+','subschemaSubentry']);
// If our schema's null, we didnt find it.
if (! $schema)
throw new Exception('Couldnt find schema at:'.$schema_dn);
switch ($item) {
case 'attributetypes':
Log::debug(sprintf('%s:Attribute Types',self::LOGKEY));
// build the array of attribueTypes
//$syntaxes = $this->SchemaSyntaxes($dn);
foreach ($schema->{$item} as $line) {
if (is_null($line) || ! strlen($line))
continue;
$o = new AttributeType($line);
$this->attributetypes->push($o);
}
foreach ($this->attributetypes as $o) {
// Now go through and reference the parent/child relationships
if ($o->sup_attribute) {
$attrid = $this->get_attr_id($o->sup_attribute);
if (! $this->attributetypes[$attrid]->children->contains($o->oid))
$this->attributetypes[$attrid]->addChild($o->oid);
}
// go through any children and add details if the child doesnt have them (ie, cn inherits name)
foreach ($o->children as $child) {
$attrid = $this->attributetypes->search(fn($o)=>$o->oid === $child);
/* only overwrite the child's SINGLE-VALUE property if the parent has it set, and the child doesnt
* (note: All LDAP attributes default to multi-value if not explicitly set SINGLE-VALUE) */
if (! is_null($o->is_single_value) && is_null($this->attributetypes[$attrid]->is_single_value))
$this->attributetypes[$attrid]->setIsSingleValue($o->is_single_value);
}
}
return $this->attributetypes;
case 'ldapsyntaxes':
Log::debug(sprintf('%s:LDAP Syntaxes',self::LOGKEY));
foreach ($schema->{$item} as $line) {
if (is_null($line) || ! strlen($line))
continue;
$o = new LDAPSyntax($line);
$this->ldapsyntaxes->push($o);
}
return $this->ldapsyntaxes;
case 'matchingrules':
Log::debug(sprintf('%s:Matching Rules',self::LOGKEY));
foreach ($schema->{$item} as $line) {
if (is_null($line) || ! strlen($line))
continue;
$o = new MatchingRule($line);
$this->matchingrules->push($o);
}
foreach ($this->schema('attributetypes') as $attr) {
$rule_id = $this->matchingrules->search(fn($item)=>$item->oid === $attr->equality);
if ($rule_id !== FALSE)
$this->matchingrules[$rule_id]->addUsedByAttr($attr->name);
}
return $this->matchingrules;
case 'objectclasses':
Log::debug(sprintf('%s:Object Classes',self::LOGKEY));
foreach ($schema->{$item} as $line) {
if (is_null($line) || ! strlen($line))
continue;
$o = new ObjectClass($line);
$this->objectclasses->push($o);
}
foreach ($this->objectclasses as $o) {
// Now go through and reference the parent/child relationships
foreach ($o->sup_classes as $sup) {
$oc_id = $this->objectclasses->search(fn($item)=>$item->name === $sup);
if (($oc_id !== FALSE) && (! $this->objectclasses[$oc_id]->child_classes->contains($o->name)))
$this->objectclasses[$oc_id]->addChildObjectClass($o->name);
}
// Add the used in and required_by values for attributes.
foreach ($o->attributes as $attribute) {
if (($attrid = $this->schema('attributetypes')->search(fn($item)=>$item->oid === $attribute->oid)) !== FALSE) {
// Add Used In.
$this->attributetypes[$attrid]->addUsedInObjectClass($o->oid,$o->isStructural());
// Add Required By.
if ($attribute->is_must)
$this->attributetypes[$attrid]->addRequiredByObjectClass($o->oid,$o->isStructural());
}
}
}
// Put the updated attributetypes back in the cache
Cache::put('schema.attributetypes',$this->attributetypes,config('ldap.cache.time'));
return $this->objectclasses;
// Shouldnt get here
default:
throw new InvalidUsage('Invalid request to fetch schema: '.$item);
}
});
}
if (is_null($key))
return $this->{$item};
switch ($item) {
case 'attributetypes':
$attrid = $this->get_attr_id($key);
$attr = ($attrid === FALSE)
? new AttributeType($key)
: clone $this->{$item}->get($attrid);
$attr->setName($attr->names->get($attr->names_lc->search(strtolower($key))) ?: $key);
return $attr;
default:
return $this->{$item}->get($key)
?: $this->{$item}->first(fn($item)=>$item->name_lc === strtolower($key));
}
}
/**
* Get the Schema DN
*
* @return string
* @throws ObjectNotFoundException
*/
public function schemaDN(): string
{
return Arr::get($this->rootDSE->subschemasubentry,0);
}
}

View File

@ -1,450 +0,0 @@
<?php
namespace App\Classes;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Ldap\Entry;
class Template
{
private const LOGKEY = 'T--';
private const LOCK_TIME = 600;
private(set) string $file;
private Collection $template;
private(set) bool $invalid = FALSE;
private(set) string $reason = '';
private Collection $on_change_target;
private Collection $on_change_attribute;
private bool $on_change_processed = FALSE;
public function __construct(string $file)
{
$td = Storage::disk(config('pla.template.dir'));
$this->on_change_attribute = collect();
$this->on_change_target = collect();
$this->file = $file;
try {
// @todo Load in the proper attribute objects and objectclass objects
// @todo Make sure we have a structural objectclass, or make the template invalid
$this->template = collect(json_decode($td->get($file),null,512,JSON_OBJECT_AS_ARRAY|JSON_THROW_ON_ERROR));
} catch (\JsonException $e) {
$this->invalid = TRUE;
$this->reason = $e->getMessage();
}
}
public function __get(string $key): mixed
{
return match ($key) {
'attributes','objectclasses' => collect($this->template->get($key)),
'enabled' => $this->template->get($key,FALSE) && (! $this->invalid),
'icon','regexp','title' => $this->template->get($key),
'name' => Str::replaceEnd('.json','',$this->file),
'order' => $this->attributes->map(fn($item)=>Arr::get($item,'order')),
default => throw new \Exception('Unknown key: '.$key),
};
}
public function __isset(string $key): bool
{
return $this->template->has($key);
}
/**
* Return the configuration for an attribute
*
* @param string $attribute
* @return array|NULL
*/
public function attribute(string $attribute): Collection|NULL
{
$key = $this->attributes->search(fn($item,$key)=>! strcasecmp($key,$attribute));
return collect($this->attributes->get($key));
}
/**
* Return an template attributes select options
*
* @param string $attribute
* @return Collection|NULL
*/
public function attributeOptions(string $attribute): Collection|NULL
{
return ($x=$this->attribute($attribute)?->get('options'))
? collect($x)->map(fn($item,$key)=>['id'=>$key,'value'=>$item])
: NULL;
}
/**
* If the attribute has been marked as read-only
*
* @param string $attribute
* @return bool
*/
public function attributeReadOnly(string $attribute): bool
{
return ($x=$this->attribute($attribute)?->get('readonly')) && $x;
}
/**
* Return the title we should use for an attribute
*
* @param string $attribute
* @return string|NULL
*/
public function attributeTitle(string $attribute): string|NULL
{
return $this->attribute($attribute)?->get('display');
}
/**
* Return the title we should use for an attribute
*
* @param string $attribute
* @return string|NULL
*/
public function attributeType(string $attribute): string|NULL
{
return $this->attribute($attribute)?->get('type');
}
public function attributeValue(string $attribute): string|NULL
{
if ($x=$this->attribute($attribute)->get('value')) {
list($command,$args) = preg_split('/^=([a-zA-Z]+)\((.+)\)$/',$x,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
return match ($command) {
'getNextNumber' => $this->getNextNumber($args),
default => NULL,
};
}
return NULL;
}
/**
* Get next number for an attribute
*
* As part of getting the next number, we'll use a lock to avoid any potential clashes. The lock is obtained by
* two lock files:
* a: Read a session lock (our session id), use that number if it exists, otherwise,
* b: Query the ldap server for the attribute, sort by number
* c: Read a system lock, if it exists, and use that as our start base (otherwise use a config() base)
* d: Starting at base, find the next free number
* e: When number identified, put it in the system lock with our session id
* f: Put the number in our session lock, with a timeout
* g: Read the system lock, make sure our session id is still in it, if not, go to (d) with our number as the base
* h: Remove our session id from the system lock (our number is unique)
*
* When using the number to create an entry:
* + Read our session lock, confirm the number is still in it, if not fail validation and bounce back
* + Create the entry
* + Delete our session lock
*
* @param string $arg
* @return int|NULL
*/
private function getNextNumber(string $arg): int|NULL
{
if (! preg_match('/;/',$arg)) {
Log::alert(sprintf('%s:Invalid argument given to getNextNumber [%s]',self::LOGKEY,$arg));
return NULL;
}
list($start,$attr) = preg_split('(([^,]+);(\w+))',$arg,-1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$attr = strtolower($attr);
// If we recently got a number, return it
if ($number=Cache::get($attr.':'.Session::id()))
return $number;
$cache = Cache::get($attr.':system');
Log::debug(sprintf('%s:System Cache has',self::LOGKEY),['cache'=>$cache]);
if (! Arr::get($cache,'number'))
$number = config('pla.template.getnextnumber.'.$attr,0);
else
$number = Arr::get($cache,'number')+1;
Log::debug(sprintf('%s:Starting with [%d] for [%s]',self::LOGKEY,$number,$attr));
$o = config('server');
$bases = ($start === '/') ? $o->baseDNs() : collect($start);
$result = collect();
$complete = [];
do {
$sizelimit = FALSE;
// Get the current numbers
foreach ($bases as $base) {
if (Arr::get($complete,$dn=$base->getDN()))
continue;
$query = Entry::query()
->setDN($base)
->select([$attr])
->where($attr,'*')
->notFilter(fn($q)=>$q->where($attr,'<=',$number-1));
if ($result->count())
$query->notFilter(fn($q)=>$q->where($attr,'>=',$result->min()));
$result = $result->merge(($x=$query
->search()
->orderBy($attr)
->get())
->pluck($attr)
->flatten());
// If we hit a sizelimit on this run
$base_sizelimit = $query->getModel()->hasMore();
Log::debug(sprintf('%s:Query in [%s] returned [%d] entries and has more [%s]',self::LOGKEY,$base,$x->count(),$base_sizelimit ? 'TRUE' : 'FALSE'));
if (! $base_sizelimit)
$complete[$dn] = TRUE;
else
Log::info(sprintf('%s:Size Limit alert for [%s]',self::LOGKEY,$dn));
$sizelimit = $sizelimit || $base_sizelimit;
}
$result = $result
->sort()
->unique();
Log::debug(sprintf('%s:Result has [%s]',self::LOGKEY,$result->join('|')));
if ($result->count())
foreach ($result as $item) {
Log::debug(sprintf('%s:Checking [%d] against [%s]',self::LOGKEY,$number,$item));
if ($number < $item)
break;
$number += 1;
}
else
$number += 1;
// Remove redundant entries
$result = $result->filter(fn($item)=>$item>$number);
if ($sizelimit)
Log::debug(sprintf('%s:We got a sizelimit.',self::LOGKEY),['number'=>$number,'result_min'=>$result->min(),'result_count'=>$result->count()]);
/*
* @todo This might need some additional work:
* EG: if sizelimit is 5
* if result has 1,2,3,4,20 [size limit]
* we re-enquire (4=>20) and get 7,8,9,10,11 [size limit]
* we re-enquire (4=>7) and get 5,6 [no size limit]
* we calculate 12, and accept it because no size limit, but we didnt test for 12
*/
} while ($sizelimit);
// We found our number
Log::debug(sprintf('%s:Autovalue for Attribute [%s] in Session [%s] Storing [%d]',self::LOGKEY,$attr,Session::id(),$number));
Cache::put($attr.':system',['number'=>$number,'session'=>Session::id(),self::LOCK_TIME*2]);
Cache::put($attr.':'.Session::id(),$number,self::LOCK_TIME);
sleep(1);
// If the session still has our session ID, then our number is ours
return (Arr::get(Cache::get($attr.':system'),'session') === Session::id())
? $number
: NULL;
}
/**
* Return the onChange JavaScript for an attribute
*
* @param string $attribute
* @return Collection|NULL
*/
public function onChange(string $attribute): Collection|NULL
{
if (! $this->on_change_processed)
$this->onChangeProcessing();
return $this->on_change_attribute
->get(strtolower($attribute));
}
/**
* Is this attribute's value populated by any onChange processing rules
*
* @param string $attribute
* @return bool
*/
public function onChangeAttribute(string $attribute): bool
{
if (! $this->on_change_processed)
$this->onChangeProcessing();
return $this->on_change_attribute
->has(strtolower($attribute));
}
/**
* Process the attributes for onChange JavaScript
*/
/**
* Return the onchange JavaScript for attribute
*
* @return Collection
*/
private function onChangeProcessing(): void
{
foreach (Arr::get($this->template,'attributes',[]) as $attribute => $detail) {
$result = collect();
foreach (Arr::get($detail,'onchange',[]) as $item) {
list($command,$args) = preg_split('/^=([a-zA-Z]+)\((.+)\)$/',$item,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
switch ($command) {
case 'autoFill':
$result->push($this->autofill($args));
break;
}
}
if ($result->count())
$this->on_change_attribute->put(strtolower($attribute),$result);
}
$this->on_change_processed = TRUE;
}
/**
* Is this attribute's value populated by any onChange processing rules
*
* @param string $attribute
* @return bool
*/
public function onChangeTarget(string $attribute): bool
{
if (! $this->on_change_processed)
$this->onChangeProcessing();
return $this->on_change_target
->has(strtolower($attribute));
}
/**
* autoFill - javascript to have one attribute fill the value of another
*
* args: is a literal string, with two parts, delimited by a semi-colon ;
* + The first part is the attribute that will be populated
* + The second part may contain many fields like %attr|start-end/flags|additionalcontrolchar%
* to substitute values read from other fields.
* + |start-end is optional, but must be present if the k flag is used
* + /flags is optional
* + |additionalcontrolchar is optional, and specific to a flag being used
*
* + flags may be:
* T:(?) Read display text from selection item (drop-down list), otherwise, read the value of the field
* For fields that aren't selection items, /T shouldn't be used, and the field value will always be read
* k:(?) Tokenize:
* If the "k" flag is not given:
* + A |start-end instruction will perform a sub-string operation upon the value of the attr, passing
* character positions start-end through
* + start can be 0 for first character, or any other integer
* + end can be 0 for last character, or any other integer for a specific position
* If the "k" flag is given:
* + The string read will be split into fields, using : as a delimiter
* + start indicates which field number to pass through
*
* If additionalcontrolchar is given, it will be used as delimiter (e.g. this allows for splitting
* e-mail addresses into domain and domain-local part)
* l: Make the result lower case
* U: Make the result upper case
* A:(?) Remap special characters to their corresponding ASCII value
*
* @note Attributes rendered on the page are lowercase, eg: <attribute id="gidnumber"> for gidNumber
* @note JavaScript generated here depends on js/template.js
* (?) = to test
*/
private function autofill(string $arg): string
{
if (! preg_match('/;/',$arg)) {
Log::alert(sprintf('%s:Invalid argument given to autofill [%s]',self::LOGKEY,$arg));
return '';
}
$result = '';
// $attr has our attribute to update, $string is the format to use when updating it
list($attr,$string) = preg_split('(([^,]+);(.*))',$arg,-1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$this->on_change_target->put(strtolower($attr),$string);
$output = $string;
//$result .= sprintf("\n// %s\n",$arg);
$m = [];
// MATCH : 0 = highlevel match, 1 = attr, 2 = subst, 3 = mod, 4 = delimiter
preg_match_all('/%(\w+)(?:\|(\d*-\d)+)?(?:\/([klTUA]+))?(?:\|(.)?)?%/U',$string,$m);
foreach ($m[0] as $index => $null) {
$match_attr = strtolower($m[1][$index]);
$match_subst = $m[2][$index];
$match_mod = $m[3][$index];
$match_delim = $m[4][$index];
$substrarray = [];
$result .= sprintf("var %s;\n",$match_attr);
if (str_contains($match_mod,'k')) {
preg_match_all('/(\d+)/',trim($match_subst),$substrarray);
$delimiter = ($match_delim === '') ? ' ' : preg_quote($match_delim);
$result .= sprintf(" %s = %s.split('%s')[%s];\n",$match_attr,$match_attr,$delimiter,$substrarray[1][0] ?? '0');
} else {
// Work out the start and end chars needed from this value if we have a range specifier
preg_match_all('/(\d*)-(\d+)/',$match_subst,$substrarray);
if ((isset($substrarray[1][0]) && $substrarray[1][0]) || (isset($substrarray[2][0]) && $substrarray[2][0])) {
$result .= sprintf("%s = get_attribute('%s',%d,%s);\n",
$match_attr,$match_attr,
$substrarray[1][0] ?? '0',
$substrarray[2][0] ?: sprintf('%s.length',$match_attr));
} else {
$result .= sprintf("%s = get_attribute('%s');\n",$match_attr,$match_attr);
}
}
if (str_contains($match_mod,'l'))
$result .= sprintf("%s = %s.toLowerCase();\n",$match_attr,$match_attr);
if (str_contains($match_mod,'U'))
$result .= sprintf("%s = %s.toUpperCase();\n",$match_attr,$match_attr);
if (str_contains($match_mod,'A'))
$result .= sprintf("%s = toAscii(%s);\n",$match_attr,$match_attr);
// For debugging
//$result .= sprintf("console.log('%s will return:'+%s);\n",$match_attr,$match_attr);
// Reformat out output into JS variables
$output = preg_replace('/'.preg_quote($m[0][$index],'/').'/','\'+'.$match_attr.'+\'',$output);
}
$result .= sprintf("put_attribute('%s','%s');\n",strtolower($attr),$output);
$result .= "\n";
return $result;
}
}

View File

@ -1,7 +0,0 @@
<?php
namespace App\Exceptions\Import;
use Exception;
class AttributeException extends Exception {}

View File

@ -1,7 +0,0 @@
<?php
namespace App\Exceptions\Import;
use Exception;
class GeneralException extends Exception {}

View File

@ -1,7 +0,0 @@
<?php
namespace App\Exceptions\Import;
use Exception;
class ObjectExistsException extends Exception {}

View File

@ -1,7 +0,0 @@
<?php
namespace App\Exceptions\Import;
use Exception;
class VersionException extends Exception {}

View File

@ -1,10 +0,0 @@
<?php
namespace App\Exceptions;
use Exception;
class InvalidUsage extends Exception
{
//
}

View File

@ -1,116 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Collection;
use App\Classes\LDAP\Server;
class AjaxController extends Controller
{
private const LOGKEY = 'CAc';
/**
* Get the LDAP server BASE DNs
*
* @return Collection
* @throws \LdapRecord\Query\ObjectNotFoundException
*/
public function bases(): Collection
{
return Server::baseDNs()
->map(fn($item)=> [
'title'=>$item->getRdn(),
'item'=>$item->getDNSecure(),
'lazy'=>TRUE,
'icon'=>'fa-fw fas fa-sitemap',
'tooltip'=>$item->getDn(),
])->values();
}
/**
* @param Request $request
* @return Collection
*/
public function children(Request $request): Collection
{
$dn = Crypt::decryptString($request->post('_key'));
// Sometimes our key has a command, so we'll ignore it
if (str_starts_with($dn,'*') && ($x=strpos($dn,'|')))
$dn = substr($dn,$x+1);
Log::debug(sprintf('%s:Query [%s]',self::LOGKEY,$dn));
return (config('server'))
->children($dn)
->transform(fn($item)=>
[
'title'=>$item->getRdn(),
'item'=>$item->getDNSecure(),
'icon'=>$item->icon(),
'lazy'=>Arr::get($item->getAttribute('hassubordinates'),0) == 'TRUE',
'tooltip'=>$item->getDn(),
])
->prepend(
$request->create
? [
'title'=>sprintf('[%s]',__('Create Entry')),
'item'=>Crypt::encryptString(sprintf('*%s|%s','create',$dn)),
'lazy'=>FALSE,
'icon'=>'fas fa-fw fa-square-plus text-warning',
'tooltip'=>__('Create new LDAP item here'),
]
: []
)
->filter()
->values();
}
public function schema_view(Request $request)
{
$server = new Server;
switch($request->type) {
case 'objectclasses':
return view('fragment.schema.objectclasses')
->with('objectclasses',$server->schema('objectclasses')->sortBy(fn($item)=>strtolower($item->name)));
case 'attributetypes':
return view('fragment.schema.attributetypes')
->with('server',$server)
->with('attributetypes',$server->schema('attributetypes')->sortBy(fn($item)=>strtolower($item->name)));
case 'ldapsyntaxes':
return view('fragment.schema.ldapsyntaxes')
->with('ldapsyntaxes',$server->schema('ldapsyntaxes')->sortBy(fn($item)=>strtolower($item->description)));
case 'matchingrules':
return view('fragment.schema.matchingrules')
->with('matchingrules',$server->schema('matchingrules')->sortBy(fn($item)=>strtolower($item->name)));
default:
abort(404);
}
}
/**
* Return the required and additional attributes for an object class
*
* @param string $objectclass
* @return array
*/
public function schema_objectclass_attrs(string $objectclass): array
{
$oc = config('server')->schema('objectclasses',$objectclass);
return [
'must' => $oc->getMustAttrs()->pluck('name'),
'may' => $oc->getMayAttrs()->pluck('name'),
];
}
}

View File

@ -1,144 +0,0 @@
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use LdapRecord\Auth\BindException;
use LdapRecord\Container;
use App\Http\Controllers\Controller;
use App\Ldap\Entry;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')
->except('logout');
}
protected function credentials(Request $request): array
{
return [
login_attr_name() => $request->get(login_attr_name()),
'password' => $request->get('password'),
];
}
/**
* When attempt to login
*
* @param Request $request
* @return bool
* @throws \LdapRecord\ConnectionException
* @throws \LdapRecord\ContainerException
*/
public function attemptLogin(Request $request)
{
$attempt = $this->guard()->attempt(
$this->credentials($request), $request->boolean('remember')
);
// If the login failed, and PLA is set to use DN login, check if the entry exists.
// If the entry doesnt exist, it might be the root DN, which cannot be used to login
if ((! $attempt) && $request->dn && config('pla.login.alert_rootdn',TRUE)) {
// Double check our credentials, and see if they authenticate
try {
Container::getInstance()
->getConnection()
->auth()
->bind($request->get(login_attr_name()),$request->get('password'));
} catch (BindException $e) {
// Password incorrect, fail anyway
return FALSE;
}
$dn = config('server')->fetch($request->dn);
$o = new Entry;
if (! $dn && $o->getConnection()->getLdapConnection()->errNo() === 32)
abort(501,'Authentication succeeded, but the DN doesnt exist');
}
return $attempt;
}
/**
* We need to delete our encrypted username/password cookies
*
* @note The rest of this function is the same as a normal laravel logout as in AuthenticatesUsers::class
* @param Request $request
* @return \Illuminate\Contracts\Foundation\Application|JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed
*/
public function logout(Request $request)
{
$user = Auth::user();
$this->guard()->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
if ($response = $this->loggedOut($request)) {
Log::info(sprintf('Logged out [%s]',$user->dn));
return $response;
}
return $request->wantsJson()
? new JsonResponse([], 204)
: redirect('/');
}
/**
*
* Show our themed login page
*/
public function showLoginForm()
{
$login_note = '';
if (file_exists('login_note.txt'))
$login_note = file_get_contents('login_note.txt');
return view('architect::auth.login')->with('login_note',$login_note);
}
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function username()
{
return login_attr_name();
}
}

View File

@ -1,8 +0,0 @@
<?php
namespace App\Http\Controllers;
abstract class Controller extends \Illuminate\Routing\Controller
{
//
}

View File

@ -1,608 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use LdapRecord\Exceptions\InsufficientAccessException;
use LdapRecord\LdapRecordException;
use LdapRecord\Query\ObjectNotFoundException;
use Nette\NotImplementedException;
use App\Classes\LDAP\Attribute\{Factory,Password};
use App\Classes\LDAP\Import\LDIF as LDIFImport;
use App\Classes\LDAP\Export\LDIF as LDIFExport;
use App\Exceptions\Import\{GeneralException,VersionException};
use App\Exceptions\InvalidUsage;
use App\Http\Requests\{EntryRequest,EntryAddRequest,ImportRequest};
use App\Ldap\Entry;
class HomeController extends Controller
{
private const LOGKEY = 'CHc';
private const INTERNAL_POST = ['_auto_value','_key','_rdn','_rdn_new','_rdn_value','_step','_template','_token','_userpassword_hash'];
/**
* Create a new object in the LDAP server
*
* @param EntryAddRequest $request
* @return \Illuminate\View\View
* @throws InvalidUsage
*/
public function entry_add(EntryAddRequest $request): \Illuminate\View\View
{
if (! old('_step',$request->validated('_step')))
abort(404);
$key = $this->request_key($request,collect(old()));
$template = NULL;
$o = new Entry;
$o->setRDNBase($key['dn']);
foreach (collect(old())->except(self::INTERNAL_POST) as $old => $value)
$o->{$old} = array_filter($value);
if (old('_template',$request->validated('template'))) {
$template = $o->template(old('_template',$request->validated('template')));
$o->objectclass = [Entry::TAG_NOTAG=>$template->objectclasses->toArray()];
foreach ($o->getAvailableAttributes()
->filter(fn($item)=>$item->names_lc->intersect($template->attributes->keys()->map('strtolower'))->count())
->sortBy(fn($item)=>Arr::get($template->order,$item->name)) as $ao)
{
$o->{$ao->name} = [Entry::TAG_NOTAG=>''];
}
} elseif (count($x=collect(old('objectclass',$request->validated('objectclass')))->dot()->filter())) {
$o->objectclass = Arr::undot($x);
// Also add in our required attributes
foreach ($o->getAvailableAttributes()->filter(fn($item)=>$item->is_must) as $ao)
$o->{$ao->name} = [Entry::TAG_NOTAG=>''];
}
$step = $request->get('_step') ? $request->get('_step')+1 : old('_step');
return view('frame')
->with('subframe','create')
->with('o',$o)
->with('step',$step)
->with('template',$template)
->with('container',old('container',$key['dn']));
}
/**
* Render a new attribute view
*
* @param Request $request
* @param string $id
* @return \Illuminate\View\View
*/
public function entry_attr_add(Request $request,string $id): \Illuminate\View\View
{
$xx = new \stdClass;
$xx->index = 0;
$dn = $request->dn ? Crypt::decrypt($request->dn) : '';
$o = Factory::create(dn: $dn,attribute: $id,values: [],oc: $request->objectclasses);
$view = $request->noheader
? view(sprintf('components.attribute.widget.%s',$id))
->with('value',$request->value)
->with('loop',$xx)
: view('components.attribute-type')
->with('new',TRUE)
->with('edit',TRUE);
return $view
->with('o',$o)
->with('langtag',Entry::TAG_NOTAG)
->with('template',NULL)
->with('updated',FALSE);
}
public function entry_create(EntryAddRequest $request): \Illuminate\Http\RedirectResponse
{
$key = $this->request_key($request,collect(old()));
$dn = sprintf('%s=%s,%s',$request->get('_rdn'),$request->get('_rdn_value'),$key['dn']);
$o = new Entry;
$o->setDn($dn);
foreach ($request->except(self::INTERNAL_POST) as $key => $value)
$o->{$key} = array_filter($value);
// We need to process and encrypt the password
if ($request->userpassword)
$o->userpassword = $this->password(
$o->getObject('userpassword'),
$request->userpassword,
$request->get('_userpassword_hash'));
try {
$o->save();
} catch (InsufficientAccessException $e) {
$request->flash();
switch ($x=$e->getDetailedError()->getErrorCode()) {
case 50:
return Redirect::to('/')
->withInput()
->with('failed',sprintf('%s: %s (%s)',__('LDAP Server Error Code'),$x,__($e->getDetailedError()->getErrorMessage())));
default:
abort(599,$e->getDetailedError()->getErrorMessage());
}
// @todo when we create an entry, and it already exists, enable a redirect to it
} catch (LdapRecordException $e) {
return Redirect::back()
->withInput()
->with('failed',sprintf('%s: %s - %s: %s',
__('LDAP Server Error Code'),
$e->getDetailedError()->getErrorCode(),
__($e->getDetailedError()->getErrorMessage()),
$e->getDetailedError()->getDiagnosticMessage(),
));
}
// If there are an _auto_value attributes, we need to invalid those
foreach ($request->get('_auto_value',[]) as $attr => $value) {
Log::debug(sprintf('%s:Removing auto_value attr [%s]',self::LOGKEY,$attr));
Cache::delete($attr.':'.Session::id());
}
return Redirect::to('/')
->withFragment($o->getDNSecure());
}
public function entry_delete(Request $request): \Illuminate\Http\RedirectResponse
{
$dn = Crypt::decryptString($request->dn);
$o = config('server')->fetch($dn);
try {
$o->delete();
} catch (InsufficientAccessException $e) {
$request->flash();
switch ($x=$e->getDetailedError()->getErrorCode()) {
case 50:
return Redirect::to('/')
->withInput()
->with('failed',sprintf('%s: %s (%s)',__('LDAP Server Error Code'),$x,__($e->getDetailedError()->getErrorMessage())));
default:
abort(599,$e->getDetailedError()->getErrorMessage());
}
} catch (LdapRecordException $e) {
$request->flash();
switch ($x=$e->getDetailedError()->getErrorCode()) {
case 8:
return Redirect::to('/')
->withInput()
->with('failed',sprintf('%s: %s (%s)',__('LDAP Server Error Code'),$x,__($e->getDetailedError()->getErrorMessage())));
default:
abort(599,$e->getDetailedError()->getErrorMessage());
}
}
return Redirect::to('/')
->with('success',sprintf('%s: %s',__('Deleted'),$dn));
}
public function entry_export(Request $request,string $id): \Illuminate\View\View
{
$dn = Crypt::decryptString($id);
$result = Entry::query()
->setDn($dn)
->recursive()
->get();
return view('fragment.export')
->with('result',new LDIFExport($result));
}
/**
* Render an available list of objectclasses for an Entry
*
* @param Request $request
* @return Collection
*/
public function entry_objectclass_add(Request $request): Collection
{
$dn = $request->get('_key') ? Crypt::decryptString($request->dn) : '';
$oc = Factory::create($dn,'objectclass',$request->oc);
$ocs = $oc
->structural
->map(fn($item)=>$item->getParents())
->flatten()
->merge(
config('server')->schema('objectclasses')
->filter(fn($item)=>$item->isAuxiliary())
)
// Remove the original objectlcasses
->filter(fn($item)=>(! $oc->values->contains($item)))
->sortBy(fn($item)=>$item->name);
return $ocs->groupBy(fn($item)=>$item->isStructural())
->map(fn($item,$key) =>
[
'text' => sprintf('%s Object Class',$key ? 'Structural' : 'Auxiliary'),
'children' => $item->map(fn($item)=>['id'=>$item->name,'text'=>$item->name]),
]);
}
public function entry_password_check(Request $request): Collection
{
$dn = Crypt::decryptString($request->dn);
$o = config('server')->fetch($dn);
$password = $o->getObject('userpassword');
$result = collect();
foreach ($password->values->dot() as $key => $value) {
$hash = $password->hash($value);
$compare = Arr::get($request->password,$key);
//Log::debug(sprintf('comparing [%s] with [%s] type [%s]',$value,$compare,$hash::id()),['object'=>$hash]);
$result->push((($compare !== NULL) && $hash->compare($value,$compare)) ? 'OK' :'FAIL');
}
return $result;
}
/**
* Show a confirmation to update a DN
*
* @param EntryRequest $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
* @throws ObjectNotFoundException
*/
public function entry_pending_update(EntryRequest $request): \Illuminate\Http\RedirectResponse|\Illuminate\View\View
{
$dn = Crypt::decryptString($request->dn);
$o = config('server')->fetch($dn);
foreach ($request->except(['_token','dn','_userpassword_hash','userpassword']) as $key => $value)
$o->{$key} = array_filter($value,fn($item)=>! is_null($item));
// @todo Need to handle incoming attributes that were modified by MD5Updates Trait (eg: jpegphoto)
// We need to process and encrypt the password
if ($request->userpassword)
$o->userpassword = $this->password(
$o->getObject('userpassword'),
$request->userpassword,
$request->get('_userpassword_hash'));
if (! $o->getDirty())
return Redirect::back()
->withInput()
->with('note',__('No attributes changed'));
return view('update')
->with('dn',$dn)
->with('o',$o);
}
public function entry_rename(Request $request): \Illuminate\Http\RedirectResponse|\Illuminate\View\View
{
$from_dn = Crypt::decryptString($request->post('dn'));
Log::info(sprintf('%s:Renaming [%s] to [%s]',self::LOGKEY,$from_dn,$request->post('_rdn_new')));
$o = config('server')->fetch($from_dn);
if (! $o)
return Redirect::back()
->withInput()
->with('note',__('DN doesnt exist'));
try {
$o->rename($request->post('_rdn_new'));
} catch (\Exception $e) {
return Redirect::to('/')
->with('failed',$e->getMessage());
}
return Redirect::to('/')
->withInput(['_key'=>Crypt::encryptString('*dn|'.$o->getDN())])
->with('success',sprintf('%s: %s',__('Entry renamed'),$from_dn));
}
/**
* Update a DN entry
*
* @param EntryRequest $request
* @return \Illuminate\Http\RedirectResponse
* @throws ObjectNotFoundException
* @todo When removing an attribute value, from a multi-value attribute, we have a ghost record showing after the update
* @todo Need to check when removing a single attribute value, do we have a ghost as well? Might be because we are redirecting with input?
*/
public function entry_update(EntryRequest $request): \Illuminate\Http\RedirectResponse
{
$dn = Crypt::decryptString($request->dn);
$o = config('server')->fetch($dn);
foreach ($request->except(['_token','dn']) as $key => $value)
$o->{$key} = array_filter($value);
if (! $dirty=$o->getDirty())
return Redirect::back()
->withInput()
->with('note',__('No attributes changed'));
try {
$o->update($request->except(['_token','dn']));
} catch (InsufficientAccessException $e) {
$request->flash();
switch ($x=$e->getDetailedError()->getErrorCode()) {
case 50:
return Redirect::to('/')
->withInput()
->with('failed',sprintf('%s: %s (%s)',__('LDAP Server Error Code'),$x,__($e->getDetailedError()->getErrorMessage())));
default:
abort(599,$e->getDetailedError()->getErrorMessage());
}
} catch (LdapRecordException $e) {
return Redirect::to('/')
->withInput()
->with('failed',sprintf('%s: %s - %s: %s',
__('LDAP Server Error Code'),
$e->getDetailedError()->getErrorCode(),
__($e->getDetailedError()->getErrorMessage()),
$e->getDetailedError()->getDiagnosticMessage(),
));
}
return Redirect::to('/')
->withInput()
->with('updated',collect($dirty)
->map(fn($item,$key)=>$o->getObject(collect(explode(';',$key))->first()))
->values()
->unique());
}
/**
* Render a frame, normally as a result of an AJAX call
* This will render the right frame.
*
* @param Request $request
* @param Collection|null $old
* @return \Illuminate\View\View
* @throws InvalidUsage
*/
public function frame(Request $request,?Collection $old=NULL): \Illuminate\View\View
{
// If our index was not render from a root url, then redirect to it
if (($request->root().'/' !== url()->previous()) && $request->method() === 'POST')
abort(409);
$key = $this->request_key($request,$old);
$view = $old
? view('frame')->with('subframe',$key['cmd'])
: view('frames.'.$key['cmd']);
// If we are rendering a DN, rebuild our object
if ($key['cmd'] === 'create') {
$o = new Entry;
$o->setRDNBase($key['dn']);
} elseif ($key['dn']) {
// @todo Need to handle if DN is null, for example if the user's session expired and the ACLs dont let them retrieve $key['dn']
$o = config('server')->fetch($key['dn']);
foreach (collect(old())->except(array_merge(self::INTERNAL_POST,['dn'])) as $attr => $value)
$o->{$attr} = $value;
}
return match ($key['cmd']) {
'create' => $view
->with('container',old('container',$key['dn']))
->with('o',$o)
->with('template',NULL)
->with('step',1),
'dn' => $view
->with('dn',$key['dn'])
->with('o',$o)
->with('page_actions',collect([
'copy'=>FALSE,
'create'=>($x=($o->getObjects()->except('entryuuid')->count() > 0)),
'delete'=>(! is_null($xx=$o->getObject('hassubordinates')->value)) && ($xx === 'FALSE'),
'edit'=>$x,
'export'=>$x,
])),
'import' => $view,
default => abort(404),
};
}
/**
* This is the main page render function
*/
public function home(Request $request): \Illuminate\View\View
{
// Did we come here as a result of a redirect
return count(old())
? $this->frame($request,collect(old()))
: view('home');
}
/**
* Process the incoming LDIF file or LDIF text
*
* @param ImportRequest $request
* @param string $type
* @return \Illuminate\View\View
* @throws GeneralException
* @throws VersionException
*/
public function import(ImportRequest $request,string $type): \Illuminate\View\View
{
switch ($type) {
case 'ldif':
$import = new LDIFImport($x=($request->text ?: $request->file->get()));
Log::debug('Processing LDIF import',['data'=>$x,'import'=>$import]);
break;
default:
abort(404,'Unknown import type: '.$type);
}
try {
$result = $import->process();
} catch (NotImplementedException $e) {
abort(555,$e->getMessage());
} catch (\Exception $e) {
abort(598,$e->getMessage());
}
return view('frame')
->with('subframe','import_result')
->with('result',$result)
->with('ldif',htmlspecialchars($x));
}
private function password(Password $po,array $values,array $hash): array
{
// We need to process and encrypt the password
$passwords = [];
foreach (Arr::dot($values) as $dotkey => $value) {
// If the password is still the MD5 of the old password, then it hasnt changed
if (($old=Arr::get($po,$dotkey)) && ($value === md5($old))) {
$passwords[$dotkey] = $value;
continue;
}
if ($value) {
$type = Arr::get($hash,$dotkey);
$passwords[$dotkey] = Password::hash_id($type)
->encode($value);
}
}
return Arr::undot($passwords);
}
/**
* For any incoming request, work out the command and DN involved
*
* @param Request $request
* @param Collection|null $old
* @return array
*/
private function request_key(Request $request,?Collection $old=NULL): array
{
// Setup
$cmd = NULL;
$dn = NULL;
$key = ($x=$request->get('_key',old('_key')))
? Crypt::decryptString($x)
: NULL;
// Determine if our key has a command
if (str_contains($key,'|')) {
$m = [];
if (preg_match('/\*([a-z_]+)\|(.+)$/',$key,$m)) {
$cmd = $m[1];
$dn = ($m[2] !== '_NOP') ? $m[2] : NULL;
}
} elseif ($x=old('dn',$request->get('_key'))) {
$cmd = 'dn';
$dn = Crypt::decryptString($x);
}
return ['cmd'=>$cmd,'dn'=>$dn];
}
/**
* Show the Schema Viewer
*
* @note Our route will validate that types are valid.
* @param Request $request
* @return \Illuminate\View\View
* @throws InvalidUsage
*/
public function schema_frame(Request $request): \Illuminate\View\View
{
// If an invalid key, we'll 404
if ($request->type && $request->get('_key') && (! config('server')->schema($request->type)->has($request->get('_key'))))
abort(404);
return view('frames.schema')
->with('type',$request->type)
->with('key',$request->get('_key'));
}
/**
* Sort the attributes
*
* @param Collection $attrs
* @return Collection
*/
private function sortAttrs(Collection $attrs): Collection
{
return $attrs->sortKeys();
}
/**
* Return the image for the logged in user or anonymous
*
* @param Request $request
* @return \Illuminate\Http\Response
*/
public function user_image(Request $request): \Illuminate\Http\Response
{
$image = NULL;
$content = NULL;
if (Auth::check()) {
$image = Arr::get(Auth::user()->getAttribute('jpegphoto'),0);
$content = 'image/jpeg';
}
if (! $image) {
$image = File::get('../resources/images/user-secret-solid.svg');
$content = 'image/svg+xml';
}
return response($image)
->header('Content-Type',$content);
}
}

View File

@ -1,59 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use App\Ldap\Entry;
class SearchController extends Controller
{
public function search(Request $request): Collection
{
$so = config('server');
// We are searching for a value
if (strpos($request->term,'=')) {
list($attr,$value) = explode('=',$request->term,2);
$value = trim($value);
$result = collect();
foreach ($so->baseDNs(FALSE) as $base) {
$search = (new Entry)
->in($base);
$search = ($x=Str::startsWith($value,'*'))
? $search->whereEndsWith($attr,substr($value,1))
: $search->whereStartsWith($attr,$value);
$result = $result->merge($search->get());
}
return $result
->map(fn($item)=>[
'name'=>$item->getDN(),
'value'=>Crypt::encryptString($item->getDN()),
'category'=>sprintf('%s: [%s=%s%s]',__('Result'),$attr,$value,($x ? '' : '*'))
]);
// We are searching for an attribute
} else {
$attrs = $so
->schema('attributetypes')
->sortBy('name')
->filter(fn($item)=>Str::contains($item->name_lc,strtolower($request->term)));
return $attrs
->map(fn($item)=>[
'name'=>$item->name,
'value'=>'',
'category'=>__('Select attribute...')
])
->values();
}
}
}

View File

@ -1,46 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
class AcceptLanguage
{
private const LOGKEY = 'MAL';
public function handle(Request $request,Closure $next): mixed
{
if ($locale=$this->parseHttpLocale($request)) {
Log::debug(sprintf('%s:Accept Language changed from [%s] to [%s] from Browser (%s)',self::LOGKEY,app()->getLocale(),$locale,$request->header('Accept-Language')));
app()->setLocale($locale);
}
return $next($request);
}
private function parseHttpLocale(Request $request): string
{
$list = explode(',',$request->server('HTTP_ACCEPT_LANGUAGE',''));
$locales = Collection::make($list)
->map(function ($locale) {
$parts = explode(';',$locale);
$mapping = [];
$mapping['locale'] = trim($parts[0]);
$mapping['factor'] = isset($parts[1])
? Arr::get(explode('=',$parts[1]),1)
: 1;
return $mapping;
})
->sortByDesc(fn($locale)=>$locale['factor']);
return Arr::get($locales->first(),'locale');
}
}

View File

@ -1,28 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class AllowAnonymous
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request,Closure $next): mixed
{
if ((! config('pla.allow_guest',FALSE))
&& ($request->path() !== 'login')
&& ((! Session::has('username_encrypt')) || (! Session::has('password_encrypt'))))
return redirect()
->to('/login');
return $next($request);
}
}

View File

@ -1,62 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
class CheckUpdate
{
private const UPDATE_SERVER = 'https://version.phpldapadmin.org';
private const UPDATE_TIME = 60*60*6;
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next): mixed
{
Config::set('update_available',Cache::get('upstream_version'));
return $next($request);
}
/**
* Handle tasks after the response has been sent to the browser.
*
* @return void
*/
public function terminate(): void
{
Cache::remember('upstream_version',self::UPDATE_TIME,function() {
// CURL call to URL to see if there is a new version
Log::debug(sprintf('CU_:Checking for updates for [%s]',config('app.version')));
$client = new Client;
try {
$response = $client->request('POST',sprintf('%s/%s',self::UPDATE_SERVER,strtolower(config('app.version'))));
if ($response->getStatusCode() === 200) {
$result = json_decode($response->getBody());
Log::debug(sprintf('CU_:- Update server returned...'),['update'=>$result]);
return $result;
}
} catch (\Exception $e) {
Log::debug(sprintf('CU_:- Exception connecting to update server'),['e'=>get_class($e)]);
}
return NULL;
});
}
}

View File

@ -1,51 +0,0 @@
<?php
namespace App\Http\Middleware;
use App\Classes\LDAP\Server;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use LdapRecord\Container;
use App\Ldap\Guard;
class SwapinAuthUser
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
* @throws \LdapRecord\Configuration\ConfigurationException
*/
public function handle(Request $request,Closure $next): mixed
{
$key = config('ldap.default');
if (! array_key_exists($key,config('ldap.connections')))
abort(599,sprintf('LDAP default server [%s] configuration doesnt exist?',$key));
if (($request->path() !== 'logout') && Session::has('username_encrypt') && Session::has('password_encrypt')) {
Config::set('ldap.connections.'.$key.'.username',Crypt::decryptString(Session::get('username_encrypt')));
Config::set('ldap.connections.'.$key.'.password',Crypt::decryptString(Session::get('password_encrypt')));
Log::debug('Swapping out configured LDAP credentials with the user\'s session.',['key'=>$key]);
}
// We need to override our Connection object so that we can store and retrieve the logged in user and swap out the credentials to use them.
$c = Container::getInstance()
->getConnection($key);
$c->setConfiguration(config('ldap.connections.'.$key));
$c->setGuardResolver(fn()=>new Guard($c->getLdapConnection(),$c->getConfiguration()));
Config::set('server',new Server);
return $next($request);
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use App\Ldap\User;
/**
* This sets up our application session with any required values, ultimately for cache optimisation reasons
*/
class ViewVariables
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request,Closure $next): mixed
{
view()->share('server',Config::get('server'));
view()->share('user',auth()->user() ?: new User);
return $next($request);
}
}

View File

@ -1,140 +0,0 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use App\Rules\{DNExists,HasStructuralObjectClass};
class EntryAddRequest extends FormRequest
{
private const LOGKEY = 'EAR';
/**
* Get the error messages for the defined validation rules.
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'_rdn' => __('RDN is required.'),
'_rdn_value' => __('RDN value is required.'),
];
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
public function rules(): array
{
if (request()->method() === 'GET')
return [];
$r = request() ?: collect();
$rk = array_keys($r->all());
return config('server')
->schema('attributetypes')
->filter(fn($item)=>$item->names_lc->intersect($rk)->count())
->transform(function($item) use ($rk) {
// Set the attributetype name
if (($x=$item->names_lc->intersect($rk))->count() === 1)
$item->setName($x->pop());
return $item;
})
->map(fn($item)=>$item->validation($r->get('objectclass',[])))
->filter()
->flatMap(fn($item)=>$item)
->merge([
'_key' => [
'required',
new DNExists,
function (string $attribute,mixed $value,\Closure $fail) {
$cmd = Crypt::decryptString($value);
// Sometimes our key has a command, so we'll ignore it
if (str_starts_with($cmd,'*') && ($x=strpos($cmd,'|')))
$cmd = substr($cmd,1,$x-1);
if ($cmd !== 'create') {
$fail(sprintf('Invalid command: %s',$cmd));
}
},
],
'_rdn' => 'required_if:_step,2|string|min:1',
'_rdn_value' => 'required_if:_step,2|string|min:1',
'_step' => 'int|min:1|max:2',
'objectclass'=>[
'required',
'array',
'min:1',
'max:1',
],
'objectclass._null_' => [
function (string $attribute,mixed $value,\Closure $fail) {
$oc = collect($value)->dot()->filter();
// If this is step 1 and there is no objectclass, and no template, then fail
if ((! $oc->count())
&& (request()->post('_step') == 1)
&& (! request()->post('template')))
{
$fail(__('Select an objectclass or a template'));
}
// Cant have both an objectclass and a template
if (request()->post('template') && $oc->count())
$fail(__('You cannot select a template and an objectclass'));
},
'array',
'min:1',
new HasStructuralObjectClass,
],
'template' => [
function (string $attribute,mixed $value,\Closure $fail) {
$oc = collect(request()->post('objectclass'))->dot()->filter();
// If this is step 1 and there is no objectclass, and no template, then fail
if ((! collect($value)->filter()->count())
&& (request()->post('_step') == 1)
&& (! $oc->count()))
{
$fail(__('Select an objectclass or a template'));
}
// Cant have both an objectclass and a template
if ($oc->count() && strlen($value))
$fail(__('You cannot select a template and an objectclass'));
},
],
'_auto_value' => 'nullable|array|min:1',
'_auto_value.*' => [
'nullable',
function (string $attribute,mixed $value,\Closure $fail) {
$attr = preg_replace('/^_auto_value\./','',$attribute);
// If the value has been overritten, then our auto_value is invalid
if (! collect(request()->get($attr))->dot()->contains($value))
return;
$cache = Cache::get($attr.':'.Session::id());
Log::debug(sprintf('%s:Autovalue for Attribute [%s] in Session [%s] Retrieved [%d](%d)',self::LOGKEY,$attr,Session::id(),$cache,$value));
if ($cache !== (int)$value)
$fail(__('Lock expired, please re-submit.'));
}
]
])
->toArray();
}
}

View File

@ -1,36 +0,0 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EntryRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
public function rules(): array
{
$r = request() ?: collect();
$rk = array_keys($r->all());
return config('server')
->schema('attributetypes')
->filter(fn($item)=>$item->names_lc->intersect($rk)->count())
->transform(function($item) use ($rk) {
// Set the attributetype name
if (($x=$item->names_lc->intersect($rk))->count() === 1)
$item->setName($x->pop());
return $item;
})
->map(fn($item)=>$item->validation($r->get('objectclass',[])))
->filter()
->flatMap(fn($item)=>$item)
->toArray();
}
}

View File

@ -1,16 +0,0 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ImportRequest extends FormRequest
{
public function rules(): array
{
return [
'file' => 'nullable|extensions:ldif|required_without:text',
'text'=> 'nullable|prohibits:file|string|min:16',
];
}
}

View File

@ -1,592 +0,0 @@
<?php
namespace App\Ldap;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use LdapRecord\Support\Arr;
use LdapRecord\Models\Model;
use App\Classes\Template;
use App\Classes\LDAP\Attribute;
use App\Classes\LDAP\Attribute\Factory;
use App\Classes\LDAP\Export\LDIF;
use App\Exceptions\Import\AttributeException;
use App\Exceptions\InvalidUsage;
/**
* An Entry in an LDAP server
*
* @notes https://ldap.com/ldap-dns-and-rdns
*/
class Entry extends Model
{
private const TAG_CHARS = 'a-zA-Z0-9-';
public const LANG_TAG_PREFIX = 'lang-';
public const TAG_CHARS_LANG = self::LANG_TAG_PREFIX.'['.self::TAG_CHARS.']+';
public const TAG_NOTAG = '_null_';
// Our Attribute objects
private Collection $objects;
// Templates that apply to this entry
private(set) Collection $templates;
// For new entries, this is the container that this entry will be stored in
private string $rdnbase;
/* OVERRIDES */
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->objects = collect();
// Load any templates
$this->templates = Cache::remember('templates'.Session::id(),config('ldap.cache.time'),function() {
$template_dir = Storage::disk(config('pla.template.dir'));
$templates = collect();
foreach (array_filter($template_dir->files('.',TRUE),fn($item)=>Str::endsWith($item,'.json')) as $file) {
if (config('pla.template.exclude_system',FALSE) && Str::doesntContain($file,'/'))
continue;
$to = new Template($file);
if ($to->invalid) {
Log::debug(sprintf('Template [%s] is not valid (%s) - ignoring',$file,$to->reason));
} else {
$templates->put($file,new Template($file));
}
}
return $templates;
});
}
public function discardChanges(): static
{
parent::discardChanges();
// If we are discharging changes, we need to reset our $objects;
$this->objects = $this->getAttributesAsObjects();
return $this;
}
/**
* This function overrides getAttributes to use our collection of Attribute objects instead of the models attributes.
*
* This returns an array that should be consistent with $this->attributes
*
* @return array
*/
public function getAttributes(): array
{
return $this->objects
->flatMap(fn($item)=>
($item->no_attr_tags)
? [strtolower($item->name)=>$item->values]
: $item->values
->flatMap(fn($v,$k)=>[strtolower($item->name.($k !== self::TAG_NOTAG ? ';'.$k : ''))=>$v]))
->toArray();
}
/**
* Determine if the new and old values for a given key are equivalent.
*/
protected function originalIsEquivalent(string $key): bool
{
$key = $this->normalizeAttributeKey($key);
list($attribute,$tag) = $this->keytag($key);
return ((! array_key_exists($key,$this->original)) && (! $this->objects->has($attribute)))
|| (! $this->getObject($attribute)->isDirty());
}
/**
* As attribute values are updated, or new ones created, we need to mirror that
* into our $objects. This is called when we $o->key = $value
*
* This function should update $this->attributes and correctly reflect changes in $this->objects
*
* @param string $key
* @param mixed $value
* @return $this
*/
public function setAttribute(string $key,mixed $value): static
{
foreach ($value as $k => $v)
parent::setAttribute($key.($k !== self::TAG_NOTAG ? ';'.$k : ''),$v);
$key = $this->normalizeAttributeKey($key);
list($attribute,$tags) = $this->keytag($key);
$o = $this->objects->get($attribute) ?: Factory::create($this->dn ?: '',$attribute,[],Arr::get($this->attributes,'objectclass',[]));
$o->values = collect($value);
$this->objects->put($key,$o);
return $this;
}
/**
* We'll shadow $this->attributes to $this->objects - a collection of Attribute objects
*
* Using the objects, it'll make it easier to work with attribute values
*
* @param array $attributes
* @return $this
*/
public function setRawAttributes(array $attributes = []): static
{
parent::setRawAttributes($attributes);
// We only set our objects on DN entries (otherwise we might get into a recursion loop if this is the schema DN)
if ($this->dn && (! in_array($this->dn,Arr::get($this->attributes,'subschemasubentry',[])))) {
$this->objects = $this->getAttributesAsObjects();
} else {
$this->objects = collect();
}
// Filter out our templates specific for this entry
if ($this->dn && (! in_array(strtolower($this->dn),['cn=subschema']))) {
$this->templates = $this->templates
->filter(fn($item)=>$item->enabled
&& (! $item->objectclasses
->map('strtolower')
->diff(array_map('strtolower',Arr::get($this->attributes,'objectclass')))
->count()))
->sortBy(fn($item)=>$item->title);
}
return $this;
}
/* ATTRIBUTES */
/**
* Return a key to use for sorting
*
* @return string
*/
public function getSortKeyAttribute(): string
{
return collect(explode(',',$this->getDn()))->reverse()->join(',');
}
/* METHODS */
/**
* Add an attribute to this entry, if the attribute already exists, then we'll add the value to the existing item.
*
* This is primarily used by LDIF imports, where attributes have multiple entries over multiple lines
*
* @param string $key
* @param mixed $value
* @return void
* @throws AttributeException
* @note Attributes added this way dont have objectclass information, and the Model::attributes are not populated
*/
public function addAttributeItem(string $key,mixed $value): void
{
// While $value is mixed, it can only be a string
if (! is_string($value))
throw new \Exception('value should be a string');
$key = $this->normalizeAttributeKey(strtolower($key));
// If the attribute name has tags
list($attribute,$tag) = $this->keytag($key);
if (config('server')->get_attr_id($attribute) === FALSE)
throw new AttributeException(sprintf('Schema doesnt have attribute [%s]',$attribute));
$o = $this->objects->get($attribute) ?: Attribute\Factory::create($this->dn ?: '',$attribute,[]);
$o->addValue($tag,[$value]);
$this->objects->put($key,$o);
}
/**
* Export this record
*
* @param string $method
* @param string $scope
* @return string
* @throws \Exception
*/
public function export(string $method,string $scope): string
{
// @todo To implement
switch ($scope) {
case 'base':
case 'one':
case 'sub':
break;
default:
throw new \Exception('Export scope unknown:'.$scope);
}
switch ($method) {
case 'ldif':
return new LDIF(collect($this));
default:
throw new \Exception('Export method not implemented:'.$method);
}
}
/**
* Convert all our attribute values into an array of Objects
*
* @return Collection
*/
private function getAttributesAsObjects(): Collection
{
$result = collect();
$entry_oc = Arr::get($this->attributes,'objectclass',[]);
foreach ($this->attributes as $attrtag => $values) {
list($attribute,$tags) = $this->keytag($attrtag);
$orig = Arr::get($this->original,$attrtag,[]);
// If the attribute doesnt exist we'll create it
$o = Arr::get(
$result,
$attribute,
Factory::create(
$this->dn,
$attribute,
[$tags=>$orig],
$entry_oc,
));
$o->addValue($tags,$values);
$o->addValueOld($tags,Arr::get($this->original,$attrtag));
$result->put($attribute,$o);
}
$sort = collect(config('pla.attr_display_order',[]))->map(fn($item)=>strtolower($item));
// Order the attributes
return $result->sortBy([function(Attribute $a,Attribute $b) use ($sort): int {
if ($a === $b)
return 0;
// Check if $a/$b are in the configuration to be sorted first, if so get it's key
$a_key = $sort->search($a->name_lc);
$b_key = $sort->search($b->name_lc);
// If the keys were not in the sort list, set the key to be the count of elements (ie: so it is last to be sorted)
if ($a_key === FALSE)
$a_key = $sort->count()+1;
if ($b_key === FALSE)
$b_key = $sort->count()+1;
// Case where neither $a, nor $b are in pla.attr_display_order, $a_key = $b_key = one greater than num elements.
// So we sort them alphabetically
if ($a_key === $b_key)
return strcasecmp($a->name,$b->name);
// Case where at least one attribute or its friendly name is in $attrs_display_order
// return -1 if $a before $b in $attrs_display_order
return ($a_key < $b_key) ? -1 : 1;
}]);
}
/**
* Return a list of available attributes - as per the objectClass entry of the record
*
* @return Collection
*/
public function getAvailableAttributes(): Collection
{
$result = collect();
foreach (($this->getObject('objectclass')?->values ?: []) as $oc)
$result = $result->merge(config('server')->schema('objectclasses',$oc)->all_attributes);
return $result;
}
/**
* Return a secure version of the DN
* @param string $cmd
* @return string
*/
public function getDNSecure(string $cmd=''): string
{
return Crypt::encryptString(($cmd ? sprintf('*%s|',$cmd) : '').$this->getDn());
}
/**
* Return a list of LDAP internal attributes
*
* @return Collection
*/
public function getInternalAttributes(): Collection
{
return $this->objects
->filter(fn($item)=>$item->is_internal);
}
/**
* Identify the language tags (RFC 3866) used by this entry
*
* @return Collection
*/
public function getLangTags(): Collection
{
return $this->getObjects()
->map(fn($item)=>$item->langtags);
}
/**
* Of all the items with lang tags, which ones have more than 1 lang tag
*
* @return Collection
*/
public function getLangMultiTags(): Collection
{
return $this->getLangTags()
->map(fn($item)=>$item->values()
->map(fn($item)=>explode(';',$item))
->filter(fn($item)=>count($item) > 1))
->filter(fn($item)=>$item->count());
}
/**
* Get an attribute as an object
*
* @param string $key
* @return Attribute|null
*/
public function getObject(string $key): Attribute|null
{
return match ($key) {
'rdn' => $this->getRDNObject(),
default => $this->objects
->get($this->normalizeAttributeKey($key))
};
}
public function getObjects(): Collection
{
// In case we havent built our objects yet (because they werent available while determining the schema DN)
if ((! $this->objects->count()) && $this->attributes)
$this->objects = $this->getAttributesAsObjects();
return $this->objects;
}
/**
* Find other attribute tags used by this entry
*
* @return Collection
*/
public function getOtherTags(): Collection
{
return $this->getObjects()
->filter(fn($item)=>! $item->no_attr_tags)
->map(fn($item)=>$item
->values
->keys()
->filter(fn($item)=>
$item && collect(explode(';',$item))->filter(
fn($item)=>
(! preg_match(sprintf('/^%s$/',self::TAG_NOTAG),$item))
&& (! preg_match(sprintf('/^%s$/',self::TAG_CHARS_LANG),$item))
)
->count())
)
->filter(fn($item)=>$item->count());
}
/**
* Return a list of attributes without any values
*
* @return Collection
*/
public function getMissingAttributes(): Collection
{
return $this->getAvailableAttributes()
->filter(fn($a)=>(! $this->getVisibleAttributes()->contains(fn($b)=>($a->name === $b->name))));
}
private function getRDNObject(): Attribute\RDN
{
$o = new Attribute\RDN('','dn',['']);
// @todo for an existing object, rdnbase would be null, so dynamically get it from the DN.
$o->setBase($this->rdnbase);
$o->setAttributes($this->getAvailableAttributes()->filter(fn($item)=>$item->is_must));
return $o;
}
/**
* Return this list of user attributes
*
* @param string $tag If null return all tags
* @return Collection
*/
public function getVisibleAttributes(string $tag=''): Collection
{
static $cache = [];
if (! Arr::get($cache,$tag ?: '_all_')) {
$ot = $this->getOtherTags();
$cache[$tag ?: '_all_'] = $this->objects
->filter(fn($item)=>(! $item->is_internal) && ((! $item->no_attr_tags) || (! $tag) || ($tag === Entry::TAG_NOTAG)))
->filter(fn($item)=>(! $tag) || $ot->has($item->name_lc) || count($item->tagValues($tag)) > 0);
}
return $cache[$tag ?: '_all_'];
}
public function hasAttribute(int|string $key): bool
{
return $this->objects
->has($key);
}
/**
* Did this query generate a size limit exception
*
* @return bool
* @throws \LdapRecord\ContainerException
*/
public function hasMore(): bool
{
return $this->getConnectionContainer()
->getConnection()
->getLdapConnection()
->getDetailedError()
?->getErrorCode() === 4;
}
/**
* Return an icon for a DN based on objectClass
*
* @return string
*/
public function icon(): string
{
$objectclasses = ($x=$this->getObject('objectclass'))
? $x->tagValues()
->map(fn($item)=>strtolower($item))
: collect();
// Return icon based upon objectClass value
if ($objectclasses->intersect([
'account',
'inetorgperson',
'organizationalperson',
'person',
'posixaccount',
])->count())
return 'fas fa-user';
elseif ($objectclasses->contains('organization'))
return 'fas fa-university';
elseif ($objectclasses->contains('organizationalunit'))
return 'fas fa-object-group';
elseif ($objectclasses->intersect([
'posixgroup',
'groupofnames',
'groupofuniquenames',
'group',
])->count())
return 'fas fa-users';
elseif ($objectclasses->intersect([
'dcobject',
'domainrelatedobject',
'domain',
'builtindomain',
])->count())
return 'fas fa-network-wired';
elseif ($objectclasses->contains('alias'))
return 'fas fa-theater-masks';
elseif ($objectclasses->contains('country'))
return sprintf('flag %s',strtolower(Arr::get($this->c ?: [],0)));
elseif ($objectclasses->contains('device'))
return 'fas fa-mobile-alt';
elseif ($objectclasses->contains('document'))
return 'fas fa-file-alt';
elseif ($objectclasses->contains('iphost'))
return 'fas fa-wifi';
elseif ($objectclasses->contains('room'))
return 'fas fa-door-open';
elseif ($objectclasses->contains('server'))
return 'fas fa-server';
elseif ($objectclasses->contains('openldaprootdse'))
return 'fas fa-info';
// Default
return 'fa-fw fas fa-cog';
}
/**
* Given an LDAP attribute, this will return the attribute name and the tag
* eg: description;lang-cn will return [description,lang-cn]
*
* @param string $key
* @return array
*/
private function keytag(string $key): array
{
$matches = [];
if (preg_match(sprintf('/^([%s]+);+([%s;]+)/',self::TAG_CHARS,self::TAG_CHARS),$key,$matches)) {
$attribute = $matches[1];
$tags = $matches[2];
} else {
$attribute = $key;
$tags = self::TAG_NOTAG;
}
return [$attribute,$tags];
}
public function setRDNBase(string $bdn): void
{
if ($this->exists)
throw new InvalidUsage('Cannot set RDN base on existing entries');
$this->rdnbase = $bdn;
$this->templates = $this->templates
->filter(fn($item)=>(! $item->regexp) || preg_match($item->regexp,$bdn));
}
public function template(string $item): Template|Null
{
return Arr::get($this->templates,$item);
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace App\Ldap;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use LdapRecord\Auth\Guard as GuardBase;
class Guard extends GuardBase
{
public function attempt(string $username, string $password, bool $stayBound = false): bool
{
Log::info(sprintf('Attempting login for [%s] with password [%s]',$username,($password ? str_repeat('*',16) : str_repeat('?',16))));
if ($result = parent::attempt($username,$password,$stayBound)) {
// Store user details so we can swap in auth details in SwapinAuthUser
session()->put('username_encrypt',Crypt::encryptString($username));
session()->put('password_encrypt',Crypt::encryptString($password));
}
return $result;
}
}

View File

@ -1,79 +0,0 @@
<?php
namespace App\Ldap;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Str;
use LdapRecord\Laravel\Events\Auth\DiscoveredWithCredentials;
use LdapRecord\Laravel\LdapUserRepository as LdapUserRepositoryBase;
use LdapRecord\Models\Model;
use App\Classes\LDAP\Server;
class LdapUserRepository extends LdapUserRepositoryBase
{
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
*
* @return Model|null
* @throws \LdapRecord\Query\ObjectNotFoundException
*/
public function findByCredentials(array $credentials = []): ?Model
{
if (empty($credentials)) {
return NULL;
}
// For DN based logins
if (! empty($credentials['dn']))
return $this->query()->find($credentials['dn']);
// Look for a user using all our baseDNs
foreach (Server::baseDNs(FALSE) as $base) {
$query = $this->query()->setBaseDn($base);
foreach ($credentials as $key => $value) {
if (Str::contains($key, $this->bypassCredentialKeys)) {
continue;
}
if (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
if (! is_null($user = $query->first())) {
event(new DiscoveredWithCredentials($user));
return $user;
}
}
return NULL;
}
/**
* Get a user by their object GUID.
*
* @param string $guid
*
* @return Model|null
* @throws \LdapRecord\Query\ObjectNotFoundException
*/
public function findByGuid($guid): ?Model
{
// Look for a user using all our baseDNs
foreach (Server::baseDNs(FALSE) as $base) {
$user = $this->query()->setBaseDn($base)->findByGuid($guid);
if ($user)
return $user;
}
return NULL;
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Ldap\Rules;
use Illuminate\Database\Eloquent\Model as Eloquent;
use LdapRecord\Laravel\Auth\Rule;
use LdapRecord\Models\Model as LdapRecord;
/**
* User must have this objectClass to login
*
* This is overridden by LDAP_LOGIN_OBJECTCLASS
* @see User::$objectClasses
*/
class LoginObjectclassRule implements Rule
{
public function passes(LdapRecord $user,?Eloquent $model=NULL): bool
{
if ($x=config('pla.login.objectclass')) {
return count(array_intersect(
array_map('strtolower',$user?->objectclass ?: []),
array_map('strtolower',$x)
));
// Otherwise allow the user to login
} else {
return TRUE;
}
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace App\Ldap;
use Laravel\Sanctum\HasApiTokens;
use LdapRecord\Models\OpenLDAP\User as Model;
use App\Ldap\Rules\LoginObjectclassRule;
class User extends Model
{
use HasApiTokens;
/**
* The object classes of the LDAP model.
*
* @note We set this to an empty array so that any objectclass can login
* @see LoginObjectclassRule::class
*/
public static array $objectClasses = [
];
/* METHODS */
public function getDn(): string
{
return $this->exists ? parent::getDn() : 'Anonymous';
}
}

View File

@ -1,32 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use LdapRecord\Configuration\DomainConfiguration;
use LdapRecord\Laravel\LdapRecord;
use App\Ldap\LdapUserRepository;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// Add a new option available to be set in the configuration:
DomainConfiguration::extend('name', $default = null);
// Use our LdapUserRepository to support multiple baseDN querying
LdapRecord::locateUsersUsing(LdapUserRepository::class);
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
$this->loadViewsFrom(__DIR__.'/../../resources/themes/architect/views/','architect');
}
}

View File

@ -1,27 +0,0 @@
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Crypt;
class DNExists implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute,mixed $value,Closure $fail): void
{
$dn = Crypt::decryptString($value);
// Sometimes our key has a command, so we'll ignore it
if (str_starts_with($dn,'*') && ($x=strpos($dn,'|')))
$dn = substr($dn,$x+1);
if (! config('server')->fetch($dn))
$fail(sprintf('The DN %s doesnt exist.',$dn));
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class HasStructuralObjectClass implements ValidationRule
{
// Required for artisan optimize
public static function __set_state(array $array): self
{
return new self;
}
/**
* Run the validation rule.
*
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute,mixed $value,Closure $fail): void
{
foreach (collect($value)->dot() as $item)
if ($item && config('server')->schema('objectclasses',$item)->isStructural())
return;
if (collect($value)->dot()->filter()->count())
$fail(__('There isnt a Structural Objectclass.'));
}
}

View File

@ -1,21 +0,0 @@
<?php
/**
* Determine if a value has changed by comparing its MD5 value
*/
namespace App\Traits;
use Illuminate\Support\Arr;
trait MD5Updates
{
public function isDirty(): bool
{
foreach ($this->values_old->dot()->keys()->merge($this->values->dot()->keys())->unique() as $dotkey)
if ((Arr::get($this->values_old->dot(),$dotkey) !== Arr::get($this->values->dot(),$dotkey))
&& (md5(Arr::get($this->values_old->dot(),$dotkey)) !== Arr::get($this->values->dot(),$dotkey)))
return TRUE;
return FALSE;
}
}

View File

@ -1,50 +0,0 @@
<?php
namespace App\View\Components;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
use App\Classes\LDAP\Attribute as LDAPAttribute;
use App\Classes\Template;
class Attribute extends Component
{
public ?LDAPAttribute $o;
public bool $edit;
public bool $new;
public bool $old;
public bool $updated;
public ?Template $template;
/**
* Create a new component instance.
*/
public function __construct(?LDAPAttribute $o,bool $edit=FALSE,bool $old=FALSE,bool $new=FALSE,bool $updated=FALSE,?Template $template=NULL)
{
$this->o = $o;
$this->edit = $edit;
$this->old = $old;
$this->new = $new;
$this->updated = $updated;
$this->template = $template;
}
/**
* Get the view / contents that represent the component.
*
* @return View|string
*/
public function render(): View|string
{
return $this->o
? $this->o
->render(
edit: $this->edit,
old: $this->old,
new: $this->new,
updated: $this->updated,
template: $this->template)
: __('Unknown');
}
}

Some files were not shown because too many files have changed in this diff Show More