The branch, master has been updated
       via  95cad5ca samba-tool: Use same method for removing trailing $ as 
elsewhere in the tool
       via  0a6c2ac samba-tool: Escape username and computername in ldb search 
filter
       via  306f5e5 s3-mdssvc: allow build with --enable-spotlight and 
libtracker-sparql-2.0
       via  ba81f33 docs-xml:samba-tool.8: improve doc for computer management 
commands
       via  5a51990 docs-xml:samba-tool.8: document computer management commands
       via  e41b9b0 samba-tool: improve computer management commands
       via  6e4a49e tests/samba-tool: add tests for new computer management 
commands
       via  f262520 samba-tool: implement computer management commands
      from  946dfc7 upgradeprovision: detect and handle lmdb databases

https://git.samba.org/?p=samba.git;a=shortlog;h=master


- Log -----------------------------------------------------------------
commit 95cad5cab30fb0cc54a730a8bbef88c34d6ed875
Author: Andrew Bartlett <abart...@samba.org>
Date:   Fri Apr 6 16:21:15 2018 +1200

    samba-tool: Use same method for removing trailing $ as elsewhere in the tool
    
    Signed-off-by: Andrew Bartlett <abart...@samba.org>
    Reviewed-by: Douglas Bagnall <douglas.bagn...@catalyst.net.nz>
    
    Autobuild-User(master): Andrew Bartlett <abart...@samba.org>
    Autobuild-Date(master): Fri Apr  6 09:30:14 CEST 2018 on sn-devel-144

commit 0a6c2ac88f8c2423ffbb7cdf2624ca5d95cb3d30
Author: Andrew Bartlett <abart...@samba.org>
Date:   Fri Apr 6 16:20:22 2018 +1200

    samba-tool: Escape username and computername in ldb search filter
    
    Signed-off-by: Andrew Bartlett <abart...@samba.org>
    Reviewed-by: Douglas Bagnall <douglas.bagn...@catalyst.net.nz>

commit 306f5e57f2ebf80bb02a9d87c34d78b3d00ca010
Author: Björn Baumbach <b...@sernet.de>
Date:   Thu Apr 5 17:14:32 2018 +0200

    s3-mdssvc: allow build with --enable-spotlight and libtracker-sparql-2.0
    
    adds libtracker-sparql version 2.0 to configure check with pkg-config.
    
    Signed-off-by: Björn Baumbach <b...@sernet.de>
    Reviewed-by: Ralph Boehme <s...@samba.org>
    Reviewed-by: Andrew Bartlett <abart...@samba.org>
    Reviewed-by: Douglas Bagnall <douglas.bagn...@catalyst.net.nz>

commit ba81f33fc4fe7b972f6852a9b1e8b026fbd45fff
Author: Joe Guo <j...@catalyst.net.nz>
Date:   Fri Mar 16 16:39:08 2018 +1300

    docs-xml:samba-tool.8: improve doc for computer management commands
    
    Add docs for new options:
    1. --ip-address
    2. --service-prinicipal-name
    
    Signed-off-by: Joe Guo <j...@catalyst.net.nz>
    Reviewed-by: Andrew Bartlett <abart...@samba.org>
    Reviewed-by: Douglas Bagnall <douglas.bagn...@catalyst.net.nz>

commit 5a51990f5dcc3cb8181d2fa4c3a1c07fea0f6112
Author: Björn Baumbach <b...@sernet.de>
Date:   Wed Mar 7 10:15:06 2018 +0100

    docs-xml:samba-tool.8: document computer management commands
    
    Signed-off-by: Björn Baumbach <b...@sernet.de>
    Reviewed-by: Andrew Bartlett <abart...@samba.org>
    Reviewed-by: Douglas Bagnall <douglas.bagn...@catalyst.net.nz>

