.. Reminder for header structure:        
  Parts (H1)          : #################### with overline
  Chapters (H2)       : ******************** with overline
  Sections (H3)       : ====================
  Subsections (H4)    : --------------------
  Subsubsections (H5) : ^^^^^^^^^^^^^^^^^^^^
  Paragraphs (H6)     : """""""""""""""""""""

.. |date| date::

.. meta::
  :description: Adding a Windows AD to your Samba Active Directory domain
  :keywords: Samba-AD, documentation, MSAD

.. _samba_add_windows_active_directory:

#########################################################
Adding a Windows AD to your Samba Active Directory domain
#########################################################

This documentation is intended for system administrators that need an MS-AD domain controller in their Samba-AD domain for technical reasons (Azure-Sync, etc.).

.. hint::

  Since version 4.20, Samba-AD manages a 2022 schema level but still with a 2016 functional level.


*******************************
Microsoft Active Directory 2016
*******************************

Preparing your Samba-AD for the future junction
===============================================

* Backup Samba-AD because irreversible changes will be made;

* Upgrade Samba to its latest available version;

* Modify [global] section of :file:`/etc/samba/smb.conf` with the following parameter on each Samba Domain Controller:

.. code-block:: ini

  ad dc functional level = 2016

* Restart Samba service on each Domain Controller:

.. code-block:: bash

  # Redhat and derivative distributions
  systemctl restart samba
  # Debian
  systemctl restart samba-ad-dc


* Install the required dependencies to join the Windows Server:

  .. code-block:: bash

    # RedHat9 and derivative distributions
    yum install patch python3-markdown
    # Debian
    apt install patch python3-markdown

* Then run the following commands, these will upgrade schema and functional level:

  .. code-block:: bash

    samba-tool domain schemaupgrade --schema=2019
    samba-tool domain functionalprep --function-level=2016
    samba-tool domain level raise --domain-level=2016 --forest-level=2016

* Check the directory database:

  .. code-block:: bash

    samba-tool dbcheck --cross-ncs --fix --yes

.. hint::

  It is possible that errors appear when launching the command the first time, just run it a second time.

* An attribute is missing in Samba that will generate error messages in the command :command:`dcdiag`.
  To solve the problem, recreate two attributes ``msDS-SDReferenceDomain in the ``cn=configuration`` partition that point to the ``rootDN`` of the Active Directory. To do this you can run the following script on the Samba-AD server:

  .. code-block:: python

    # -*- coding: utf-8 -*-
    from samba.auth import system_session
    from samba.credentials import Credentials
    from samba.samdb import SamDB
    import optparse
    import samba.getopt as options

    parser = optparse.OptionParser("/etc/samba/smb.conf")
    sambaopts = options.SambaOptions(parser)

    lp = sambaopts.get_loadparm()
    domaine = sambaopts._lp.get('realm').lower()

    creds = Credentials()
    creds.guess(lp)

    samdbloc = SamDB(session_info=system_session(),credentials=creds, lp=lp)
    listdn = list(samdbloc.search(base='cn=partitions,' + str(samdbloc.get_config_basedn()), expression=('(|(dnsroot=ForestDnsZones.%s)(dnsroot=DomainDnsZones.%s))' % (domaine,domaine) )))

    for dn in listdn:
        if not 'msDS-SDReferenceDomain' in dn :
            ldif_data = u"""dn: %s
    changetype: modify
    replace: msDS-SDReferenceDomain
    msDS-SDReferenceDomain: %s""" % (dn['dn'],str(samdbloc.get_root_basedn()))
            print(ldif_data)
            samdbloc.modify_ldif(ldif_data)

.. _join_windows_server:

Preparing and joining the Microsoft Active Directory 2016
=========================================================

.. note::

  It is recommended to use an English version of Windows Server for infrastructure services.
  This allows you to have logs in English and feel less lonely when searching on the Internet.

* If not already done, set the server to a fixed IP and configure the DNS redirector to point to the main AD;

* Install the Active Directory components. In a PowerShell console run the following commands:

  .. code-block:: text

    Install-WindowsFeature AD-Domain-Services
    Add-WindowsFeature RSAT-ADLDS
    Add-WindowsFeature RSAT-ADDS-Tools
    Add-WindowsFeature RSAT-DNS-Server
    Add-WindowsFeature RSAT-DFS-Mgmt-Con
    Add-WindowsFeature GPMC

* Now that the role is installed, promote the server to AD and set it up;

  .. note::

    The following command will open a popup that will ask for the *Domain Admins* credentials to join the server (in graphical mode), then the credentials for the AD restore mode (in text mode).

  .. note::

    Of course **modify** the values *Credential*, *DomainName*, *SiteName* and *ReplicationSourceDC*.

    There is a *back quote (`)* character at the end of each line.
    Do not remove it or PowerShell will interpret this command as multiple commands.

    .. code-block:: text

      Install-ADDSDomainController  `
        -Credential (Get-Credential "MYDOMAIN\Administrator") `
        -DomainName 'mydomain.lan' `
        -SiteName 'Default-First-Site-Name' `
        -ReplicationSourceDC srvads.mydomain.lan `
        -CreateDnsDelegation:$false  `
        -DatabasePath 'C:\Windows\NTDS' `
        -InstallDns:$true  `
        -LogPath 'C:\Windows\NTDS' `
        -NoGlobalCatalog:$false `
        -SysvolPath 'C:\Windows\SYSVOL'  `
        -NoRebootOnCompletion:$true  `
        -Force:$true

    .. note::

      At this stage, the Windows Active Directory is properly attached to the domain. However, some options need to be adjusted on the sysvol, DNS and NTP parts.

* Force the activation of the Sysvol directory on the MS-AD:

  .. code-block:: text

    Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters" -Name "SysvolReady" -Value "1"

* Copy the contents of the :file:`SYSVOL` from the Samba-AD server.
  To do this, in a file explorer, type ``\\srvads\\sysvol``, then go to the folder corresponding to your domain name (for example *ad.mydomain.lan*) and copy ``Policies`` and ``Scripts`` into :file:`C:\windows\SYSVOL\domain` (but not the domain name).
  After the copy we will have these two directories:

  * :file:`C:\windows\SYSVOL\domain\Policies`;

  * :file:`C:\windows\SYSVOL\domain\Scripts`;

.. note::

  There is a link from :file:`C:\\windows\\SYSVOL\\sysvol\\ad.mydomain.lan` to :file:`C:\\windows\\SYSVOL\\domain`.

* Restart the MS-AD server:

  .. code-block:: text

    shutdown -r -t 0

* Reverse DNS servers on the network card. The primary DNS server must be itself (``127.0.0.1``), and the secondary DNS server is the Samba-AD server (Microsoft does the opposite when joining).

* In the DNS console, change the DNS redirector to the network recursor (by default Windows sets the first domain controller as the recursor when joining).

* The change the NTP configuration in the MS-AD registry:

  .. code-block:: text

    Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters" -Name "Type" -Value  "NTP"

* Then restart the NTP service with a command prompt on the MS-AD server:

  .. code-block:: bash

    net stop w32time
    net start w32time

* Finally, update the DNS and Kerberos configuration of the Samba-AD server by updating the information about the new Windows server.
  To do this, modify the files :file:`/etc/hosts`, :file:`/etc/resolv.conf` and :file:`/etc/krb5.conf`;

.. warning::

  Samba does not support DFS-R or FRS protocols.

  Therefore, it will be necessary to manually synchronize the :file:`SYSVOL` directory each time a GPO is created or modified.


