mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Valery Kharseko
3 hours ago 8672f11245231e8d7eecc2054653a3e3b133f1a3
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env python3
#
# The contents of this file are subject to the terms of the Common Development and
# Distribution License (the License). You may not use this file except in compliance with the
# License.
#
# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
# specific language governing permission and limitations under the License.
#
# When distributing Covered Software, include this CDDL Header Notice in each file and include
# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
# Header, with the fields enclosed by brackets [] replaced by your own identifying
# information: "Portions copyright [year] [name of copyright owner]".
#
# Copyright 2026 3A Systems, LLC.
 
"""Read changelog monitors and check membership over loopback LDAPS without a client JVM.
 
This implements LDAPv3 simple bind and the searches needed for the scale checks.
A non-success result, referral, malformed response or timeout never yields a snapshot.
The caller supplies a loopback-only published administration port and an absolute deadline;
the bind password is read from standard input, not from the command line.
"""
 
import base64
import re
import socket
import ssl
import sys
import time
 
MAX_FRAME = 8 * 1024 * 1024
MAX_SNAPSHOT = 8 * 1024 * 1024
 
 
class LdapError(Exception):
    pass
 
 
def tlv(tag, value):
    length = len(value)
    if length < 128:
        encoded = bytes([length])
    else:
        raw = length.to_bytes((length.bit_length() + 7) // 8, 'big')
        encoded = bytes([0x80 | len(raw)]) + raw
    return bytes([tag]) + encoded + value
 
 
def fields(data):
    position = 0
    while position < len(data):
        if position + 2 > len(data):
            raise LdapError('truncated BER field')
        tag, length = data[position], data[position + 1]
        position += 2
        if length & 0x80:
            size = length & 0x7f
            if not size or size > 4 or position + size > len(data):
                raise LdapError('invalid BER length')
            length = int.from_bytes(data[position:position + size], 'big')
            position += size
        if length > MAX_FRAME or position + length > len(data):
            raise LdapError('truncated or oversized BER value')
        yield tag, data[position:position + length]
        position += length
 
 
def receive(sock, length, deadline):
    data = bytearray()
    while len(data) < length:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError('LDAP request timed out')
        sock.settimeout(remaining)
        try:
            chunk = sock.recv(length - len(data))
        except socket.timeout as error:
            raise TimeoutError('LDAP request timed out') from error
        if not chunk:
            raise EOFError('LDAP connection closed before the response')
        data.extend(chunk)
    return bytes(data)
 
 
def transmit(sock, data, deadline):
    remaining = deadline - time.monotonic()
    if remaining <= 0:
        raise TimeoutError('LDAP request timed out')
    sock.settimeout(remaining)
    try:
        sock.sendall(data)
    except socket.timeout as error:
        raise TimeoutError('LDAP request timed out') from error
 
 
def read_frame(sock, deadline):
    header = receive(sock, 2, deadline)
    if header[0] != 0x30:
        raise LdapError('LDAP response is not a sequence')
    length = header[1]
    if length & 0x80:
        size = length & 0x7f
        if not size or size > 4:
            raise LdapError('invalid LDAP message length')
        length = int.from_bytes(receive(sock, size, deadline), 'big')
    if length > MAX_FRAME:
        raise LdapError('LDAP message exceeds size limit')
    return receive(sock, length, deadline)
 
 
def message(sock, wanted_id, deadline):
    parts = list(fields(read_frame(sock, deadline)))
    if len(parts) < 2 or parts[0][0] != 0x02 or not parts[0][1]:
        raise LdapError('invalid LDAP message envelope')
    if int.from_bytes(parts[0][1], 'big', signed=True) != wanted_id:
        raise LdapError('unexpected LDAP message ID')
    if len(parts) > 3 or (len(parts) == 3 and parts[2][0] != 0xa0):
        raise LdapError('unexpected LDAP message fields')
    return parts[1]
 
 
def require_success(value):
    parts = list(fields(value))
    if len(parts) < 3 or [part[0] for part in parts[:3]] != [0x0a, 0x04, 0x04] or not parts[0][1]:
        raise LdapError('invalid LDAP result')
    code = int.from_bytes(parts[0][1], 'big', signed=True)
    if code != 0:
        raise LdapError('LDAP operation failed with result %s' % code)
 
 
def entry_ldif(value):
    parts = list(fields(value))
    if len(parts) != 2 or parts[0][0] != 0x04 or parts[1][0] != 0x30:
        raise LdapError('invalid LDAP search entry')
    lines = ['dn:: ' + base64.b64encode(parts[0][1]).decode('ascii')]
    for tag, attr in fields(parts[1][1]):
        items = list(fields(attr))
        if tag != 0x30 or len(items) != 2 or items[0][0] != 0x04 or items[1][0] != 0x31:
            raise LdapError('invalid LDAP attribute')
        name = items[0][1].decode('ascii')
        if not re.fullmatch(r'[A-Za-z0-9;-]+', name):
            raise LdapError('invalid LDAP attribute name')
        for value_tag, content in fields(items[1][1]):
            if value_tag != 0x04:
                raise LdapError('invalid LDAP attribute value')
            lines.append(name + ':: ' + base64.b64encode(content).decode('ascii'))
    return '\n'.join(lines) + '\n\n'
 
 
def bind(sock, password, deadline):
    request = tlv(0x02, b'\x03') + tlv(0x04, b'cn=Directory Manager') + tlv(0x80, password)
    transmit(sock, tlv(0x30, tlv(0x02, b'\x01') + tlv(0x60, request)), deadline)
    tag, result = message(sock, 1, deadline)
    if tag != 0x61:
        raise LdapError('expected LDAP bind response')
    require_success(result)
 
 
def search(sock, password, deadline, present=b'replicationServer-database',
           attributes=(b'replicationServer-database', b'domain-name', b'last-change')):
    bind(sock, password, deadline)
    query = (tlv(0x04, b'cn=monitor') + tlv(0x0a, b'\x02') + tlv(0x0a, b'\x00') +
             tlv(0x02, b'\x00') + tlv(0x02, b'\x00') + tlv(0x01, b'\x00') +
             tlv(0x87, present) + tlv(0x30, b''.join(tlv(0x04, attr) for attr in attributes)))
    transmit(sock, tlv(0x30, tlv(0x02, b'\x02') + tlv(0x63, query)), deadline)
    entries = []
    size = 0
    while True:
        tag, value = message(sock, 2, deadline)
        if tag == 0x64:
            entry = entry_ldif(value)
            size += len(entry)
            if size > MAX_SNAPSHOT:
                raise LdapError('LDAP snapshot exceeds size limit')
            entries.append(entry)
        elif tag == 0x65:
            require_success(value)
            if time.monotonic() >= deadline:
                raise TimeoutError('LDAP response completed after the deadline')
            return 'version: 1\n\n' + ''.join(entries)
        else:
            raise LdapError('unexpected LDAP search response')
 
 
def entry_attributes(value):
    parts = list(fields(value))
    if len(parts) != 2 or parts[0][0] != 0x04 or parts[1][0] != 0x30:
        raise LdapError('invalid LDAP search entry')
    parts[0][1].decode('utf-8')
    attributes = {}
    for tag, attribute in fields(parts[1][1]):
        items = list(fields(attribute))
        if tag != 0x30 or len(items) != 2 or items[0][0] != 0x04 or items[1][0] != 0x31:
            raise LdapError('invalid LDAP attribute')
        name = items[0][1].decode('ascii').lower()
        if not re.fullmatch(r'[a-z0-9;-]+', name) or name in attributes:
            raise LdapError('invalid or duplicate LDAP attribute')
        values = []
        for value_tag, content in fields(items[1][1]):
            if value_tag != 0x04:
                raise LdapError('invalid LDAP attribute value')
            values.append(content.decode('utf-8'))
        attributes[name] = values
    return attributes
 
 
def attribute_search(sock, deadline, message_id, base, scope, ldap_filter, attribute):
    query = (tlv(0x04, base) + tlv(0x0a, bytes([scope])) + tlv(0x0a, b'\x00') +
             tlv(0x02, b'\x00') + tlv(0x02, b'\x00') + tlv(0x01, b'\x00') +
             ldap_filter + tlv(0x30, tlv(0x04, attribute)))
    transmit(sock, tlv(0x30, tlv(0x02, bytes([message_id])) + tlv(0x63, query)), deadline)
    entries, size = [], 0
    while True:
        tag, value = message(sock, message_id, deadline)
        if tag == 0x64:
            size += len(value)
            if size > MAX_SNAPSHOT:
                raise LdapError('LDAP snapshot exceeds size limit')
            entries.append(entry_attributes(value))
        elif tag == 0x65:
            require_success(value)
            if time.monotonic() >= deadline:
                raise TimeoutError('LDAP response completed after the deadline')
            return entries
        else:
            raise LdapError('unexpected LDAP search response')
 
 
def connected_to(sock, password, deadline, domain):
    bind(sock, password, deadline)
    attribute = b'connected-to'
    entries = attribute_search(sock, deadline, 2, domain.encode('utf-8'), 1, tlv(0x87, attribute), attribute)
    values = entries[0].get('connected-to', []) if len(entries) == 1 else []
    if len(values) != 1 or not values[0]:
        raise LdapError('expected one connected-to endpoint for ' + domain)
    return values[0]
 
 
def membership_matches(registry, config, peer, wanted):
    if wanted not in ('present', 'absent') or not registry or not config:
        return False
    peer = peer.lower()
    def matches(host):
        host = host.lower()
        return host == peer or host.split('.')[0] == peer
    hosts = [host for entry in registry for host in entry.get('hostname', [])]
    if not hosts or any(not host for host in hosts):
        return False
    found = any(matches(host) for host in hosts)
    lists = [any(matches(re.sub(r':[0-9]+$', '', host))
                 for host in entry.get('ds-cfg-replication-server', [])) for entry in config]
    return (found and all(lists)) if wanted == 'present' else (not found and not any(lists))
 
 
def membership(sock, password, deadline, peer, wanted):
    bind(sock, password, deadline)
    registry = attribute_search(sock, deadline, 2, b'cn=Servers,cn=admin data', 1,
                                tlv(0x87, b'objectClass'), b'hostname')
    equal = lambda value: tlv(0xa3, tlv(0x04, b'objectClass') + tlv(0x04, value))
    ldap_filter = tlv(0xa1, equal(b'ds-cfg-replication-server') + equal(b'ds-cfg-replication-domain'))
    config = attribute_search(sock, deadline, 3, b'cn=config', 2, ldap_filter,
                              b'ds-cfg-replication-server')
    return membership_matches(registry, config, peer, wanted)
 
 
def main(argv):
    args = argv[3:]
    route = len(args) == 2 and args[0] == 'connected-to'
    member = len(args) == 3 and args[0] == 'membership' and args[2] in ('present', 'absent')
    if len(argv) < 3 or (args and not (route or member)):
        print('usage: scale-monitor.py <loopback port> <load deadline in milliseconds> '
              '[connected-to <monitor DN> | membership <peer> <present|absent>]', file=sys.stderr)
        return 2
    try:
        port, load_deadline = int(argv[1]), int(argv[2]) / 1000
        if not 1 <= port <= 65535:
            raise ValueError('invalid loopback port')
        password = sys.stdin.buffer.read(4097)
        if not password or len(password) > 4096:
            raise ValueError('invalid bind password')
        remaining = min(45.0, load_deadline - time.time())
        if remaining <= 0:
            raise TimeoutError('load deadline reached')
        deadline = time.monotonic() + remaining
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE  # Same trust policy as the existing --trustAll search.
        with socket.create_connection(('127.0.0.1', port), timeout=remaining) as raw:
            with context.wrap_socket(raw, server_hostname='localhost') as connection:
                output, matched = None, True
                if route:
                    output = connected_to(connection, password, deadline, args[1]) + '\n'
                elif member:
                    matched = membership(connection, password, deadline, args[1], args[2])
                else:
                    output = search(connection, password, deadline)
        if time.monotonic() >= deadline or time.time() >= load_deadline:
            raise TimeoutError('LDAP response completed after the deadline')
        if output is not None:
            sys.stdout.write(output)
        return 0 if matched else 1
    except (TimeoutError, socket.timeout):
        print('timeout=' + ('load' if time.time() >= load_deadline else 'query'), file=sys.stderr)
        return 124
    except (OSError, ValueError, UnicodeError, LdapError, EOFError) as error:
        print('scale monitor failed: %s' % error, file=sys.stderr)
        return 1
 
 
if __name__ == '__main__':
    sys.exit(main(sys.argv))