commit e41b9b04e23f0e8831ff922d247b737bf8116151
Author: Joe Guo <j...@catalyst.net.nz>
Date:   Tue Mar 13 16:47:58 2018 +1300

    samba-tool: improve computer management commands
    
    This pathch is based on Björn Baumbach's work:
    1. Add `--ip-address` option for create subcommand, to allow user set DNS
    A or AAAA records while creating the computer.
    2. Delete above DNS records while deleting the computer.
    3. Add `--service-principal-name` option for create command, to allow user
    set `servicePrincipalName` while creating the computer.
    4. Tests.
    
    Signed-off-by: Joe Guo <j...@catalyst.net.nz>
    Reviewed-by: Andrew Bartlett <abart...@samba.org>
    Reviewed-by: Douglas Bagnall <douglas.bagn...@catalyst.net.nz>

commit 6e4a49e992a9b3b3dc5e96896c934abcb6ee6b4e
Author: Björn Baumbach <b...@sernet.de>
Date:   Tue Feb 6 22:11:12 2018 +0100

    tests/samba-tool: add tests for new computer management commands
    
    Signed-off-by: Björn Baumbach <b...@sernet.de>
    Reviewed-by: Andrew Bartlett <abart...@samba.org>
    Reviewed-by: Douglas Bagnall <douglas.bagn...@catalyst.net.nz>

commit f262520c8556b117d7c20bc4127b2de0483828ae
Author: Björn Baumbach <b...@sernet.de>
Date:   Thu Dec 7 21:38:28 2017 +0100

    samba-tool: implement computer management commands
    
    Usage: samba-tool computer <subcommand>
    
    Computer management.
    
    Available subcommands:
      create  - Create a new computer.
      delete  - Delete a computer.
      list    - List all computers.
      move    - Move a computer to an organizational unit/container.
      show    - Display a computer AD object
    
    Signed-off-by: Björn Baumbach <b...@sernet.de>
    Reviewed-by: Andrew Bartlett <abart...@samba.org>
    Reviewed-by: Douglas Bagnall <douglas.bagn...@catalyst.net.nz>

-----------------------------------------------------------------------

Summary of changes:
 docs-xml/manpages/samba-tool.8.xml        |  85 +++++
 python/samba/netcmd/computer.py           | 586 ++++++++++++++++++++++++++++++
 python/samba/netcmd/main.py               |   1 +
 python/samba/netcmd/user.py               |   2 +-
 python/samba/samdb.py                     |  60 +++
 python/samba/tests/samba_tool/computer.py | 329 +++++++++++++++++
 source3/wscript                           |   2 +-
 source4/selftest/tests.py                 |   1 +
 8 files changed, 1064 insertions(+), 2 deletions(-)
 create mode 100644 python/samba/netcmd/computer.py
 create mode 100644 python/samba/tests/samba_tool/computer.py


Changeset truncated at 500 lines:

diff --git a/docs-xml/manpages/samba-tool.8.xml 
b/docs-xml/manpages/samba-tool.8.xml
index bcdad77..3cde4c5 100644
--- a/docs-xml/manpages/samba-tool.8.xml
+++ b/docs-xml/manpages/samba-tool.8.xml
@@ -110,6 +110,91 @@
 <refsect1>
 <title>COMMANDS</title>
 
