summaryrefslogtreecommitdiff
path: root/auth/credentials/tests/bind.py
blob: 8bee6f96c62a43d90e42a3e64fabb69ad326cf19 (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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This is unit with tests for LDAP access checks

from __future__ import print_function
import optparse
import sys
import base64
import copy

sys.path.insert(0, "bin/python")
import samba
from samba.tests.subunitrun import SubunitOptions, TestProgram

import samba.getopt as options

from ldb import SCOPE_BASE, SCOPE_SUBTREE, LdbError, ERR_INVALID_CREDENTIALS

from samba import gensec
import samba.tests
from samba.tests import delete_force
from samba.credentials import Credentials

def create_credential(lp, other):
    c = Credentials()
    c.guess(lp)
    c.set_gensec_features(other.get_gensec_features())
    return c

parser = optparse.OptionParser("ldap [options] <host>")
sambaopts = options.SambaOptions(parser)
parser.add_option_group(sambaopts)

# use command line creds if available
credopts = options.CredentialsOptions(parser)
parser.add_option_group(credopts)
subunitopts = SubunitOptions(parser)
parser.add_option_group(subunitopts)
opts, args = parser.parse_args()

if len(args) < 1:
    parser.print_usage()
    sys.exit(1)

host = args[0]
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)

creds_machine = create_credential(lp, creds)
creds_virtual = create_credential(lp, creds)
creds_user1 = create_credential(lp, creds)
creds_user2 = create_credential(lp, creds)
creds_user3 = create_credential(lp, creds)
creds_user4 = create_credential(lp, creds)

