summaryrefslogtreecommitdiffstats
path: root/lib/password_policy.php
blob: 38cac162871d507427468c6b9e4771e570bca574 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
<?php
/*
 +--------------------------------------------------------------------------+
 | This file is part of the Kolab Web Admin Panel                           |
 |                                                                          |
 | Copyright (C) 2011-2015, Kolab Systems AG                                |
 |                                                                          |
 | This program is free software: you can redistribute it and/or modify     |
 | it under the terms of the GNU Affero General Public License as published |
 | by the Free Software Foundation, either version 3 of the License, or     |
 | (at your option) any later version.                                      |
 |                                                                          |
 | This program is distributed in the hope that it will be useful,          |
 | but WITHOUT ANY WARRANTY; without even the implied warranty of           |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the             |
 | GNU Affero General Public License for more details.                      |
 |                                                                          |
 | You should have received a copy of the GNU Affero General Public License |
 | along with this program. If not, see <http://www.gnu.org/licenses/>      |
 +--------------------------------------------------------------------------+
 | Author: Timotheus Pokorra <tp@tbits.net>                                 |
 +--------------------------------------------------------------------------+
*/

class password_policy {

    private static function get_password_policy()
    {
        // TODO: get the password policy from LDAP instead?
        $conf = Conf::get_instance();

        $passwordpolicy = $conf->get('kolab', 'password_policy', Conf::AUTO);

        if (isset($passwordpolicy) && !isset($passwordpolicy['specialChars'])) {
            $passwordpolicy['specialChars'] = self::get_special_characters($passwordpolicy);
        }

        return $passwordpolicy;
    }

    /**
     * calculate which special characters will work in the current setup
     *
     * @return string with the allowed special characters
     */
    private static function get_special_characters($passwordpolicy)
    {
        $special_chars = '';

        // only use the characters from the 127 bit range. otherwise the user gets characters that he cannot type or does not know, eg Umlaut
        $maxcharacter = 127;

        for ($c = 33; $c < $maxcharacter; $c++) {
            if ($c >= ord('0') && $c <= ord('9')) {
                continue;
            }

            if ($c >= ord('a') && $c <= ord('z')) {
                continue;
            }

            if ($c >= ord('A') && $c <= ord('Z')) {
                continue;
            }

            if ($c == 127 || $c == 255) {
                continue;
            }

            # do not use some characters that are not well-known to users
            if (chr($c) == '`' || chr($c) == '|') {
                continue;
            }

            if ($c > 127) {
                $special_chars .= mb_convert_encoding('&#' . intval($c) . ';', 'UTF-8', 'HTML-ENTITIES');
            } else {
                $special_chars .= chr($c);
            }
        }

        return $special_chars;
    }

    /**
     * validate if password matches the password policy
     * @throws an exception if password is not secure enough
     */
    public static function validate_password($password)
    {
        $passwordpolicy = self::get_password_policy();

        if (!isset($passwordpolicy)) {
           return true;
        }

        $password = trim($password);

        $errors = '';

        if (strlen($password) < $passwordpolicy['minLength']) {
            $errors .= kolab_api_controller::translate("error").": ".
                       kolab_api_controller::translate("user.password.tooshort", $passwordpolicy['minLength']).'<br/>';
        }

        $countUpperCaseChars = strlen(preg_replace('![^A-Z]+!', '', $password));
        if ($countUpperCaseChars < $passwordpolicy['minUpper']) {
            $errors .= kolab_api_controller::translate("error").": ".
                       kolab_api_controller::translate("user.password.moreupper", $passwordpolicy['minUpper']).'<br/>';
        }

        $countLowerCaseChars = strlen(preg_replace('![^a-z]+!', '', $password));
        if ($countLowerCaseChars < $passwordpolicy['minLower']) {
            $errors .= kolab_api_controller::translate("error").": ".
                       kolab_api_controller::translate("user.password.morelower", $passwordpolicy['minLower']).'<br/>';
        }

        $countDigits = strlen(preg_replace('![^0-9]+!', '', $password));
        if ($countDigits < $passwordpolicy['minNumeric']) {
            $errors .= kolab_api_controller::translate("error").": ".
                       kolab_api_controller::translate("user.password.moredigits", $passwordpolicy['minNumeric']).'<br/>';
        }

        $sourceCharacters = str_split($passwordpolicy['specialChars']);
        $countSpecialChars = 0;
        foreach($sourceCharacters as $currentCharacter) {
            $countSpecialChars += substr_count($password, $currentCharacter);
        }

        if ($countSpecialChars < $passwordpolicy['minSpecial']) {
             $errors .= kolab_api_controller::translate("error").": ".
                        kolab_api_controller::translate("user.password.morespecial", $passwordpolicy['minSpecial'], $passwordpolicy['specialChars']).'<br/>';
        }

        # by default there is a 7-bit password enforcement plugin enabled on 389ds
        if ($passwordpolicy['7bitPasswordEnforcement'] == '0') {
            // do not test for characters beyond 127
        } else if ($countUpperCaseChars + $countLowerCaseChars + $countDigits + $countSpecialChars < strlen($password)) {
            $errors .= kolab_api_controller::translate("error").": ".
                       kolab_api_controller::translate("user.password.notallowed").'<br/>';
        }

        if ($errors != "") {
            throw new Exception($errors);
        }
    }

    /**
     * generate a password that meets the given password complexity policy
     *
     * @return password
    */
    public static function generate_password()
    {
        $passwordpolicy = self::get_password_policy();

        if (!isset($passwordpolicy)) {
             # default behaviour, if no policy has been configured
             exec("head -c 200 /dev/urandom | tr -dc _A-Z-a-z-0-9 | head -c15", $userpassword_plain);
             return $userpassword_plain[0];
        }

        $password = '';

        if ($passwordpolicy['minNumeric'] > 0) {
            unset($pwd_snippet);
            exec("head -c 200 /dev/urandom | tr -dc 0-9 | head -c".$passwordpolicy['minNumeric'], $pwd_snippet);
            $password .= $pwd_snippet[0];
        }

        if ($passwordpolicy['minUpper'] > 0) {
            unset($pwd_snippet);
            exec("head -c 200 /dev/urandom | tr -dc 'A-Z' | head -c".$passwordpolicy['minUpper'], $pwd_snippet);
            $password .= $pwd_snippet[0];
        }

        if ($passwordpolicy['minSpecial'] > 0) {
            # using rand instead of /dev/urandom to avoid problems with special characters on bash command line
            for ($countSpecialChar = 0; $countSpecialChar < $passwordpolicy['minSpecial']; $countSpecialChar++) {
                $password .= mb_substr($passwordpolicy['specialChars'], rand() % mb_strlen($passwordpolicy['specialChars']), 1);
            }
        }

        $numberLowerCase = $passwordpolicy['minLower'];

        if ($passwordpolicy['minLength'] > mb_strlen($password) + $passwordpolicy['minLower']) {
            $numberLowerCase = $passwordpolicy['minLength'] - mb_strlen($password);
        }

        unset($pwd_snippet);
        exec("head -c 200 /dev/urandom | tr -dc a-z | head -c".$numberLowerCase, $pwd_snippet);
        $password .= $pwd_snippet[0];

        $len = mb_strlen($password);
        $pwd_chars = array();
        while($len-- > 0) {
            $pwd_chars[] = mb_substr($password, $len, 1);
        }

        shuffle($pwd_chars);

        return join('', $pwd_chars);
    }
}