+<refsect3>
+       <title>computer create <replaceable>computername</replaceable> 
[options]</title>
+       <para>Create a new computer in the Active Directory Domain.</para>
+       <para>The new computer name specified on the command is the
+       sAMAccountName, with or without the trailing dollar sign.</para>
+
+       <variablelist>
+       <varlistentry>
+       <term>--computerou=COMPUTEROU</term>
+       <listitem><para>
+       DN of alternative location (with or without domainDN counterpart) to
+       default CN=Users in which new computer object will be created.
+       E.g. 'OU=OUname'.
+       </para></listitem>
+       </varlistentry>
+
+       <varlistentry>
+       <term>--description=DESCRIPTION</term>
+       <listitem><para>
+       The new computers's description.
+       </para></listitem>
+       </varlistentry>
+
+       <varlistentry>
+       <term>--ip-address=IP_ADDRESS_LIST</term>
+       <listitem><para>
+       IPv4 address for the computer's A record, or IPv6 address for AAAA 
record,
+       can be provided multiple times.
+       </para></listitem>
+       </varlistentry>
+
+       <varlistentry>
+       <term>--service-principal-name=SERVICE_PRINCIPAL_NAME_LIST</term>
+       <listitem><para>
+       Computer's Service Principal Name, can be provided multiple times.
+       </para></listitem>
+       </varlistentry>
+
+       <varlistentry>
+       <term>--prepare-oldjoin</term>
+       <listitem><para>
+       Prepare enabled machine account for oldjoin mechanism.
+       </para></listitem>
+       </varlistentry>
+       </variablelist>
+</refsect3>
+
+<refsect3>
+       <title>computer delete <replaceable>computername</replaceable> 
[options]</title>
+       <para>Delete an existing computer account.</para>
+       <para>The computer name specified on the command is the
+       sAMAccountName, with or without the trailing dollar sign.</para>
+</refsect3>
+
+<refsect3>
+       <title>computer list</title>
+       <para>List all computers.</para>
+</refsect3>
+
+<refsect3>
+       <title>computer move <replaceable>computername</replaceable> 
<replaceable>new_parent_dn</replaceable> [options]</title>
+       <para>This command moves a computer account into the specified
+       organizational unit or container.</para>
+       <para>The computername specified on the command is the
+       sAMAccountName, with or without the trailing dollar sign.</para>
+       <para>The name of the organizational unit or container can be
+       specified as a full DN or without the domainDN component.</para>
+</refsect3>
+
+<refsect3>
+       <title>computer show <replaceable>computername</replaceable> 
[options]</title>
+       <para>Display a computer AD object.</para>
+       <para>The computer name specified on the command is the
+       sAMAccountName, with or without the trailing dollar sign.</para>
+
+       <variablelist>
+       <varlistentry>
+       <term>--attributes=USER_ATTRS</term>
+       <listitem><para>
+       Comma separated list of attributes, which will be printed.
+       </para></listitem>
+       </varlistentry>
+       </variablelist>
+</refsect3>
+
 <refsect2>
        <title>dbcheck</title>
        <para>Check the local AD database for errors.</para>