class BindTests(samba.tests.TestCase):

    info_dc = None

    def setUp(self):
        super(BindTests, self).setUp()
        # fetch rootDSEs

        self.ldb = samba.tests.connect_samdb(host, credentials=creds, lp=lp, ldap_only=True)

        if self.info_dc is None:
            res = self.ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"])
            self.assertEqual(len(res), 1)
            BindTests.info_dc = res[0]
        # cache some of RootDSE props
        self.schema_dn = self.info_dc["schemaNamingContext"][0]
        self.domain_dn = self.info_dc["defaultNamingContext"][0]
        self.config_dn = self.info_dc["configurationNamingContext"][0]
        self.realm = self.info_dc["ldapServiceName"][0].split(b'@')[1].decode('utf-8')
        self.computer_dn = "CN=centos53,CN=Computers,%s" % self.domain_dn
        self.virtual_user_dn = "CN=frednurk@%s,CN=Computers,%s" % (self.realm, self.domain_dn)
        self.password = "P@ssw0rd"
        self.username = "BindTestUser"

    def tearDown(self):
        delete_force(self.ldb, self.virtual_user_dn)
        super(BindTests, self).tearDown()

    def test_virtual_email_account_style_bind(self):
        # create a user in the style often deployed for authentication
        # of virtual email account at a hosting provider
        #
        # The userPrincipalName must not match the samAccountName for
        # this test to detect when the LDAP DN is being double-parsed
        # but must be in the user@realm style to allow the account to
        # be created
        self.ldb.add_ldif("""
dn: """ + self.virtual_user_dn + """
cn: frednurk@""" + self.realm + """
displayName: Fred Nurk
sAMAccountName: frednurk@""" + self.realm + """
userPrincipalName: frednurk@NOT.""" + self.realm + """
countryCode: 0
objectClass: computer
objectClass: organizationalPerson
objectClass: person
objectClass: top
objectClass: user
""")
        self.addCleanup(delete_force, self.ldb, self.virtual_user_dn)
        self.ldb.modify_ldif("""
dn: """ + self.virtual_user_dn + """
changetype: modify
replace: unicodePwd
unicodePwd:: """ + base64.b64encode(u"\"P@ssw0rd\"".encode('utf-16-le')).decode('utf8') + """
""")

        self.ldb.enable_account('distinguishedName=%s' % self.virtual_user_dn)

        # do a simple bind and search with the machine account
        creds_virtual.set_bind_dn(self.virtual_user_dn)
        creds_virtual.set_password(self.password)
        print("BindTest with: " + creds_virtual.get_bind_dn())
        try:
            ldb_virtual = samba.tests.connect_samdb(host, credentials=creds_virtual,
                                                    lp=lp, ldap_only=True)
        except LdbError as e:
            (num, msg) = e.args
            if num != ERR_INVALID_CREDENTIALS:
                raise
            self.fail(msg)

        res = ldb_virtual.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"])

    def test_computer_account_bind(self):
        # create a computer acocount for the test
        delete_force(self.ldb, self.computer_dn)
        self.ldb.add_ldif("""
dn: """ + self.computer_dn + """
cn: CENTOS53
displayName: CENTOS53$
name: CENTOS53
sAMAccountName: CENTOS53$
countryCode: 0
objectClass: computer
objectClass: organizationalPerson
objectClass: person
objectClass: top
objectClass: user
codePage: 0
userAccountControl: 4096
dNSHostName: centos53.alabala.test
operatingSystemVersion: 5.2 (3790)
operatingSystem: Windows Server 2003
""")
        self.ldb.modify_ldif("""
dn: """ + self.computer_dn + """
changetype: modify
replace: unicodePwd
unicodePwd:: """ + base64.b64encode(u"\"P@ssw0rd\"".encode('utf-16-le')).decode('utf8') + """
""")

        # do a simple bind and search with the machine account
        creds_machine.set_bind_dn(self.computer_dn)
        creds_machine.set_password(self.password)
        print("BindTest with: " + creds_machine.get_bind_dn())
        ldb_machine = samba.tests.connect_samdb(host, credentials=creds_machine,
                                                lp=lp, ldap_only=True)
        res = ldb_machine.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"])

    def test_user_account_bind(self):
        # create user
        self.ldb.newuser(username=self.username, password=self.password)
        ldb_res = self.ldb.search(base=self.domain_dn,
                                  scope=SCOPE_SUBTREE,
                                  expression="(samAccountName=%s)" % self.username)
        self.assertEqual(len(ldb_res), 1)
        user_dn = ldb_res[0]["dn"]
        self.addCleanup(delete_force, self.ldb, user_dn)

        # do a simple bind and search with the user account in format user@realm
        creds_user1.set_bind_dn(self.username + "@" + creds.get_realm())
        creds_user1.set_password(self.password)
        print("BindTest with: " + creds_user1.get_bind_dn())
        ldb_user1 = samba.tests.connect_samdb(host, credentials=creds_user1,
                                              lp=lp, ldap_only=True)
        res = ldb_user1.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"])

        # do a simple bind and search with the user account in format domain\user
        creds_user2.set_bind_dn(creds.get_domain() + "\\" + self.username)
        creds_user2.set_password(self.password)
        print("BindTest with: " + creds_user2.get_bind_dn())
        ldb_user2 = samba.tests.connect_samdb(host, credentials=creds_user2,
                                              lp=lp, ldap_only=True)
        res = ldb_user2.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"])

        # do a simple bind and search with the user account DN
        creds_user3.set_bind_dn(str(user_dn))
        creds_user3.set_password(self.password)
        print("BindTest with: " + creds_user3.get_bind_dn())
        ldb_user3 = samba.tests.connect_samdb(host, credentials=creds_user3,
                                              lp=lp, ldap_only=True)
        res = ldb_user3.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"])

    def test_user_account_bind_no_domain(self):
        # create user
        self.ldb.newuser(username=self.username, password=self.password)
        ldb_res = self.ldb.search(base=self.domain_dn,
                                  scope=SCOPE_SUBTREE,
                                  expression="(samAccountName=%s)" % self.username)
        self.assertEqual(len(ldb_res), 1)
        user_dn = ldb_res[0]["dn"]
        self.addCleanup(delete_force, self.ldb, user_dn)

        creds_user4.set_username(self.username)
        creds_user4.set_password(self.password)
        creds_user4.set_domain('')
        creds_user4.set_workstation('')
        print("BindTest (no domain) with: " + self.username)
        try:
            ldb_user4 = samba.tests.connect_samdb(host, credentials=creds_user4,
                                                  lp=lp, ldap_only=True)
        except:
            self.fail("Failed to connect without the domain set")

        res = ldb_user4.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"])


TestProgram(module=__name__, opts=subunitopts)