diff --git a/python/samba/netcmd/computer.py b/python/samba/netcmd/computer.py
new file mode 100644
index 0000000..3b130b1
--- /dev/null
+++ b/python/samba/netcmd/computer.py
@@ -0,0 +1,586 @@
+# machine account (computer) management
+#
+# Copyright Bjoern Baumbch <b...@sernet.de> 2018
+#
+# based on user management
+# Copyright Jelmer Vernooij 2010 <jel...@samba.org>
+# Copyright Theresa Halloran 2011 <theresahallo...@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+import samba.getopt as options
+import ldb
+import socket
+import samba
+import re
+from samba import sd_utils
+from samba.dcerpc import dnsserver, dnsp, security
+from samba.dnsserver import ARecord, AAAARecord
+from samba.ndr import ndr_unpack, ndr_pack, ndr_print
+from samba.remove_dc import remove_dns_references
+from samba.auth import system_session
+from samba.samdb import SamDB
+
+from samba import (
+    credentials,
+    dsdb,
+    Ldb,
+    werror,
+    WERRORError
+    )
+
+from samba.netcmd import (
+    Command,
+    CommandError,
+    SuperCommand,
+    Option,
+    )
+
+
+def _is_valid_ip(ip_string, address_families=None):
+    """Check ip string is valid address"""
+    # by default, check both ipv4 and ipv6
+    if not address_families:
+        address_families = [socket.AF_INET, socket.AF_INET6]
+
+    for address_family in address_families:
+        try:
+            socket.inet_pton(address_family, ip_string)
+            return True  # if no error, return directly
+        except socket.error:
+            continue  # Otherwise, check next family
+    return False
+
+
+def _is_valid_ipv4(ip_string):
+    """Check ip string is valid ipv4 address"""
+    return _is_valid_ip(ip_string, address_families=[socket.AF_INET])
+
+
+def _is_valid_ipv6(ip_string):
+    """Check ip string is valid ipv6 address"""
+    return _is_valid_ip(ip_string, address_families=[socket.AF_INET6])
+
+
+def add_dns_records(
+        samdb, name, dns_conn, change_owner_sd,
+        server, ip_address_list, logger):
+    """Add DNS A or AAAA records while creating computer. """
+    name = name.rstrip('$')
+    client_version = dnsserver.DNS_CLIENT_VERSION_LONGHORN
+    select_flags = dnsserver.DNS_RPC_VIEW_AUTHORITY_DATA | 
dnsserver.DNS_RPC_VIEW_NO_CHILDREN
+    zone = samdb.domain_dns_name()
+    name_found = True
+    sd_helper = sd_utils.SDUtils(samdb)
+
+    try:
+        buflen, res = dns_conn.DnssrvEnumRecords2(
+            client_version,
+            0,
+            server,
+            zone,
+            name,
+            None,
+            dnsp.DNS_TYPE_ALL,
+            select_flags,
+            None,
+            None,
+        )
+    except WERRORError as e:
+        if e.args[0] == werror.WERR_DNS_ERROR_NAME_DOES_NOT_EXIST:
+            name_found = False
+            pass
+
+    if name_found:
+        for rec in res.rec:
+            for record in rec.records:
+                if record.wType == dnsp.DNS_TYPE_A or record.wType == 
dnsp.DNS_TYPE_AAAA:
+                    # delete record
+                    del_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
+                    del_rec_buf.rec = record
+                    try:
+                        dns_conn.DnssrvUpdateRecord2(
+                            client_version,
+                            0,
+                            server,
+                            zone,
+                            name,
+                            None,
+                            del_rec_buf,
+                        )
+                    except WERRORError as e:
+                        if e.args[0] != 
werror.WERR_DNS_ERROR_NAME_DOES_NOT_EXIST:
+                            raise
+
+    for ip_address in ip_address_list:
+        if _is_valid_ipv6(ip_address):
+            logger.info("Adding DNS AAAA record %s.%s for IPv6 IP: %s" % (
+                name, zone, ip_address))
+            rec = AAAARecord(ip_address)
+        elif _is_valid_ipv4(ip_address):
+            logger.info("Adding DNS A record %s.%s for IPv4 IP: %s" % (
+                name, zone, ip_address))
+            rec = ARecord(ip_address)
+        else:
+            raise ValueError('Invalid IP: {}'.format(ip_address))
+
+        # Add record
+        add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
+        add_rec_buf.rec = rec
+
+        dns_conn.DnssrvUpdateRecord2(
+            client_version,
+            0,
+            server,
+            zone,
+            name,
+            add_rec_buf,
+            None,
+        )
+
+    if (len(ip_address_list) > 0):
+        domaindns_zone_dn = ldb.Dn(
+            samdb,
+            'DC=DomainDnsZones,%s' % samdb.get_default_basedn(),
+        )
+
+        dns_a_dn, ldap_record = samdb.dns_lookup(
+            "%s.%s" % (name, zone),
+            dns_partition=domaindns_zone_dn,
+        )
+
+        # Make the DC own the DNS record, not the administrator
+        sd_helper.modify_sd_on_dn(
+            dns_a_dn,
+            change_owner_sd,
+            controls=["sd_flags:1:%d" % (security.SECINFO_OWNER | 
security.SECINFO_GROUP)],
+        )
+
+
+class cmd_computer_create(Command):
+    """Create a new computer.
+
+This command creates a new computer account in the Active Directory domain.
+The computername specified on the command is the sAMaccountName without the
+trailing $ (dollar sign).
+
+User accounts may represent physical entities, such as workstations. Computer
+accounts are also referred to as security principals and are assigned a
+security identifier (SID).
+
+Example1:
+samba-tool computer create Computer1 -H ldap://samba.samdom.example.com \
+    -Uadministrator%passw1rd
+
+Example1 shows how to create a new computer in the domain against a remote LDAP
+server. The -H parameter is used to specify the remote target server. The -U
+option is used to pass the userid and password authorized to issue the command
+remotely.
+
+Example2:
+sudo samba-tool computer create Computer2
+
+Example2 shows how to create a new computer in the domain against the local
+server. sudo is used so a user may run the command as root.
+
+Example3:
+samba-tool computer create Computer3 --computerou='OU=OrgUnit'
+
+Example3 shows how to create a new computer in the OrgUnit organizational unit.
+
+"""
+    synopsis = "%prog <computername> [options]"
+
+    takes_options = [
+        Option("-H", "--URL", help="LDB URL for database or target server",
+               type=str, metavar="URL", dest="H"),
+        Option("--computerou",
+                help=("DN of alternative location (with or without domainDN "
+                      "counterpart) to default CN=Users in which new computer "
+                      "object will be created. E. g. 'OU=<OU name>'"),
+                type=str),
+        Option("--description", help="Computers's description", type=str),
+        Option("--prepare-oldjoin",
+               help="Prepare enabled machine account for oldjoin mechanism",
+               action="store_true"),
+        Option("--ip-address",
+               dest='ip_address_list',
+               help=("IPv4 address for the computer's A record, or IPv6 "
+                     "address for AAAA record, can be provided multiple "
+                     "times"),
+               action='append'),
+        Option("--service-principal-name",
+               dest='service_principal_name_list',
+               help=("Computer's Service Principal Name, can be provided "
+                     "multiple times"),
+               action='append')
+    ]
+
+    takes_args = ["computername"]
+
+    takes_optiongroups = {
+        "sambaopts": options.SambaOptions,
+        "credopts": options.CredentialsOptions,
+        "versionopts": options.VersionOptions,
+        }
+
+    def run(self, computername, credopts=None, sambaopts=None, 
versionopts=None,
+            H=None, computerou=None, description=None, prepare_oldjoin=False,
+            ip_address_list=None, service_principal_name_list=None):
+
+        if ip_address_list is None:
+            ip_address_list = []
+
+        if service_principal_name_list is None:
+            service_principal_name_list = []
+
+        # check each IP address if provided
+        for ip_address in ip_address_list:
+            if not _is_valid_ip(ip_address):
+                raise CommandError('Invalid IP address {}'.format(ip_address))
+
+        lp = sambaopts.get_loadparm()
+        creds = credopts.get_credentials(lp)
+
+        try:
+            samdb = SamDB(url=H, session_info=system_session(),
+                          credentials=creds, lp=lp)
+            samdb.newcomputer(computername, computerou=computerou,
+                              description=description,
+                              prepare_oldjoin=prepare_oldjoin,
+                              ip_address_list=ip_address_list,
+                              
service_principal_name_list=service_principal_name_list,
+                              )
+
+            if ip_address_list:
+                # if ip_address_list provided, then we need to create DNS
+                # records for this computer.
+
+                hostname = re.sub(r"\$$", "", computername)
+                if hostname.count('$'):
+                    raise CommandError('Illegal computername "%s"' % 
computername)
+
+                filters = 
'(&(sAMAccountName={}$)(objectclass=computer))'.format(
+                    ldb.binary_encode(hostname))
+
+                recs = samdb.search(
+                    base=samdb.domain_dn(),
+                    scope=ldb.SCOPE_SUBTREE,
+                    expression=filters,
+                    attrs=['primaryGroupID', 'objectSid'])
+
+                group = recs[0]['primaryGroupID'][0]
+                owner = ndr_unpack(security.dom_sid, recs[0]["objectSid"][0])
+
+                dns_conn = dnsserver.dnsserver(
+                    "ncacn_ip_tcp:{}[sign]".format(samdb.host_dns_name()),
+                    lp, creds)
+
+                change_owner_sd = security.descriptor()
+                change_owner_sd.owner_sid = owner
+                change_owner_sd.group_sid = security.dom_sid(
+                    "{}-{}".format(samdb.get_domain_sid(), group),
+                )
+
+                add_dns_records(
+                    samdb, hostname, dns_conn,
+                    change_owner_sd, samdb.host_dns_name(),
+                    ip_address_list, self.get_logger())
+        except Exception, e:
+            raise CommandError("Failed to create computer '%s': " %
+                               computername, e)
+
+        self.outf.write("Computer '%s' created successfully\n" % computername)
+
+
+class cmd_computer_delete(Command):
+    """Delete a computer.
+
+This command deletes a computer account from the Active Directory domain. The
+computername specified on the command is the sAMAccountName without the
+trailing $ (dollar sign).
+
+Once the account is deleted, all permissions and memberships associated with
+that account are deleted. If a new computer account is added with the same name
+as a previously deleted account name, the new computer does not have the
+previous permissions. The new account computer will be assigned a new security
+identifier (SID) and permissions and memberships will have to be added.
+
+The command may be run from the root userid or another authorized
+userid. The -H or --URL= option can be used to execute the command against
+a remote server.
+
+Example1:
+samba-tool computer delete Computer1 -H ldap://samba.samdom.example.com \
+    -Uadministrator%passw1rd
+
+Example1 shows how to delete a computer in the domain against a remote LDAP
+server. The -H parameter is used to specify the remote target server. The
+--computername= and --password= options are used to pass the computername and
+password of a computer that exists on the remote server and is authorized to
+issue the command on that server.
+
+Example2:
+sudo samba-tool computer delete Computer2
+
+Example2 shows how to delete a computer in the domain against the local server.
+sudo is used so a computer may run the command as root.
+
+"""
+    synopsis = "%prog <computername> [options]"
+
+    takes_options = [
+        Option("-H", "--URL", help="LDB URL for database or target server",
+               type=str, metavar="URL", dest="H"),
+    ]
+
+    takes_args = ["computername"]
+    takes_optiongroups = {
+        "sambaopts": options.SambaOptions,
+        "credopts": options.CredentialsOptions,
+        "versionopts": options.VersionOptions,
+        }
+
+    def run(self, computername, credopts=None, sambaopts=None,
+            versionopts=None, H=None):
+        lp = sambaopts.get_loadparm()
+        creds = credopts.get_credentials(lp, fallback_machine=True)
+
+        samdb = SamDB(url=H, session_info=system_session(),
+                      credentials=creds, lp=lp)
+
+        samaccountname = computername
+        if not computername.endswith('$'):
+            samaccountname = "%s$" % computername
+
+        filter = ("(&(sAMAccountName=%s)(sAMAccountType=%u))" %
+                  (ldb.binary_encode(samaccountname),
+                   dsdb.ATYPE_WORKSTATION_TRUST))
+        try:
+            res = samdb.search(base=samdb.domain_dn(),
+                               scope=ldb.SCOPE_SUBTREE,
+                               expression=filter,
+                               attrs=["userAccountControl", "dNSHostName"])
+            computer_dn = res[0].dn
+            computer_ac = int(res[0]["userAccountControl"][0])
+            if "dNSHostName" in res[0]:
+                computer_dns_host_name = res[0]["dNSHostName"][0]
+            else:
+                computer_dns_host_name = None
+        except IndexError:
+            raise CommandError('Unable to find computer "%s"' % computername)
+
+        computer_is_workstation = (
+            computer_ac & dsdb.UF_WORKSTATION_TRUST_ACCOUNT)
+        if computer_is_workstation == False:
+            raise CommandError('Failed to remove computer "%s": '
+                               'Computer is not a workstation - removal denied'
+                               % computername)
+        try:
+            samdb.delete(computer_dn)
+            if computer_dns_host_name:
+                remove_dns_references(
+                    samdb, self.get_logger(), computer_dns_host_name,
+                    ignore_no_name=True)
+        except Exception, e:
+            raise CommandError('Failed to remove computer "%s"' %


-- 
Samba Shared Repository

Reply via email to