Initial commit: MAAS-deployable Samba Active Directory domain controller

Builds a Debian image that MAAS deploys to bare metal as an Active Directory
domain controller, with first-boot automation that either creates a domain or
joins an existing one without anyone logging in. To a Windows client the result
is an AD domain: same Kerberos, same LDAP, same Group Policy, same domain join.

The request was for "primary and backup domain controllers", which is NT 4
terminology. Active Directory has no such split — every DC holds a writable copy
and any of them can service a logon. What lives on one DC at a time are the five
FSMO roles, one confusingly named "PDC Emulator". The image therefore offers
provision (create the domain) and join (add another equal DC), which is the
distinction that actually exists.

Contents:

  * customize-samba-ad.sh, run inside the packer-maas build VM: installs samba,
    winbind, Kerberos, chrony and rsync, swaps the cloud kernel for the generic
    one, and deletes every trace of a domain so one image can produce many DCs
  * adc-maas-init, a first-boot state machine covering /etc/hosts, node-unique
    identifiers, time, the resolver, provisioning or joining, the service
    switchover and a self-test that proves Kerberos issues a ticket
  * adc-sysvol-sync, a systemd timer implementing the SYSVOL workaround
  * a MAAS curtin preseed, cloud-init examples, and the release pipeline

Two findings shaped the design.

Debian builds Samba against its bundled Heimdal rather than system MIT Kerberos
— samba-ad-dc does not depend on krb5-kdc — so the AD DC role is in Samba's
supported configuration, not the experimental MIT one. The build asserts this
and fails if it ever changes.

Samba implements neither DFS-R nor FRS, so SYSVOL — where Group Policy lives —
does not replicate between DCs. Left alone, a policy created on one DC never
reaches the others and clients behave differently depending on which DC answered
them, with nothing reporting an error. adc-sysvol-sync applies the Samba wiki's
rsync workaround: sync idmap.ldb once so SID-to-uid mappings agree, rsync the
tree, then samba-tool ntacl sysvolreset because rsync carries POSIX bits while
the Windows ACLs live in AD. Without an SSH key to the source DC it exits with
an explanation rather than letting Group Policy diverge quietly.

Also carried over from maas-proxmox, where they were verified on real hardware:
the curtin-hooks that skip the kernel install and pin interface names by MAC,
Type=simple on the first-boot unit to avoid the systemd ordering cycle, and
shipping networking.service disabled so MAAS owns the network on first boot.
Specific to this image, the Debian cloud kernel is replaced with the generic one
— a bare-metal node booted with the cloud kernel can come up with no disk.

Nothing here has been built or deployed. The README says so at the top and in a
Verified status section that separates what was checked from what was not.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-09-05 14:44:37 +02:00
commit cf07702535
25 changed files with 3158 additions and 0 deletions

View File

@@ -0,0 +1,117 @@
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Builds the MAAS image and publishes it as a Gitea release.
#
# Runs daily, but only *builds* when Debian actually carries a newer samba or
# kernel than the last published release, or once the newest image passes
# MAX_AGE_DAYS. An unconditional daily build would produce a pile of
# near-identical multi-gigabyte artifacts for nothing. Trigger manually with
# `force` to rebuild anyway.
#
# The runner is registered in host mode: steps run directly on the build machine
# as root, because the build needs /dev/kvm, qemu-nbd, FUSE and root privileges.
# Anything that can dispatch a workflow here therefore has root on that machine.
name: build-image
on:
schedule:
- cron: '0 3 * * *'
workflow_dispatch:
inputs:
force:
description: 'Build even if the version has not changed'
type: boolean
default: false
concurrency:
group: build-image
cancel-in-progress: false
jobs:
build:
runs-on: maas-builder
timeout-minutes: 120
env:
GITEA_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
KEEP_RELEASES: '3'
# Rebuild even without a Proxmox version change once an image reaches this
# age, so Debian base security updates make it into the image.
MAX_AGE_DAYS: '30'
steps:
- name: Check out
# A plain clone rather than actions/checkout: the runner is in host mode
# and has no Node.js runtime for JavaScript actions.
run: |
set -eux
# Step out of the workspace before removing it: the shell starts *in*
# $GITHUB_WORKSPACE, and deleting the current working directory makes
# every later command fail with "Unable to read current working directory".
cd /
rm -rf "$GITHUB_WORKSPACE"
git clone --depth 1 --branch "$GITHUB_REF_NAME" \
"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" "$GITHUB_WORKSPACE"
cd "$GITHUB_WORKSPACE" && git log --oneline -1
- name: Decide whether to build
id: decide
run: |
set -eu
cd "$GITHUB_WORKSPACE"
./scripts/ci/decide-build.sh "$MAX_AGE_DAYS" > "$GITHUB_OUTPUT"
if [ "${{ inputs.force }}" = "true" ]; then
echo "forced by manual trigger"
sed -i 's/^build=no$/build=yes/' "$GITHUB_OUTPUT"
fi
cat "$GITHUB_OUTPUT"
- name: Build
if: steps.decide.outputs.build == 'yes'
run: |
set -eux
cd "$GITHUB_WORKSPACE"
make image
- name: Verify
if: steps.decide.outputs.build == 'yes'
run: |
set -eux
cd "$GITHUB_WORKSPACE"
make verify
- name: Assemble release artifacts
if: steps.decide.outputs.build == 'yes'
run: |
set -eu
cd "$GITHUB_WORKSPACE"
./scripts/ci/assemble-artifacts.sh "${{ steps.decide.outputs.version }}"
- name: Publish
if: steps.decide.outputs.build == 'yes'
run: |
set -eu
cd "$GITHUB_WORKSPACE"
./scripts/ci/publish-release.sh \
"${{ steps.decide.outputs.tag }}" \
"${{ steps.decide.outputs.version }}" \
dist
- name: Prune old releases
if: steps.decide.outputs.build == 'yes'
run: |
set -eu
cd "$GITHUB_WORKSPACE"
./scripts/ci/prune-releases.sh "$KEEP_RELEASES"
- name: Clean up
if: always()
run: |
# A 1.5 GB artifact per run would fill the builder otherwise.
# Runs even when an earlier step left the workspace missing, so cd out first.
cd /
rm -rf "$GITHUB_WORKSPACE/dist" "$GITHUB_WORKSPACE/build" || true
df -h / | tail -1

6
.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
/build/
*.tar.gz
*.dd.gz
OVMF_CODE.fd
OVMF_VARS.fd
.secrets/

661
LICENSE Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

270
Makefile Normal file
View File

@@ -0,0 +1,270 @@
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
# maas-samba-ad - Samba Active Directory domain controller image for MAAS
#
# Hizli baslangic (build host uzerinde, root olarak):
# sudo ./scripts/install-deps.sh
# sudo make image
# make preseed
# make upload MAAS_PROFILE=admin
#
SHELL := /bin/bash
.DEFAULT_GOAL := help
# ---------------------------------------------------------------- version settings
# Samba's AD DC comes straight from Debian - no third-party repository is
# involved, so there is nothing to pin beyond the Debian release itself.
DEBIAN_SERIES ?= trixie
DEBIAN_VERSION ?= 13
# Packages beyond the domain controller itself.
AD_EXTRA_PACKAGES ?= acl attr net-tools ldap-utils python3-gpg bind9-dnsutils \
ethtool ipmitool nvme-cli lsscsi sudo
# ---------------------------------------------------------------- imaj ayarlari
# amd64 | arm64. arm64 is wired up but has never been built or deployed -
# see "Verified status" in the README. Building arm64 on an x86_64 host means
# TCG emulation with no KVM, which is very slow; prefer a native arm64 builder.
ARCH ?= amd64
SUBARCH ?= generic
BOOT ?= uefi
TIMEOUT ?= 3h
PACKER_LOG ?= 0
# Build VM kaynaklari. Upstream sablon 4G/2CPU/2GB ile gelir; Debian cloud image
# (~3G) plus Samba and its dependencies does not fit in 4G, so we patch it.
# Sonuc tgz yalnizca kullanilan dosyalari icerdiginden buyuk disk imaji sismez.
DISK_SIZE ?= 16G
BUILD_CPUS ?= 4
BUILD_MEM ?= 4096
# --- derleme hizi -------------------------------------------------------------
# stable | daily
# stable: cloud.debian.org/.../trixie/latest (sabit URL -> packer onbellegi
# calisir, tekrarlanan derlemelerde ~350MB indirme yok, tekrarlanabilir)
# daily : upstream sablonun varsayilani (her gun degisir, onbellek isabet etmez)
DEBIAN_IMAGE_CHANNEL ?= stable
# Tarball sikistirma seviyesi. Upstream --best (9) kullaniyor; 6 belirgin daha
# hizli ve imaj yalnizca ~%2-3 buyuyor. pigz varsa cok cekirdekli calisir.
GZIP_LEVEL ?= 6
# Yerel APT onbellegi (or. apt-cacher-ng): http://10.0.2.2:3142
# Packer'in user-mode aginda build VM host'u 10.0.2.2 olarak gorur.
# Bos birakilirsa proxy kullanilmaz. Bkz: make deps-cache
APT_PROXY ?=
IMAGE_NAME ?= samba-ad-dc
IMAGE_TITLE ?= Samba AD Domain Controller (Debian $(DEBIAN_VERSION))
# ---------------------------------------------------------------- yollar
WORKDIR ?= $(CURDIR)/build
PM_REPO ?= https://github.com/canonical/packer-maas.git
# Test edilmis upstream commit'e sabitlenmistir. 'main' birakmak, upstream'de
# yapilan bir degisikligin derlemeyi haber vermeden bozmasi anlamina gelir.
# Ileri tasimak icin: PM_REF=main ile derleyip test edin, sonra yeni SHA'yi buraya yazin.
PM_REF ?= c23d5dd985f52b2eaccc893e886213a424a243a5
PM := $(WORKDIR)/packer-maas
TPL := $(PM)/debian
OVERLAY_TGZ := $(WORKDIR)/adc-maas-overlay.tar.gz
CUSTOMIZE := $(WORKDIR)/customize-samba-ad.sh
OUTPUT ?= $(WORKDIR)/$(IMAGE_NAME).tar.gz
PRESEED := $(WORKDIR)/curtin_userdata_custom_$(ARCH)_$(SUBARCH)_$(IMAGE_NAME)
# ---------------------------------------------------------------- MAAS ayarlari
MAAS_PROFILE ?= admin
MAAS_ARCH ?= $(ARCH)/$(SUBARCH)
MAAS_IMAGE_NAME ?= custom/$(IMAGE_NAME)
# MAAS snap kurulumu icin: /var/snap/maas/current/preseeds
MAAS_PRESEED_DIR ?= /var/snap/maas/current/preseeds
# UEFI firmware, keyed on the TARGET architecture - an aarch64 guest needs
# AAVMF whatever the build host is. (Upstream packer-maas keys this on the host
# architecture instead, which only works when host and target match.)
ifeq ($(strip $(ARCH)),arm64)
FW_DIR ?= /usr/share/AAVMF
FW ?= AAVMF
else
FW_DIR ?= /usr/share/OVMF
FW ?= OVMF
endif
FW_SFX ?= $(shell test -f $(FW_DIR)/$(FW)_CODE.fd && echo "" || echo "_4M")
# KVM is only usable when the host and the guest share an architecture.
# Otherwise QEMU falls back to TCG emulation, which is very slow.
HOST_IS_ARM := $(shell test "$$(uname -m)" = aarch64 && echo true || echo false)
# ---------------------------------------------------------------- hedefler
.PHONY: help deps deps-cache check-upstream print-var checkout overlay customize image verify preseed install-preseed upload clean distclean lint
help:
@echo "maas-samba-ad - Samba AD Domain Controller MAAS image"
@echo
@echo " make deps Build host bagimliliklarini kur (root gerekir)"
@echo " make deps-cache Yerel APT onbellegi kur (derlemeyi hizlandirir)"
@echo " make image Imaji derle -> $(OUTPUT) (root gerekir)"
@echo " make verify Uretilen imajin icerigini dogrula"
@echo " make check-upstream Depodaki surumleri elimizdeki imajla karsilastir"
@echo " make preseed MAAS curtin preseed dosyasini uret"
@echo " make install-preseed Preseed'i $(MAAS_PRESEED_DIR) altina kopyala (root)"
@echo " make upload Imaji MAAS'a yukle (MAAS_PROFILE=$(MAAS_PROFILE))"
@echo " make clean Ara dosyalari sil"
@echo " make distclean build/ dizinini tamamen sil"
@echo
@echo "Onemli degiskenler:"
@echo " DEBIAN_SERIES=$(DEBIAN_SERIES) IMAGE_NAME=$(IMAGE_NAME)"
@echo " ARCH=$(ARCH) BOOT=$(BOOT)"
@echo " OUTPUT=$(OUTPUT)"
deps:
./scripts/install-deps.sh
# --- packer-maas deposunu getir -----------------------------------------------
$(PM)/.git:
@mkdir -p $(WORKDIR)
git clone $(PM_REPO) $(PM)
# PM_REF bir dal, etiket ya da commit SHA olabilir.
checkout: $(PM)/.git
@cd $(PM) && git fetch -q --all --tags && git checkout -q -f $(PM_REF) \
&& (git symbolic-ref -q HEAD >/dev/null && git pull -q --ff-only || true)
@echo "packer-maas: $$(cd $(PM) && git rev-parse --short HEAD) ($(PM_REF))"
# --- imaja gomulecek overlay ---------------------------------------------------
overlay: $(OVERLAY_TGZ)
$(OVERLAY_TGZ): $(shell find overlay -type f 2>/dev/null)
@mkdir -p $(WORKDIR)
COPYFILE_DISABLE=1 tar czf $@ -C overlay --no-xattrs --exclude='.keep' .
@echo "overlay: $@ ($$(du -h $@ | cut -f1))"
# --- packer'in VM icinde calistiracagi customize script -------------------------
customize: $(CUSTOMIZE)
$(CUSTOMIZE): scripts/customize-samba-ad.sh.in $(OVERLAY_TGZ)
@mkdir -p $(WORKDIR)
@sed -e 's|@@DEBIAN_SERIES@@|$(DEBIAN_SERIES)|g' \
-e 's|@@AD_EXTRA_PACKAGES@@|$(AD_EXTRA_PACKAGES)|g' \
-e 's|@@PM_REF@@|$(PM_REF)|g' \
$< > $@
@echo '__ADC_MAAS_OVERLAY__' >> $@
@base64 < $(OVERLAY_TGZ) >> $@
@chmod +x $@
@echo "customize script: $@"
# --- imaj derleme ---------------------------------------------------------------
image: checkout $(CUSTOMIZE)
@if [ "$$(id -u)" -ne 0 ]; then echo "HATA: 'make image' root gerektirir (sudo make image)"; exit 1; fi
@command -v packer >/dev/null || { echo "HATA: packer yok, once 'make deps'"; exit 1; }
@echo "==> Sablon yamalaniyor: disk=$(DISK_SIZE) cpus=$(BUILD_CPUS) mem=$(BUILD_MEM)"
sed -i -E 's|^([[:space:]]*disk_size[[:space:]]*=[[:space:]]*).*|\1"$(DISK_SIZE)"|' $(TPL)/debian-cloudimg.pkr.hcl
sed -i -E 's|^([[:space:]]*cpus[[:space:]]*=[[:space:]]*).*|\1$(BUILD_CPUS)|' $(TPL)/debian-cloudimg.pkr.hcl
sed -i -E 's|^([[:space:]]*memory[[:space:]]*=[[:space:]]*).*|\1$(BUILD_MEM)|' $(TPL)/debian-cloudimg.pkr.hcl
ifeq ($(strip $(DEBIAN_IMAGE_CHANNEL)),stable)
@echo "==> Kararli Debian cloud image kullanilacak (packer onbellegi isabet eder)"
sed -i -E 's|/daily/latest/|/latest/|g; s|-daily\.qcow2|.qcow2|g' $(TPL)/debian-cloudimg.pkr.hcl
@grep -nE 'iso_url|iso_checksum' $(TPL)/debian-cloudimg.pkr.hcl
endif
sed -i -E 's|--best --force|-$(GZIP_LEVEL) --force|' $(PM)/scripts/fuse-tar-root
@grep -nE 'disk_size|^ cpus|^ memory' $(TPL)/debian-cloudimg.pkr.hcl
cp -v $(FW_DIR)/$(FW)_CODE$(FW_SFX).fd $(TPL)/OVMF_CODE.fd
cp -v $(FW_DIR)/$(FW)_VARS$(FW_SFX).fd $(TPL)/OVMF_VARS.fd
ifeq ($(strip $(ARCH)),arm64)
# AAVMF images must be padded to 64 MiB for QEMU's arm64 "virt" machine.
truncate -s 64m $(TPL)/OVMF_CODE.fd
truncate -s 64m $(TPL)/OVMF_VARS.fd
endif
rm -rf $(TPL)/output-cloudimg $(TPL)/seeds-cloudimg.iso
cd $(TPL) && PACKER_LOG=$(PACKER_LOG) packer init .
cd $(TPL) && PACKER_LOG=$(PACKER_LOG) packer build \
-var debian_series=$(DEBIAN_SERIES) \
-var debian_version=$(DEBIAN_VERSION) \
-var architecture=$(ARCH) \
-var boot_mode=$(BOOT) \
-var ovmf_suffix=$(FW_SFX) \
-var host_is_arm=$(HOST_IS_ARM) \
-var timeout=$(TIMEOUT) \
-var customize_script=$(CUSTOMIZE) \
-var filename=$(OUTPUT) \
-var http_proxy=$(APT_PROXY) \
.
@ls -lh $(OUTPUT)
# --- MAAS preseed ---------------------------------------------------------------
preseed: $(PRESEED)
$(PRESEED): maas/curtin_userdata_custom.in
@mkdir -p $(WORKDIR)
@sed -e 's|@@IMAGE_NAME@@|$(IMAGE_NAME)|g' \
-e 's|@@ARCH@@|$(ARCH)|g' \
$< > $@
@echo "preseed: $@"
@echo " -> MAAS region controller uzerinde $(MAAS_PRESEED_DIR)/ altina kopyalayin"
install-preseed: $(PRESEED)
@if [ "$$(id -u)" -ne 0 ]; then echo "HATA: root gerekir"; exit 1; fi
install -D -m 0644 $(PRESEED) $(MAAS_PRESEED_DIR)/$(notdir $(PRESEED))
@echo "kuruldu: $(MAAS_PRESEED_DIR)/$(notdir $(PRESEED))"
# --- MAAS'a yukleme -------------------------------------------------------------
upload:
@test -f $(OUTPUT) || { echo "HATA: $(OUTPUT) yok, once 'make image'"; exit 1; }
maas $(MAAS_PROFILE) boot-resources create \
name='$(MAAS_IMAGE_NAME)' \
title='$(IMAGE_TITLE)' \
architecture='$(MAAS_ARCH)' \
filetype='tgz' \
content@=$(OUTPUT)
verify:
@test -f $(OUTPUT) || { echo "HATA: $(OUTPUT) yok, once 'make image'"; exit 1; }
./scripts/verify-image.sh $(OUTPUT)
# Depoda hangi surumler var, elimizdeki imaj hangi surumde?
check-upstream:
@echo "==> Available in Debian $(DEBIAN_SERIES):"
@curl -fsS http://deb.debian.org/debian/dists/$(DEBIAN_SERIES)/main/binary-$(ARCH)/Packages.gz 2>/dev/null \
| gunzip \
| awk '/^Package: (samba|samba-ad-dc|winbind)$$/{p=$$2; next} \
/^Version: /{if(p!=""){print p" "$$2; p=""}}' \
| sort -V | awk '{v[$$1]=$$2} END{for(k in v) printf " %-18s %s\n", k, v[k]}' \
|| echo " (could not reach the archive)"
@echo "==> In the local image ($(OUTPUT)):"
@if [ -f $(OUTPUT) ]; then \
tar xzf $(OUTPUT) -O ./etc/adc-maas/image-info 2>/dev/null | sed 's/^/ /' \
|| echo " (image-info unreadable)"; \
else echo " (no image - run 'make image' first)"; fi
# Yerel APT onbellegi - tekrarlanan derlemelerde ~700MB indirmeyi ortadan kaldirir.
# Kurduktan sonra: sudo make image APT_PROXY=http://10.0.2.2:3142
deps-cache:
@if [ "$$(id -u)" -ne 0 ]; then echo "HATA: root gerekir (sudo make deps-cache)"; exit 1; fi
DEBIAN_FRONTEND=noninteractive apt-get install -y apt-cacher-ng
systemctl enable --now apt-cacher-ng
@echo
@echo "Hazir. Derlemede kullanmak icin:"
@echo " sudo make image APT_PROXY=http://10.0.2.2:3142"
@echo "(10.0.2.2 = packer user-mode aginda build host'un adresi)"
# Tek bir degiskenin degerini bas - CI script'leri bunu kullanir.
# make -s print-var VAR=OUTPUT
print-var:
@echo "$($(VAR))"
lint:
@bash -n scripts/customize-samba-ad.sh.in && echo "customize-samba-ad.sh.in: OK"
@bash -n overlay/usr/local/sbin/adc-maas-init && echo "adc-maas-init: OK"
@bash -n overlay/usr/local/sbin/adc-sysvol-sync && echo "adc-sysvol-sync: OK"
@command -v shellcheck >/dev/null && shellcheck -S warning \
overlay/usr/local/sbin/adc-maas-init overlay/usr/local/sbin/adc-sysvol-sync \
scripts/install-deps.sh || true
clean:
rm -f $(OVERLAY_TGZ) $(CUSTOMIZE) $(PRESEED)
rm -rf $(TPL)/output-cloudimg $(TPL)/seeds-cloudimg.iso \
$(TPL)/OVMF_CODE.fd $(TPL)/OVMF_VARS.fd
distclean:
rm -rf $(WORKDIR)

397
README.md Normal file
View File

@@ -0,0 +1,397 @@
# maas-samba-ad
Build a Debian image that [MAAS](https://maas.io) can deploy to bare metal as an
**Active Directory domain controller**, with first-boot automation that either creates
a new domain or joins an existing one — without anyone logging in.
The domain controller is [Samba](https://www.samba.org/) in AD DC mode. To a Windows
client it is an Active Directory domain: same Kerberos, same LDAP, same Group Policy,
same `net use`, same domain join.
> **Not tested yet.** The code is written and statically checked; nothing here has been
> built or deployed. See [Verified status](#verified-status).
---
## Table of contents
- [If Active Directory is new to you](#if-active-directory-is-new-to-you)
- [What "highly available" means here](#what-highly-available-means-here)
- [The SYSVOL problem](#the-sysvol-problem)
- [How it works](#how-it-works)
- [Requirements](#requirements)
- [Quick start](#quick-start)
- [Deploying a domain](#deploying-a-domain)
- [Configuration reference](#configuration-reference)
- [Operating the domain](#operating-the-domain)
- [Build configuration](#build-configuration)
- [Traps this image works around](#traps-this-image-works-around)
- [Verified status](#verified-status)
- [Licensing](#licensing)
---
## If Active Directory is new to you
Skip this if it isn't.
**There is no "primary" and "backup" domain controller.** That is Windows NT 4
terminology, retired in 2000. In Active Directory every DC holds a full, writable copy
of the directory and they replicate to each other. Any DC can service any logon.
What *does* live on exactly one DC at a time are the five **FSMO roles** — small
coordination duties such as allocating blocks of security identifiers. One of them is
called "PDC Emulator", which is where the old name survives and where most of the
confusion comes from. Losing the DC that holds them does not cost you the domain; you
seize the roles onto another DC and carry on.
So this image has two modes, and they map to the real distinction:
| Mode | What it does |
|---|---|
| `AD_MODE=provision` | Creates the domain. The first DC, and initially the FSMO holder |
| `AD_MODE=join` | Joins the existing domain as another equal DC |
**A domain is not one service.** These have to work together, and all of them except
the clock come from the single `samba` daemon:
| Piece | Why it matters |
|---|---|
| **LDAP** | The directory itself: users, groups, computers, policy links |
| **Kerberos** | Issues the tickets clients actually authenticate with |
| **DNS** | Clients find domain controllers through SRV records. AD without working DNS does not function at all — this is the single most common cause of a broken domain |
| **SMB** | Serves `SYSVOL` and `NETLOGON`, the shares Group Policy and logon scripts live in |
| **Time** | Kerberos refuses tickets when clocks differ by more than five minutes. The symptom is logins failing for no visible reason |
The image installs and wires up all of them.
**Names you have to choose.** Two, and they are awkward to change later:
- **Realm** — your DNS domain in uppercase, e.g. `AD.EXAMPLE.COM`. Use a domain you
control. Do not use your public web domain, and never a bare `.local` (it collides
with mDNS).
- **NetBIOS name** — the short legacy form, e.g. `EXAMPLE`. Uppercase, at most 15
characters, no dots. Conventionally the realm's first label.
**Passwords.** Active Directory enforces complexity by default: at least seven
characters, and three of upper case, lower case, digit, symbol. A weak
`AD_ADMIN_PASSWORD` makes provisioning fail with an error that does not say so.
---
## What "highly available" means here
Availability in an AD domain comes from having more than one DC, not from clustering
anything. Concretely:
1. **At least two DCs.** Two survives losing one. Three is better, because with two you
have no majority when one is down and some operations get cautious.
2. **Each DC runs DNS**, serving the same AD-integrated zones. This image does that
automatically — every DC answers for the domain.
3. **Clients must be told about both.** Hand out both DC addresses as DNS servers over
DHCP. A client that only knows one DC has no redundancy no matter how many you run.
In MAAS that is the subnet's DNS server list.
4. **Time comes from the DCs.** Set `AD_NTP_ALLOW` so members can use them.
5. **SYSVOL has to be replicated.** This is the part that does not happen by itself —
see below.
The FSMO roles sit on the first DC. If it dies permanently you seize them; the domain
keeps authenticating in the meantime.
---
## The SYSVOL problem
**Read this before relying on the result.**
`SYSVOL` is the share holding Group Policy objects and logon scripts. Windows replicates
it between DCs using DFS-R. **Samba implements neither DFS-R nor its predecessor FRS**,
so a policy created on one DC never reaches the others by itself. Clients then behave
differently depending on which DC happened to answer them — and nothing reports an
error.
The [Samba wiki's](https://wiki.samba.org/index.php/SysVol_replication_(DFS-R))
workaround is to copy SYSVOL with rsync and then reapply the ACLs from AD. This image
ships that as [`adc-sysvol-sync`](overlay/usr/local/sbin/adc-sysvol-sync), run by a
systemd timer:
1. Sync `idmap.ldb` from the source DC once. Without it the same file shows different
ownership on different DCs, because the SID-to-uid mapping differs.
2. `rsync -aAX --delete` the SYSVOL tree.
3. `samba-tool ntacl sysvolreset`, because rsync carries POSIX bits while the Windows
ACLs live in AD and have to be reapplied — skip it and clients get access-denied on
Group Policy.
It needs a root SSH key on the joining DC that is authorised on the source DC. If there
isn't one, the sync **exits with an explanation instead of pretending to work**. That is
deliberate: silent SYSVOL divergence is worse than a visible failure.
This is a real limitation of Samba, not of this image. If you need genuine multi-master
SYSVOL replication, you need Windows DCs.
---
## How it works
```
Debian 13 cloud image (qcow2, official)
├─ canonical/packer-maas, "debian" template (QEMU + KVM)
│ ├─ cloud-init / netplan / curtin compatibility [upstream]
│ └─ customize-samba-ad.sh [this repo]
│ ├─ samba, samba-ad-dc, winbind, krb5, chrony, rsync
│ ├─ swap the cloud kernel for the generic one
│ ├─ delete every trace of a domain
│ ├─ mask smbd/nmbd/winbind, disable networking.service
│ └─ install the overlay (adc-maas-init, sysvol sync, curtin-hooks)
└─ samba-ad-dc.tar.gz ──► maas boot-resources create
```
On first boot `adc-maas-init` runs these stages, each once, recorded in
`/var/lib/adc-maas/<stage>.done`:
| Stage | What it does |
|---|---|
| `hosts` | Makes the FQDN resolve to the management address. Samba insists on this |
| `identity` | Regenerates anything that must not be shared between clones |
| `time` | Configures chrony, including the signed-NTP socket Windows clients expect |
| `resolver` | Points DNS at the DC being joined, then at itself once it serves DNS |
| `domain` | `samba-tool domain provision` or `samba-tool domain join` |
| `services` | Masks the standalone file-server daemons, starts `samba-ad-dc` |
| `sysvol` | Sets up SYSVOL replication where it is needed |
| `selftest` | Proves Kerberos issues a ticket and SMB answers |
A stage that fails leaves the service failed and is retried on the next boot, rather
than leaving a half-configured domain controller that looks fine.
---
## Requirements
**Build host:** Ubuntu 22.04+ with access to `/dev/kvm`, 4+ vCPU, 8+ GB RAM, 25+ GB
free. If it is a VM, nested virtualization must be on and the CPU type must pass the
flags through (on Proxmox: `--cpu host`).
**Deployment:** MAAS 3.2+ with the curtin preseed from this repository installed on the
region controller.
---
## Quick start
```bash
sudo ./scripts/install-deps.sh # packer, qemu, ovmf, nbdkit, fuse2fs
sudo make image # -> build/samba-ad-dc.tar.gz
make verify
make preseed
sudo make install-preseed # onto the MAAS region controller
make upload MAAS_PROFILE=admin
```
**The preseed is not optional.** Without it the deployment fails — see
[Traps](#traps-this-image-works-around).
---
## Deploying a domain
### The first DC
```bash
maas $PROFILE machine deploy $SYSTEM_ID \
osystem=custom distro_series=samba-ad-dc \
user_data="$(base64 -w0 maas/examples/01-first-dc.yaml)"
```
with, in that user-data:
```
AD_MODE=provision
AD_REALM=AD.EXAMPLE.COM
AD_DOMAIN=EXAMPLE
AD_ADMIN_PASSWORD='...'
AD_DNS_FORWARDER=192.0.2.1
AD_NTP_ALLOW=192.0.2.0/24
```
### Every DC after that
```
AD_MODE=join
AD_REALM=AD.EXAMPLE.COM
AD_DOMAIN=EXAMPLE
AD_JOIN_PEER=192.0.2.10 # an existing DC
AD_ADMIN_PASSWORD='...' # a Domain Admin on it
AD_SYSVOL_SYNC=on
AD_SYSVOL_SOURCE=192.0.2.10
```
Full examples: [`maas/examples/`](maas/examples/).
### Then
Point the subnet's DHCP at **both** DCs for DNS, and check the domain from either:
```bash
samba-tool domain level show
samba-tool drs showrepl # replication between DCs
samba-tool fsmo show # who holds the five roles
```
### Security notes
- `AD_ADMIN_PASSWORD` is plaintext in MAAS user-data, where anyone with MAAS access can
read it. Use a short-lived password and change it after the domain is up. It is
scrubbed from `conf.d` on the node once the domain is running
(`AD_WIPE_SECRETS=true`), but not from MAAS.
- The SYSVOL SSH key, if you supply one through user-data, has the same exposure. Use a
key dedicated to that job and authorised for nothing else.
---
## Configuration reference
Defaults live in [`/etc/adc-maas/adc-maas.conf`](overlay/etc/adc-maas/adc-maas.conf),
which documents every option. Per-node settings go in `/etc/adc-maas/conf.d/*.conf`,
written by cloud-init from the user-data MAAS supplies, and override the defaults.
| Option | Default | Meaning |
|---|---|---|
| `AD_MODE` | `none` | `none`, `provision` or `join` |
| `AD_REALM` | *(empty)* | Kerberos realm, uppercase DNS domain |
| `AD_DOMAIN` | *(empty)* | NetBIOS name, uppercase, ≤15 chars |
| `AD_ADMIN_PASSWORD` | *(empty)* | Administrator password / join credentials |
| `AD_ADMIN_PASSWORD_FILE` | *(empty)* | Read it from a file instead |
| `AD_JOIN_USER` | `Administrator` | Account used to join |
| `AD_JOIN_PEER` | *(empty)* | An existing DC to join |
| `AD_DNS_BACKEND` | `SAMBA_INTERNAL` | Or `BIND9_DLZ` if you need BIND's features |
| `AD_DNS_FORWARDER` | *(empty)* | Where to send queries the DC is not authoritative for |
| `AD_FUNCTION_LEVEL` | `2008_R2` | Domain and forest functional level |
| `AD_SITE` | `Default-First-Site-Name` | AD site to join |
| `AD_USE_RFC2307` | `true` | Store POSIX uid/gid in AD |
| `AD_INTERFACE` | *(auto)* | Interface Samba binds to |
| `AD_NTP_ALLOW` | *(empty)* | Subnet allowed to use this DC as a time source |
| `AD_SYSVOL_SYNC` | `auto` | `auto` (on for joined DCs), `on`, `off` |
| `AD_SYSVOL_SOURCE` | *(join peer)* | DC to pull SYSVOL from |
| `AD_SYSVOL_INTERVAL` | `5min` | How often |
| `AD_WAIT` / `AD_RETRIES` | `900` / `5` | Waiting for the peer, and join attempts |
| `AD_WIPE_SECRETS` | `true` | Scrub the password from `conf.d` afterwards |
| `AD_ENABLED` | `true` | Set false to disable all first-boot automation |
---
## Operating the domain
```bash
# Users and groups
samba-tool user create alice
samba-tool group addmembers "Domain Admins" alice
# Health
samba-tool drs showrepl # is replication working?
samba-tool dns query localhost <realm> @ ALL -U Administrator
# Which DC holds the FSMO roles
samba-tool fsmo show
# The first DC is gone for good: take the roles onto this one
samba-tool fsmo seize --role=all
# A DC that will never come back has to be removed from the directory,
# or replication keeps trying to reach it
samba-tool domain demote --remove-other-dead-server=<name>
```
Windows clients join the domain exactly as they would against a Windows DC, provided
their DNS points at a DC.
---
## Build configuration
| Variable | Default | Meaning |
|---|---|---|
| `DEBIAN_SERIES` / `DEBIAN_VERSION` | `trixie` / `13` | Debian release |
| `AD_EXTRA_PACKAGES` | `acl attr ldap-utils …` | Extra packages baked in |
| `IMAGE_NAME` | `samba-ad-dc` | MAAS name and preseed filename |
| `ARCH` / `BOOT` | `amd64` / `uefi` | Architecture and boot mode |
| `DISK_SIZE` | `16G` | Build VM disk; upstream's 4G is too small |
| `PM_REF` | pinned SHA | `canonical/packer-maas` revision |
| `APT_PROXY` | *(empty)* | Local APT cache — see `make deps-cache` |
`make check-upstream` compares the `samba` version in Debian against the image you have,
without building anything.
---
## Traps this image works around
These are the same class of problem as in the sibling
[maas-proxmox](https://github.com/ilkermanap/maas-proxmox) project, and each fails
**silently**:
1. **`kernel: null` in the preseed.** Some curtin versions shipped with MAAS crash on
it. The image carries `/curtin/curtin-hooks` instead, which disables the kernel
install and works regardless of curtin version.
2. **Interface renaming.** MAAS records the interface name it saw in its Ubuntu
commissioning environment; Debian's udev may name the same card differently, and
cloud-init then fails to rename it and leaves the link **down**. `curtin-hooks`
pins MAC-to-name mappings so udev gets it right from the start.
3. **systemd ordering.** Ordering the first-boot unit after `cloud-final.service` while
it is `WantedBy=multi-user.target` forms a cycle, and systemd resolves it by deleting
the unit's start job — it never runs and reports nothing. The unit is `Type=simple`
with no cloud-init ordering; the script waits for cloud-init itself.
4. **`networking.service`.** ifupdown starting with the build VM's stale interface
definition takes the real interface down before any automation runs. It ships
disabled, and MAAS owns the network.
Two more are specific to this image:
5. **The cloud kernel.** The Debian cloud image ships `linux-image-cloud-amd64`, built
for virtual machines and missing most physical-hardware drivers. A bare-metal DC
deployed with it can come up with no disk or no network. The build swaps in the
generic kernel.
6. **A domain baked into the image.** Installing the packages leaves a default
`smb.conf`. If that shipped, every machine from the image would start from the same
half-configured directory and `samba-tool domain provision` would refuse to run. The
build deletes all of it.
---
## Verified status
**Nothing in this repository has been built or deployed.** It is written and statically
checked, no more than that.
### Checked
| | |
|---|---|
| Shell syntax | `make lint` passes on every script |
| Generation | `make preseed` and `make customize` produce correct output; the embedded overlay round-trips |
| Samba capability | Debian trixie ships samba 4.22.10, and `samba-ad-dc` does **not** depend on `krb5-kdc` — so it uses the bundled Heimdal KDC, which is Samba's supported configuration for an AD DC. The build asserts this and fails if it ever changes |
| SYSVOL behaviour | Confirmed against the Samba wiki: no DFS-R, no FRS, rsync plus `ntacl sysvolreset` is the documented workaround, and `idmap.ldb` must be synced first |
| Pattern | The build pipeline, curtin hooks and first-boot state machine are adapted from [maas-proxmox](https://github.com/ilkermanap/maas-proxmox), where they were verified end to end on real infrastructure |
### Not verified
Everything else. Specifically: the image has never been built; no domain has been
provisioned or joined; SYSVOL replication has never run; the self-test has never
executed; `BIND9_DLZ` was not tried; no Windows client has been joined to a domain from
this image; arm64 is untouched.
Treat the first deployment as a test, and read `journalctl -u adc-maas-init -b` on the
node.
---
## Licensing
**AGPL-3.0-or-later**, see [LICENSE](LICENSE).
The build pipeline derives from [`canonical/packer-maas`](https://github.com/canonical/packer-maas)
(AGPLv3) — the curtin preseed and `curtin-hooks` in particular — so the copyleft carries
over. The upstream template is cloned at build time, not vendored.
Samba itself is GPLv3+ and is installed from Debian, unmodified.

View File

@@ -0,0 +1,59 @@
#cloud-config
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# MAAS curtin preseed - Samba AD domain controller image
#
# Dosya adi: curtin_userdata_custom_@@ARCH@@_generic_@@IMAGE_NAME@@
# Kopyalanacak yer (MAAS snap): /var/snap/maas/current/preseeds/
# (MAAS deb paketi): /etc/maas/preseeds/
#
# Bu ad yalnizca 'custom/@@IMAGE_NAME@@' adiyla, '@@ARCH@@/generic' mimarisiyle
# yuklenen imaja uygulanir; diger ozel imajlariniz etkilenmez.
# Cekirdek kurulumu imajdaki /curtin/curtin-hooks tarafindan devre disi
# birakilir (Proxmox cekirdegi imajda hazir gelir). Asagidaki blok yalnizca
# kanca herhangi bir nedenle calismazsa devreye giren yedek yoldur.
#
# DIKKAT: burada 'kernel: null' KULLANMAYIN. MAAS ile gelen curtin
# surumlerinin bir kismi bunu desteklemiyor ve kurulum su hatayla basarisiz
# oluyor: install_kernel -> AttributeError: 'NoneType' object has no
# attribute 'get'
kernel:
package: linux-image-@@ARCH@@
fallback-package: linux-image-@@ARCH@@
mapping: {}
apt:
preserve_sources_list: true
debconf_selections:
maas: |
{{for line in str(curtin_preseed).splitlines()}}
{{line}}
{{endfor}}
late_commands:
maas: [wget, '--no-proxy', '{{node_disable_pxe_url}}', '--post-data', '{{node_disable_pxe_data}}', '-O', '/dev/null']
# Hedef sistemi /mnt altina bagla
late_01: mount --bind $TARGET_MOUNT_POINT /mnt
# MAAS datasource tanimini hedef sisteme tasi
late_02: grep -A2 datasource /etc/cloud/cloud.cfg.d/91_kernel_cmdline_url.cfg | sed 's/curtin//' | tee /mnt/etc/cloud/cloud.cfg.d/91_maas_datasource.cfg
# Debian cloud-init sablonundaki Ubuntu referanslarini duzelt
late_03: sed -i 's@ubuntu.com/ubuntu@debian.org/debian@g;s@archive@deb@g;s@ubuntu@debian@g;s@Ubuntu@Debian@g;s@security.debian.org/debian@security.debian.org@g' /mnt/etc/cloud/cloud.cfg
# zz-update-grub kancasindaki 'set -e' tuzagini kaldir
late_04: sed -i '/^set -e/{n;N;d}' /mnt/etc/kernel/postinst.d/zz-update-grub
# packer-maas'in netplan.io kontrolunu atlatmak icin koydugu sarmalayicilari sil
late_05: rm -f /usr/local/bin/dpkg-query /usr/local/bin/netplan
late_06: rm -f /mnt/usr/local/bin/dpkg-query /mnt/usr/local/bin/netplan
# Safety net: make sure the first-boot service really is enabled
late_07: chroot /mnt systemctl enable adc-maas-init.service || true
# Clear any stage markers left over from a previous run
late_08: rm -f /mnt/var/lib/adc-maas/*.done /mnt/var/lib/adc-maas/complete

View File

@@ -0,0 +1,40 @@
#cloud-config
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# The FIRST domain controller: creates the domain.
#
# In Active Directory this is not a "primary" DC in the NT 4 sense — every DC is
# an equal, writable peer. This one simply happens to run the provisioning step,
# and it starts out holding the five FSMO roles.
#
# maas $PROFILE machine deploy $SYSTEM_ID \
# osystem=custom distro_series=samba-ad-dc \
# user_data="$(base64 -w0 01-first-dc.yaml)"
write_files:
- path: /etc/adc-maas/conf.d/50-ad.conf
permissions: "0600"
owner: root:root
content: |
AD_MODE=provision
# Kerberos realm: your DNS domain in UPPERCASE. Use something you control
# and that is not your public web domain. Never a bare ".local".
AD_REALM=AD.EXAMPLE.COM
# NetBIOS name: uppercase, at most 15 characters, no dots.
AD_DOMAIN=EXAMPLE
# Becomes the domain Administrator password. Active Directory enforces
# complexity: 7+ characters, three of upper/lower/digit/symbol. A weak one
# makes provisioning fail with an unhelpful error.
AD_ADMIN_PASSWORD='CHANGE-ME-Str0ng!'
# Where the DC forwards queries it is not authoritative for. Without this
# the DC resolves your domain and nothing else.
AD_DNS_FORWARDER=192.0.2.1
# Subnet allowed to use this DC as a time source. Domain members need
# working time — Kerberos rejects a skew over five minutes.
AD_NTP_ALLOW=192.0.2.0/24

View File

@@ -0,0 +1,55 @@
#cloud-config
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# An ADDITIONAL domain controller: joins the existing domain.
#
# This is what gives the domain redundancy. Two DCs mean logons survive losing
# one of them; point clients at both as DNS servers.
write_files:
- path: /etc/adc-maas/conf.d/50-ad.conf
permissions: "0600"
owner: root:root
content: |
AD_MODE=join
AD_REALM=AD.EXAMPLE.COM
AD_DOMAIN=EXAMPLE
# An existing DC, by IP. Needed because this host cannot resolve the
# domain until it points its resolver at a DC that already serves it.
AD_JOIN_PEER=192.0.2.10
# Credentials of a Domain Admin on that DC.
AD_JOIN_USER=Administrator
AD_ADMIN_PASSWORD='CHANGE-ME-Str0ng!'
AD_DNS_FORWARDER=192.0.2.1
AD_NTP_ALLOW=192.0.2.0/24
# SYSVOL — where Group Policy lives — does not replicate by itself:
# Samba implements neither DFS-R nor FRS. This pulls it from the first DC
# over rsync and reapplies the ACLs afterwards.
#
# It needs a root SSH key here that is authorised on AD_SYSVOL_SOURCE.
# Without one the sync exits with an explanation instead of silently
# letting Group Policy diverge between DCs.
AD_SYSVOL_SYNC=on
AD_SYSVOL_SOURCE=192.0.2.10
AD_SYSVOL_INTERVAL=5min
# The private key the SYSVOL sync uses to reach the source DC. Its public
# half must be in /root/.ssh/authorized_keys on that DC.
#
# This puts a private key into MAAS user-data, where anyone with MAAS access
# can read it. Use a key generated for this purpose only, authorised for
# nothing else. If that is not acceptable, leave this out and set up SYSVOL
# replication by hand after deployment - the sync script says exactly what it
# needs and refuses to pretend it is working.
- path: /root/.ssh/id_ed25519
permissions: "0600"
owner: root:root
content: |
-----BEGIN OPENSSH PRIVATE KEY-----
REPLACE-WITH-A-KEY-DEDICATED-TO-SYSVOL-REPLICATION
-----END OPENSSH PRIVATE KEY-----

View File

@@ -0,0 +1,13 @@
#cloud-config
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Deploy the image without touching any domain — useful for staging a machine
# now and provisioning or joining later by hand.
write_files:
- path: /etc/adc-maas/conf.d/50-ad.conf
permissions: "0600"
owner: root:root
content: |
AD_MODE=none

116
overlay/curtin/curtin-hooks Executable file
View File

@@ -0,0 +1,116 @@
#!/usr/bin/env python3
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# curtin-hooks - MAAS/curtin kurulum kancasi (Proxmox VE imaji icin)
#
# Curtin, hedef sistemde /curtin/curtin-hooks varsa dahili curthooks yerine
# bu script'i calistirir (curtin.util.run_hook_if_exists).
#
# Amac: curtin'in APT uzerinden cekirdek kurmaya calismasini engellemek.
# Proxmox cekirdegi (proxmox-default-kernel) imajin icinde hazir gelir;
# curtin'in onu yeniden kurmasi gereksizdir ve dugumun deploy sirasinda
# download.proxmox.com'a erisebilmesini zorunlu kilar (izole aglarda calismaz).
#
# Not: Bunu preseed'de "kernel: null" ile yapmak mumkun degil - MAAS ile
# gelen curtin surumlerinin bir kismi bu degeri desteklemiyor ve
# install_kernel icinde AttributeError ile patliyor. Kancayi kullanmak
# curtin surumunden bagimsiz olarak calisir.
#
import shutil
import os
from curtin.commands import curthooks
from curtin.config import load_command_config
from curtin.util import load_command_environment
def disable_kernel_install():
"""curtin'in cekirdek kurulum adimini etkisiz hale getir.
Fonksiyon adi curtin surumune gore degisiyor (install_kernel ->
curthook_install_kernel), ikisini de yakaliyoruz.
"""
disabled = []
for name in ("install_kernel", "curthook_install_kernel"):
if hasattr(curthooks, name):
setattr(curthooks, name, lambda *args, **kwargs: None)
disabled.append(name)
print("curtin-hooks: cekirdek kurulumu devre disi: %s" % (disabled or "hicbiri bulunamadi"))
def pin_interface_names(config, target):
"""MAAS'in bildigi arayuz adlarini hedef sistemde MAC uzerinden sabitle.
MAAS commissioning'i Ubuntu ephemeral ortaminda yapiyor ve arayuzu orada
gordugu adla (or. enp6s18) kaydediyor. Deploy edilen Debian 13 / Proxmox
ise udev'in farkli isimlendirme semasi yuzunden ayni karti ens18 diye
adlandirabiliyor. Bu durumda cloud-init acilista arayuzu yeniden
adlandirmaya calisiyor, su hatayi aliyor:
Failed to rename devices: [busy] Error renaming
mac=... from ens18 to enp6s18
...ve arayuzu KAPALI birakiyor; dugum agini tamamen kaybediyor.
Cozum: MAC -> ad eslemesini systemd .link dosyasi olarak yaziyoruz, boylece
udev karti en bastan MAAS'in bekledigi adla olusturuyor ve yeniden
adlandirmaya hic gerek kalmiyor.
"""
net = config.get("network") or {}
pairs = []
# netplan / v2 bicimi
for name, cfg in (net.get("ethernets") or {}).items():
cfg = cfg or {}
mac = (cfg.get("match") or {}).get("macaddress")
if mac:
pairs.append((cfg.get("set-name") or name, mac))
# curtin v1 bicimi
for entry in net.get("config") or []:
if not isinstance(entry, dict) or entry.get("type") != "physical":
continue
if entry.get("name") and entry.get("mac_address"):
pairs.append((entry["name"], entry["mac_address"]))
if not pairs:
print("curtin-hooks: arayuz adi sabitlenmedi (ag yapilandirmasi bos)")
return
link_dir = os.path.join(target, "etc/systemd/network")
os.makedirs(link_dir, exist_ok=True)
for name, mac in pairs:
path = os.path.join(link_dir, "10-maas-%s.link" % name)
with open(path, "w") as fh:
fh.write(
"# MAAS tarafindan beklenen arayuz adi - pve-maas imaji\n"
"# curtin-hooks tarafindan olusturuldu.\n"
"[Match]\n"
"MACAddress=%s\n"
"\n"
"[Link]\n"
"Name=%s\n" % (mac.lower(), name)
)
print("curtin-hooks: arayuz adi sabitlendi %s -> %s" % (mac, name))
def cleanup():
"""Kancayi hedef sistemden kaldir - iz birakma."""
curtin_dir = os.path.dirname(os.path.abspath(__file__))
shutil.rmtree(curtin_dir, ignore_errors=True)
def main():
state = load_command_environment()
config = load_command_config(None, state)
target = state["target"]
disable_kernel_install()
curthooks.builtin_curthooks(config, target, state)
pin_interface_names(config, target)
cleanup()
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,108 @@
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# /etc/adc-maas/adc-maas.conf
#
# Defaults for adc-maas-init. DO NOT EDIT THIS FILE. Put per-node settings in
# /etc/adc-maas/conf.d/*.conf, which cloud-init writes from the user-data MAAS
# passes at deploy time; those values override everything here.
#
# A note on terminology, because it trips people up. "Primary" and "backup"
# domain controllers are Windows NT 4 concepts. Active Directory, from Windows
# 2000 onwards, has no such split: every DC is a writable, equal peer and they
# replicate to each other. What does live on exactly one DC at a time are the
# five FSMO roles, one of which is confusingly named "PDC Emulator".
#
# So the real distinction is not primary versus backup, it is:
#
# AD_MODE=provision the FIRST DC, which creates the domain
# AD_MODE=join every DC after that, which joins the existing domain
#
# All of them then serve logons equally. Losing the first one costs you the FSMO
# roles, which you seize onto another DC — it does not cost you the domain.
# ---------------------------------------------------------------- general
AD_ENABLED=true
# none | provision | join
AD_MODE=none
# ---------------------------------------------------------------- identity
# The Kerberos realm: your DNS domain in UPPERCASE. Use a domain you control and
# that is not your public web domain — EXAMPLE.LAN, AD.EXAMPLE.COM, and so on.
# Never use a bare ".local", which collides with mDNS.
AD_REALM=
# The NetBIOS name: the short, legacy form. Uppercase, at most 15 characters,
# no dots. Conventionally the first label of the realm.
AD_DOMAIN=
# For AD_MODE=provision this becomes the domain Administrator password.
# For AD_MODE=join these are the credentials used to join.
#
# Active Directory enforces password complexity by default: at least 7
# characters and three of upper case, lower case, digit, symbol. A weak password
# makes provisioning fail with an error that does not say so clearly.
AD_ADMIN_PASSWORD=
AD_ADMIN_PASSWORD_FILE=
AD_JOIN_USER=Administrator
# An existing DC to join, by IP or FQDN. Empty means "find one via DNS", which
# only works if this host's resolver already points at the domain.
AD_JOIN_PEER=
# ---------------------------------------------------------------- DNS
# SAMBA_INTERNAL is the Samba-provided DNS server. It is the recommended default
# and needs no separate configuration. BIND9_DLZ hands DNS to BIND with an AD
# backend, which you only want if you need BIND features such as complex views
# or DNSSEC.
AD_DNS_BACKEND=SAMBA_INTERNAL
# Where the DC sends queries it is not authoritative for. Without this the DC
# resolves your domain but nothing else.
AD_DNS_FORWARDER=
# ---------------------------------------------------------------- domain shape
# 2008_R2 is the safe default and interoperates with everything current.
# Raise it only when every DC in the domain supports the higher level.
AD_FUNCTION_LEVEL=2008_R2
AD_SITE=Default-First-Site-Name
# Store POSIX uid/gid attributes in AD. Keep this on if Linux machines will also
# authenticate against the domain; it makes uids consistent across them.
AD_USE_RFC2307=true
# ---------------------------------------------------------------- networking
# Empty means the interface holding the default route.
AD_INTERFACE=
# Subnet allowed to use this DC as an NTP source, e.g. 192.0.2.0/24.
# Domain members need working time: Kerberos rejects a skew over five minutes,
# and the usual symptom is logins failing for no visible reason.
AD_NTP_ALLOW=
# ---------------------------------------------------------------- SYSVOL
# SYSVOL is the share holding Group Policy objects and logon scripts. Windows
# replicates it between DCs with DFS-R. Samba implements neither DFS-R nor its
# predecessor FRS, so without help a policy created on one DC never reaches the
# others and clients behave differently depending on which DC answered them.
#
# The workaround, straight from the Samba wiki, is to pull SYSVOL over rsync
# from the DC holding the PDC Emulator role and then reapply the ACLs from AD.
#
# auto replicate on nodes that joined, not on the one that provisioned
# on replicate here
# off do not replicate; you are handling it another way
#
# This needs a root SSH key on this host that is authorised on the source DC.
# Without one the sync exits with an explanation instead of failing quietly.
AD_SYSVOL_SYNC=auto
AD_SYSVOL_SOURCE=
AD_SYSVOL_INTERVAL=5min
# ---------------------------------------------------------------- misc
AD_WAIT=900
AD_RETRIES=5
# Scrub AD_ADMIN_PASSWORD from conf.d once the domain is up.
AD_WIPE_SECRETS=true

View File

View File

@@ -0,0 +1,28 @@
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
[Unit]
Description=Samba AD domain controller post-deployment configuration for MAAS
Documentation=file:/etc/adc-maas/adc-maas.conf
After=network-online.target
Wants=network-online.target
ConditionPathExists=!/var/lib/adc-maas/complete
# Do NOT order this after cloud-init here.
#
# After=cloud-final.service together with WantedBy=multi-user.target forms an
# ordering cycle on this image, and systemd breaks it by deleting THIS unit's
# start job — the service then never runs and reports no error. The script waits
# for cloud-init itself instead.
[Service]
# Type=simple, not oneshot: a oneshot unit blocks multi-user.target, which
# cloud-final.service is ordered after, so waiting for cloud-init inside the
# script would deadlock. Stage tracking uses /var/lib/adc-maas/*.done anyway.
Type=simple
ExecStart=/usr/local/sbin/adc-maas-init
TimeoutStartSec=0
StandardOutput=journal+console
StandardError=journal+console
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,12 @@
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
[Unit]
Description=Replicate SYSVOL from another domain controller
Documentation=https://wiki.samba.org/index.php/SysVol_replication_(DFS-R)
After=samba-ad-dc.service
Requires=samba-ad-dc.service
ConditionPathExists=/etc/adc-maas/sysvol-sync.conf
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/adc-sysvol-sync

View File

@@ -0,0 +1,14 @@
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
[Unit]
Description=Replicate SYSVOL periodically
Documentation=https://wiki.samba.org/index.php/SysVol_replication_(DFS-R)
[Timer]
OnBootSec=3min
OnUnitActiveSec=5min
AccuracySec=30s
Unit=adc-sysvol-sync.service
[Install]
WantedBy=timers.target

View File

@@ -0,0 +1,491 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# adc-maas-init - configures a MAAS-deployed Debian node as a Samba Active
# Directory domain controller on first boot.
#
# Stages, each run once and recorded in /var/lib/adc-maas/<stage>.done:
#
# hosts the FQDN must resolve to the management address; Samba insists
# identity regenerate anything that must not be shared between clones
# time Kerberos rejects a clock skew over 5 minutes, so chrony first
# resolver a DC has to resolve its own domain
# domain provision a new domain, or join an existing one
# services hand SMB over to the samba-ad-dc daemon
# sysvol set up SYSVOL replication, which Samba does not do by itself
# selftest prove Kerberos and SMB actually answer
#
# Configuration comes from /etc/adc-maas/adc-maas.conf and, overriding it,
# /etc/adc-maas/conf.d/*.conf — which cloud-init writes from the user-data MAAS
# passes at deploy time.
#
set -uo pipefail
CONF_DIR=/etc/adc-maas
STATE_DIR=/var/lib/adc-maas
LOG_TAG=adc-maas-init
mkdir -p "$STATE_DIR" "$CONF_DIR/conf.d"
log() { echo "[$LOG_TAG] $*"; logger -t "$LOG_TAG" -- "$*" 2>/dev/null || true; }
warn() { echo "[$LOG_TAG] UYARI: $*" >&2; logger -t "$LOG_TAG" -p user.warning -- "WARN: $*" 2>/dev/null || true; }
done_flag() { echo "$STATE_DIR/$1.done"; }
is_done() { [ -e "$(done_flag "$1")" ]; }
mark_done() { date -Is > "$(done_flag "$1")"; }
# ---------------------------------------------------------------------------
load_config() {
# shellcheck disable=SC1091
[ -r "$CONF_DIR/adc-maas.conf" ] && . "$CONF_DIR/adc-maas.conf"
local f
for f in "$CONF_DIR"/conf.d/*.conf; do
[ -r "$f" ] || continue
log "loading configuration: $f"
# shellcheck disable=SC1090
. "$f"
done
AD_ENABLED="${AD_ENABLED:-true}"
AD_MODE="${AD_MODE:-none}" # none | provision | join
AD_REALM="${AD_REALM:-}" # EXAMPLE.LAN (uppercase)
AD_DOMAIN="${AD_DOMAIN:-}" # EXAMPLE (NetBIOS, <= 15 chars)
AD_ADMIN_PASSWORD="${AD_ADMIN_PASSWORD:-}"
AD_ADMIN_PASSWORD_FILE="${AD_ADMIN_PASSWORD_FILE:-}"
AD_JOIN_USER="${AD_JOIN_USER:-Administrator}"
AD_JOIN_PEER="${AD_JOIN_PEER:-}" # an existing DC; empty = find via DNS
AD_DNS_BACKEND="${AD_DNS_BACKEND:-SAMBA_INTERNAL}"
AD_DNS_FORWARDER="${AD_DNS_FORWARDER:-}"
AD_FUNCTION_LEVEL="${AD_FUNCTION_LEVEL:-2008_R2}"
AD_SITE="${AD_SITE:-Default-First-Site-Name}"
AD_USE_RFC2307="${AD_USE_RFC2307:-true}"
AD_INTERFACE="${AD_INTERFACE:-}" # empty = the default-route interface
AD_NTP_ALLOW="${AD_NTP_ALLOW:-}" # subnet allowed to use this DC as a time source
AD_WAIT="${AD_WAIT:-900}"
AD_RETRIES="${AD_RETRIES:-5}"
AD_WIPE_SECRETS="${AD_WIPE_SECRETS:-true}"
AD_SYSVOL_SYNC="${AD_SYSVOL_SYNC:-auto}" # auto | off | on
AD_SYSVOL_SOURCE="${AD_SYSVOL_SOURCE:-}" # DC to pull SYSVOL from; default = join peer
AD_SYSVOL_INTERVAL="${AD_SYSVOL_INTERVAL:-5min}"
}
admin_password() {
if [ -n "$AD_ADMIN_PASSWORD_FILE" ] && [ -r "$AD_ADMIN_PASSWORD_FILE" ]; then
head -1 "$AD_ADMIN_PASSWORD_FILE"
else
printf '%s' "$AD_ADMIN_PASSWORD"
fi
}
primary_iface() {
[ -n "$AD_INTERFACE" ] && { echo "$AD_INTERFACE"; return; }
ip -4 -o route show default 2>/dev/null \
| awk '{for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1); exit}}'
}
primary_ip() {
ip -4 -o route get 1.1.1.1 2>/dev/null \
| awk '{for(i=1;i<=NF;i++) if($i=="src"){print $(i+1); exit}}'
}
wait_for_network() {
local i
for ((i = 0; i < 120; i += 5)); do
[ -n "$(primary_ip)" ] && return 0
sleep 5
done
return 1
}
wait_for_cloud_init() {
command -v cloud-init >/dev/null 2>&1 || return 0
log "waiting for cloud-init"
# The unit deliberately carries no cloud-init ordering — see the unit file.
timeout 900 cloud-init status --wait >/dev/null 2>&1
log "cloud-init: $(cloud-init status 2>/dev/null | head -1)"
return 0
}
realm_lower() { printf '%s' "${AD_REALM,,}"; }
# ---------------------------------------------------------------------------
# hosts
# ---------------------------------------------------------------------------
stage_hosts() {
is_done hosts && return 0
local host fqdn ip keep
host="$(hostname -s)"
ip="$(primary_ip)"
[ -n "$ip" ] || { warn "no management address found"; return 1; }
if [ -n "$AD_REALM" ]; then
fqdn="${host}.$(realm_lower)"
else
fqdn="$(hostname -f 2>/dev/null || echo "$host")"
fi
log "/etc/hosts: ${ip} ${fqdn} ${host}"
cp -a /etc/hosts "$STATE_DIR/hosts.orig" 2>/dev/null || true
keep="$(grep -vE "^[[:space:]]*(127\.0\.0\.1|127\.0\.1\.1|::1|ff02::[12])[[:space:]]" /etc/hosts 2>/dev/null \
| grep -vE "[[:space:]]${host}([[:space:]]|\$)" || true)"
{
echo "127.0.0.1 localhost.localdomain localhost"
echo "${ip} ${fqdn} ${host}"
[ -n "$keep" ] && echo "$keep"
echo
echo "::1 localhost ip6-localhost ip6-loopback"
echo "ff02::1 ip6-allnodes"
echo "ff02::2 ip6-allrouters"
} > /etc/hosts
# cloud-init rewrites /etc/hosts on every boot otherwise, undoing this.
cat > /etc/cloud/cloud.cfg.d/99-adc-maas-hosts.cfg <<'EOF'
# /etc/hosts is managed by adc-maas-init.
manage_etc_hosts: false
EOF
mark_done hosts
}
# ---------------------------------------------------------------------------
# identity — nothing here may be shared between machines built from one image
# ---------------------------------------------------------------------------
stage_identity() {
is_done identity && return 0
if [ ! -s /etc/iscsi/initiatorname.iscsi ] && command -v iscsi-iname >/dev/null 2>&1; then
mkdir -p /etc/iscsi
echo "InitiatorName=$(iscsi-iname)" > /etc/iscsi/initiatorname.iscsi
chmod 0600 /etc/iscsi/initiatorname.iscsi
fi
mark_done identity
}
# ---------------------------------------------------------------------------
# time — Kerberos refuses tickets when the clock is more than five minutes out
# ---------------------------------------------------------------------------
stage_time() {
is_done time && return 0
command -v chronyd >/dev/null 2>&1 || { warn "chrony missing"; mark_done time; return 0; }
log "configuring chrony (Kerberos requires clock skew under 5 minutes)"
# ntpsigndsocket lets Windows clients use this DC as a signed NTP source,
# which is what domain members expect.
cat > /etc/chrony/conf.d/adc-maas.conf <<EOF
# Managed by adc-maas-init.
ntpsigndsocket /var/lib/samba/ntp_signd
EOF
if [ -n "$AD_NTP_ALLOW" ]; then
echo "allow ${AD_NTP_ALLOW}" >> /etc/chrony/conf.d/adc-maas.conf
else
warn "AD_NTP_ALLOW unset — domain members cannot use this DC as a time source"
fi
systemctl restart chrony >/dev/null 2>&1 || systemctl restart chronyd >/dev/null 2>&1 || true
mark_done time
}
# ---------------------------------------------------------------------------
# resolver
# ---------------------------------------------------------------------------
write_resolv() {
local ns="$1" search="$2"
[ -L /etc/resolv.conf ] && rm -f /etc/resolv.conf
{
[ -n "$search" ] && echo "search ${search}"
echo "nameserver ${ns}"
} > /etc/resolv.conf
# Otherwise cloud-init or netplan puts the old resolver back on next boot.
cat > /etc/cloud/cloud.cfg.d/99-adc-maas-resolv.cfg <<'EOF'
manage_resolv_conf: false
EOF
}
stage_resolver() {
is_done resolver && return 0
[ -n "$AD_REALM" ] || { mark_done resolver; return 0; }
# Before the domain exists locally, point at whichever DC we are joining.
# stage_domain switches this to 127.0.0.1 once Samba serves DNS here.
local ns
if [ "$AD_MODE" = "join" ] && [ -n "$AD_JOIN_PEER" ]; then
ns="$AD_JOIN_PEER"
log "resolver -> ${ns} (the DC being joined)"
else
ns="$(primary_ip)"
log "resolver -> ${ns} (this host)"
fi
cp -a /etc/resolv.conf "$STATE_DIR/resolv.conf.orig" 2>/dev/null || true
write_resolv "$ns" "$(realm_lower)"
mark_done resolver
}
# ---------------------------------------------------------------------------
# domain
# ---------------------------------------------------------------------------
stop_samba_services() {
systemctl stop samba-ad-dc smbd nmbd winbind >/dev/null 2>&1 || true
}
wait_for_peer() {
local peer="$1" i
log "waiting for ${peer}:389 (LDAP) for up to ${AD_WAIT}s"
for ((i = 0; i < AD_WAIT; i += 5)); do
if timeout 4 bash -c "exec 3<>/dev/tcp/${peer}/389" 2>/dev/null; then return 0; fi
sleep 5
done
return 1
}
configure_smb_extras() {
# samba-tool writes a minimal smb.conf; add what a DC in this setup needs.
local iface conf=/etc/samba/smb.conf
iface="$(primary_iface)"
grep -q 'adc-maas' "$conf" 2>/dev/null && return 0
python3 - "$conf" "$iface" "$AD_DNS_FORWARDER" <<'PY'
import sys
path, iface, forwarder = sys.argv[1], sys.argv[2], sys.argv[3]
lines = open(path).read().splitlines()
out, injected = [], False
for line in lines:
out.append(line)
if not injected and line.strip().lower() == "[global]":
out.append("\t# --- adc-maas ---")
if forwarder:
out.append("\tdns forwarder = %s" % forwarder)
if iface:
out.append("\tinterfaces = lo %s" % iface)
out.append("\tbind interfaces only = yes")
# Windows clients still negotiate SMB2 at minimum; refuse SMB1 outright.
out.append("\tserver min protocol = SMB2_10")
out.append("\t# --- end adc-maas ---")
injected = True
open(path, "w").write("\n".join(out) + "\n")
PY
}
link_krb5_conf() {
if [ -f /var/lib/samba/private/krb5.conf ]; then
cp -a /etc/krb5.conf "$STATE_DIR/krb5.conf.orig" 2>/dev/null || true
ln -sf /var/lib/samba/private/krb5.conf /etc/krb5.conf
fi
}
stage_domain() {
is_done domain && return 0
[ "$AD_MODE" = "none" ] && { log "AD_MODE=none, nothing to do"; mark_done domain; return 0; }
local pw; pw="$(admin_password)"
[ -n "$AD_REALM" ] || { warn "AD_REALM is required"; return 1; }
[ -n "$AD_DOMAIN" ] || { warn "AD_DOMAIN (NetBIOS name) is required"; return 1; }
[ -n "$pw" ] || { warn "AD_ADMIN_PASSWORD is required"; return 1; }
if [ -f /var/lib/samba/private/sam.ldb ]; then
log "this host already holds a domain database, skipping"
mark_done domain
return 0
fi
stop_samba_services
rm -f /etc/samba/smb.conf
local -a rfc=()
[ "$AD_USE_RFC2307" = "true" ] && rfc=(--use-rfc2307)
case "$AD_MODE" in
provision)
log "provisioning a new domain: realm=${AD_REALM} netbios=${AD_DOMAIN}"
if ! samba-tool domain provision \
--realm="$AD_REALM" \
--domain="$AD_DOMAIN" \
--server-role=dc \
--dns-backend="$AD_DNS_BACKEND" \
--function-level="$AD_FUNCTION_LEVEL" \
--adminpass="$pw" \
"${rfc[@]}"; then
warn "samba-tool domain provision failed"
warn "a common cause is AD_ADMIN_PASSWORD not meeting complexity rules"
return 1
fi
;;
join)
local peer="$AD_JOIN_PEER"
if [ -n "$peer" ]; then
wait_for_peer "$peer" || { warn "${peer} did not answer on 389"; return 1; }
else
warn "AD_JOIN_PEER unset — relying on DNS to locate a DC"
fi
local i rc=1
for ((i = 1; i <= AD_RETRIES; i++)); do
log "joining ${AD_REALM} as a domain controller (attempt ${i}/${AD_RETRIES})"
if samba-tool domain join "$AD_REALM" DC \
-U"${AD_DOMAIN}\\${AD_JOIN_USER}" \
--password="$pw" \
--dns-backend="$AD_DNS_BACKEND" \
--site="$AD_SITE"; then
rc=0; break
fi
warn "join failed, retrying in 30s"
sleep 30
done
[ "$rc" -eq 0 ] || { warn "join failed after ${AD_RETRIES} attempts"; return 1; }
;;
*)
warn "invalid AD_MODE=${AD_MODE}"
mark_done domain
return 0
;;
esac
configure_smb_extras
link_krb5_conf
mark_done domain
}
# ---------------------------------------------------------------------------
# services — Debian ships the standalone file-server daemons enabled; a DC runs
# a single samba daemon instead, and the two sets conflict.
# ---------------------------------------------------------------------------
stage_services() {
is_done services && return 0
[ -f /var/lib/samba/private/sam.ldb ] || { mark_done services; return 0; }
log "switching to the samba-ad-dc daemon"
systemctl disable --now smbd nmbd winbind >/dev/null 2>&1 || true
systemctl mask smbd nmbd winbind >/dev/null 2>&1 || true
systemctl unmask samba-ad-dc >/dev/null 2>&1 || true
systemctl enable --now samba-ad-dc >/dev/null 2>&1 || {
warn "samba-ad-dc did not start"; return 1; }
# A DC serves its own domain's DNS; point the resolver at it now.
write_resolv 127.0.0.1 "$(realm_lower)"
mark_done services
}
# ---------------------------------------------------------------------------
# sysvol — Samba implements neither DFS-R nor FRS, so SYSVOL (where Group
# Policy lives) does not replicate between DCs on its own.
# ---------------------------------------------------------------------------
stage_sysvol() {
is_done sysvol && return 0
[ -f /var/lib/samba/private/sam.ldb ] || { mark_done sysvol; return 0; }
local source="${AD_SYSVOL_SOURCE:-$AD_JOIN_PEER}"
local want="$AD_SYSVOL_SYNC"
[ "$want" = "auto" ] && { [ "$AD_MODE" = "join" ] && want=on || want=off; }
if [ "$want" != "on" ]; then
log "SYSVOL replication not enabled on this host"
[ "$AD_MODE" = "provision" ] && \
log "this DC is the replication source; additional DCs pull from it"
mark_done sysvol
return 0
fi
if [ -z "$source" ]; then
warn "AD_SYSVOL_SOURCE unset and no join peer — SYSVOL will not replicate"
warn "Group Policy changes made on other DCs will not appear here"
mark_done sysvol
return 0
fi
log "enabling SYSVOL replication from ${source} every ${AD_SYSVOL_INTERVAL}"
cat > /etc/adc-maas/sysvol-sync.conf <<EOF
# Managed by adc-maas-init.
SYSVOL_SOURCE=${source}
EOF
sed -i "s|^OnUnitActiveSec=.*|OnUnitActiveSec=${AD_SYSVOL_INTERVAL}|" \
/etc/systemd/system/adc-sysvol-sync.timer 2>/dev/null || true
systemctl daemon-reload
systemctl enable --now adc-sysvol-sync.timer >/dev/null 2>&1 \
|| warn "could not enable adc-sysvol-sync.timer"
mark_done sysvol
}
# ---------------------------------------------------------------------------
# selftest
# ---------------------------------------------------------------------------
stage_selftest() {
is_done selftest && return 0
[ -f /var/lib/samba/private/sam.ldb ] || { mark_done selftest; return 0; }
local ok=0 pw; pw="$(admin_password)"
if samba-tool domain level show >/dev/null 2>&1; then
log "domain level: $(samba-tool domain level show 2>/dev/null | tr '\n' ' ')"
else
warn "samba-tool domain level show failed"; ok=1
fi
if command -v smbclient >/dev/null 2>&1; then
if smbclient -L localhost -N >/dev/null 2>&1; then
log "SMB responds; SYSVOL and NETLOGON should be listed"
else
warn "smbclient could not list shares"; ok=1
fi
fi
if [ -n "$pw" ] && command -v kinit >/dev/null 2>&1; then
if printf '%s' "$pw" | kinit "Administrator@${AD_REALM}" >/dev/null 2>&1; then
log "Kerberos: got a ticket for Administrator@${AD_REALM}"
kdestroy >/dev/null 2>&1 || true
else
warn "kinit failed — check the clock and the DNS records"; ok=1
fi
fi
[ "$ok" -eq 0 ] || warn "self-test reported problems; see the messages above"
mark_done selftest
}
wipe_secrets() {
[ "$AD_WIPE_SECRETS" = "true" ] || return 0
local f
for f in "$CONF_DIR"/conf.d/*.conf; do
[ -r "$f" ] || continue
grep -q 'AD_ADMIN_PASSWORD' "$f" || continue
log "scrubbing credentials from $f"
sed -i -E "s/^([[:space:]]*AD_ADMIN_PASSWORD=).*/\1'<removed>'/" "$f"
done
if [ -n "$AD_ADMIN_PASSWORD_FILE" ] && [ -f "$AD_ADMIN_PASSWORD_FILE" ]; then
shred -u "$AD_ADMIN_PASSWORD_FILE" 2>/dev/null || rm -f "$AD_ADMIN_PASSWORD_FILE"
fi
}
# ---------------------------------------------------------------------------
main() {
load_config
[ "$AD_ENABLED" = "true" ] || { log "AD_ENABLED=false, doing nothing"; exit 0; }
log "starting (hostname=$(hostname -s))"
wait_for_cloud_init
load_config # cloud-init may have just written conf.d
if ! wait_for_network; then
warn "no management address; will retry on the next boot"
exit 1
fi
local failed=0
stage_hosts || failed=1
stage_identity || failed=1
stage_time || failed=1
stage_resolver || failed=1
stage_domain || failed=1
stage_services || failed=1
stage_sysvol || failed=1
stage_selftest || failed=1
if [ "$failed" -eq 0 ] \
&& is_done hosts && is_done identity && is_done time && is_done resolver \
&& is_done domain && is_done services && is_done sysvol && is_done selftest; then
wipe_secrets
date -Is > "$STATE_DIR/complete"
log "all stages complete"
else
warn "some stages did not complete; the service retries on the next boot"
warn "details: journalctl -u adc-maas-init"
exit 1
fi
}
main "$@"

View File

@@ -0,0 +1,72 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# adc-sysvol-sync - pulls SYSVOL from another domain controller.
#
# Samba implements neither DFS-R nor FRS, so the SYSVOL share — which holds
# Group Policy objects and logon scripts — does not replicate between domain
# controllers by itself. Without something like this, a policy created on one DC
# is invisible to clients that authenticate against another, and the domain
# silently behaves differently depending on which DC a client happened to reach.
#
# This is the rsync approach from the Samba wiki: pull from the DC holding the
# PDC Emulator FSMO role, then reset the POSIX ACLs from what is stored in AD.
#
# Configuration: /etc/adc-maas/sysvol-sync.conf (SYSVOL_SOURCE=<dc fqdn or ip>)
# Authentication: root SSH key to the source DC. Provide one at deploy time;
# without it this exits with a clear message rather than failing silently.
set -uo pipefail
CONF=/etc/adc-maas/sysvol-sync.conf
SYSVOL=/var/lib/samba/sysvol
LOG_TAG=adc-sysvol-sync
log() { echo "[$LOG_TAG] $*"; logger -t "$LOG_TAG" -- "$*" 2>/dev/null || true; }
warn() { echo "[$LOG_TAG] WARN: $*" >&2; logger -t "$LOG_TAG" -p user.warning -- "$*" 2>/dev/null || true; }
[ -r "$CONF" ] || { log "no $CONF, nothing to do"; exit 0; }
# shellcheck disable=SC1090
. "$CONF"
: "${SYSVOL_SOURCE:?SYSVOL_SOURCE not set in $CONF}"
[ -d "$SYSVOL" ] || { warn "$SYSVOL missing — is this host a DC?"; exit 1; }
SSH_OPTS="-o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10"
if ! ssh $SSH_OPTS "root@${SYSVOL_SOURCE}" true 2>/dev/null; then
warn "cannot reach root@${SYSVOL_SOURCE} over SSH — SYSVOL is NOT replicating"
warn "install a root SSH key on this host that is authorised on ${SYSVOL_SOURCE},"
warn "or replicate SYSVOL by some other means. Group Policy will diverge until then."
exit 1
fi
# idmap.ldb decides which POSIX uid/gid each SID maps to. If it differs between
# DCs, the same file shows different ownership depending on which DC serves it.
# The Samba wiki calls syncing it a prerequisite, not an optimisation.
if [ ! -e /var/lib/adc-maas/idmap-synced ]; then
log "syncing idmap.ldb from ${SYSVOL_SOURCE} (one time)"
if rsync -a -e "ssh $SSH_OPTS" \
"root@${SYSVOL_SOURCE}:/var/lib/samba/private/idmap.ldb" \
/var/lib/samba/private/idmap.ldb; then
mkdir -p /var/lib/adc-maas && date -Is > /var/lib/adc-maas/idmap-synced
systemctl restart samba-ad-dc >/dev/null 2>&1 || true
else
warn "idmap.ldb sync failed; uid/gid mappings may differ between DCs"
fi
fi
log "pulling SYSVOL from ${SYSVOL_SOURCE}"
if rsync -aAX --delete -e "ssh $SSH_OPTS" \
"root@${SYSVOL_SOURCE}:${SYSVOL}/" "${SYSVOL}/"; then
# rsync carries POSIX bits; the Windows ACLs come from AD and have to be
# reapplied afterwards or clients get access-denied on Group Policy.
if samba-tool ntacl sysvolreset >/dev/null 2>&1; then
log "SYSVOL synced and ACLs reset"
else
warn "sysvolreset failed — clients may be denied access to Group Policy"
exit 1
fi
else
warn "rsync failed"
exit 1
fi

View File

@@ -0,0 +1,59 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Moves the built image into dist/ under a release-friendly name and writes the
# checksum plus the corresponding-source offer that has to accompany a binary
# distribution of GPL/AGPL software.
#
# assemble-artifacts.sh <samba-version>
set -euo pipefail
cd "$(dirname "$0")/../.."
VERSION="${1:?samba version required}"
OUT=$(make -s print-var VAR=OUTPUT)
ARCH=$(make -s print-var VAR=ARCH)
[ -f "$OUT" ] || { echo "built image not found: $OUT" >&2; exit 1; }
# Named after what it is - a MAAS image carrying a Samba AD domain
# controller. Nothing here is a Microsoft or Samba product.
NAME="maas-image-samba-ad-${VERSION}-${ARCH}.tar.gz"
rm -rf dist && mkdir -p dist
mv "$OUT" "dist/${NAME}"
( cd dist && sha256sum "$NAME" > "${NAME}.sha256" )
tar xzf "dist/${NAME}" -O ./etc/adc-maas/image-info > dist/image-info.txt 2>/dev/null \
|| echo "(no image-info found)" > dist/image-info.txt
DEB_VER=$(make -s print-var VAR=DEBIAN_VERSION)
DEB_SUITE=$(make -s print-var VAR=DEBIAN_SERIES)
REPO_URL="${GITHUB_SERVER_URL:-}/${GITHUB_REPOSITORY:-}"
{
echo "# Corresponding source"
echo
echo "This image is an unmodified installation of packages from the archives listed"
echo "below. No package was patched. What is ours is the selection and the"
echo "configuration, and that is the entire content of the repository linked below."
echo
echo "Written offer, per GPLv2 section 3 and GPLv3 section 6: the complete"
echo "corresponding source for every package in this image is available from the"
echo "archive it was installed from, at the versions recorded in the image's own"
echo "package database (\`/var/lib/dpkg/status\`)."
echo
echo "| Component | Source |"
echo "|---|---|"
echo "| Debian ${DEB_VER} \"${DEB_SUITE}\" | <https://deb.debian.org/debian> — \`apt-get source <pkg>\` |"
echo "| Build recipe | <${REPO_URL}> |"
echo
echo "Samba is GPLv3+; the Debian source package carries the full terms."
echo
echo "## Image metadata"
echo
echo '```'
cat dist/image-info.txt
echo '```'
} > dist/SOURCES.md
ls -lh dist/

95
scripts/ci/decide-build.sh Executable file
View File

@@ -0,0 +1,95 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Decides whether a rebuild is worth doing, and prints the decision as
# key=value lines suitable for $GITHUB_OUTPUT.
#
# decide-build.sh [max-age-days] (default 30)
#
# A rebuild happens when any of these is true:
#
# 1. samba in the Debian suite differs from the published image
# 2. the kernel package differs — kernel security fixes do not bump samba
# 3. the newest release is older than max-age-days — most Debian security
# updates touch neither, so without a floor an image could sit unchanged
# for months while its openssl and glibc went stale
#
# Requires GITEA_API and GITEA_TOKEN in the environment.
set -euo pipefail
cd "$(dirname "$0")/../.."
MAX_AGE_DAYS="${1:-30}"
: "${GITEA_API:?GITEA_API required}"
: "${GITEA_TOKEN:?GITEA_TOKEN required}"
SUITE=$(make -s print-var VAR=DEBIAN_SERIES)
ARCH=$(make -s print-var VAR=ARCH)
# Newest version of each package we care about, in one pass over the index.
PKGS=$(curl -fsS "http://deb.debian.org/debian/dists/${SUITE}/main/binary-${ARCH}/Packages.gz" | gunzip)
newest() {
printf '%s\n' "$PKGS" \
| awk -v want="$1" '$1=="Package:" && $2==want {p=1; next} p && $1=="Version:" {print $2; p=0}' \
| sort -V | tail -1
}
UP_SAMBA=$(newest samba)
UP_KERNEL=$(newest "linux-image-${ARCH}")
[ -n "$UP_SAMBA" ] || { echo "samba not found in Debian ${SUITE}" >&2; exit 1; }
[ -n "$UP_KERNEL" ] || { echo "linux-image-${ARCH} not found" >&2; exit 1; }
echo "upstream: samba=${UP_SAMBA} linux-image=${UP_KERNEL}" >&2
# What the newest published release actually contains. image-info.txt is a few
# hundred bytes and is published with every release, so this needs no guessing
# from tag names.
LATEST=$(curl -fsS -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_API}/releases?limit=1")
INFO_URL=$(printf '%s' "$LATEST" | python3 -c '
import json, sys
r = json.load(sys.stdin)
if r:
for a in r[0].get("assets", []):
if a["name"] == "image-info.txt":
print(a["browser_download_url"]); break
')
CREATED=$(printf '%s' "$LATEST" | python3 -c '
import json, sys
r = json.load(sys.stdin); print(r[0]["created_at"] if r else "")')
PREV_SAMBA="" PREV_KERNEL=""
if [ -n "$INFO_URL" ]; then
INFO=$(curl -fsSL "$INFO_URL" || true)
PREV_SAMBA=$(printf '%s' "$INFO" | awk -F= '$1=="samba"{print $2}')
PREV_KERNEL=$(printf '%s' "$INFO" | awk -F= '$1=="kernel"{print $2}')
fi
echo "published: samba=${PREV_SAMBA:-<none>} kernel=${PREV_KERNEL:-<none>}" >&2
AGE_DAYS=99999
if [ -n "$CREATED" ]; then
AGE_DAYS=$(CREATED="$CREATED" python3 -c '
import datetime, os
c = datetime.datetime.fromisoformat(os.environ["CREATED"].replace("Z", "+00:00"))
print((datetime.datetime.now(datetime.timezone.utc) - c).days)')
echo "newest release is ${AGE_DAYS} day(s) old" >&2
fi
BUILD=no
REASON="up to date"
if [ -z "$PREV_SAMBA" ]; then
BUILD=yes; REASON="no published image yet"
elif [ "$UP_SAMBA" != "$PREV_SAMBA" ]; then
BUILD=yes; REASON="samba ${PREV_SAMBA} -> ${UP_SAMBA}"
elif [ "$UP_KERNEL" != "$PREV_KERNEL" ]; then
BUILD=yes; REASON="kernel ${PREV_KERNEL} -> ${UP_KERNEL}"
elif [ "$AGE_DAYS" -ge "$MAX_AGE_DAYS" ]; then
BUILD=yes; REASON="image is ${AGE_DAYS} days old (limit ${MAX_AGE_DAYS}) — picking up Debian updates"
fi
echo "decision: ${BUILD} (${REASON})" >&2
printf 'build=%s\n' "$BUILD"
# Debian versions carry epochs and tildes; a tag cannot.
SAFE_VER=$(printf '%s' "$UP_SAMBA" | sed 's/^[0-9]*://; s/[^A-Za-z0-9._-]/-/g')
printf 'tag=%s\n' "samba-${SAFE_VER}-$(date -u +%Y%m%d)"
printf 'version=%s\n' "$SAFE_VER"
printf 'kernel=%s\n' "$UP_KERNEL"
printf 'reason=%s\n' "$REASON"

29
scripts/ci/prune-releases.sh Executable file
View File

@@ -0,0 +1,29 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Keeps the newest N releases and deletes the rest, tags included.
# Each image is ~1.5 GB, so unbounded retention fills the server.
#
# prune-releases.sh [keep] (default 3)
#
# Requires GITEA_API and GITEA_TOKEN in the environment.
set -euo pipefail
KEEP="${1:-3}"
: "${GITEA_API:?GITEA_API required}"
: "${GITEA_TOKEN:?GITEA_TOKEN required}"
curl -fsS -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_API}/releases?limit=50" \
| KEEP="$KEEP" python3 -c '
import json, os, sys
keep = int(os.environ["KEEP"])
for r in json.load(sys.stdin)[keep:]:
print(r["id"], r["tag_name"])
' | while read -r id tag; do
echo "removing old release ${tag}"
curl -fsS -X DELETE -H "Authorization: token ${GITEA_TOKEN}" \
"${GITEA_API}/releases/${id}" || true
curl -fsS -X DELETE -H "Authorization: token ${GITEA_TOKEN}" \
"${GITEA_API}/tags/${tag}" || true
done

81
scripts/ci/publish-release.sh Executable file
View File

@@ -0,0 +1,81 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Creates a Gitea release and uploads the image, its checksum and the
# corresponding-source offer.
#
# publish-release.sh <tag> <version> <dist-dir>
#
# Requires GITEA_API and GITEA_TOKEN in the environment.
set -euo pipefail
TAG="${1:?tag required}"
VERSION="${2:?version required}"
DIST="${3:?dist directory required}"
# DIST cagiranin dizinine goreli olabilir; repo kokune gecmeden once mutlaklastir.
DIST="$(cd "$DIST" && pwd)"
# make degiskenlerini okuyabilmek icin depo koku gerekiyor.
cd "$(dirname "$0")/../.."
: "${GITEA_API:?GITEA_API required}"
: "${GITEA_TOKEN:?GITEA_TOKEN required}"
REPO_URL="${GITHUB_SERVER_URL:-}/${GITHUB_REPOSITORY:-}"
RUN="${GITHUB_RUN_NUMBER:-manual}"
SHA="${GITHUB_SHA:-}"
IMAGE=$(basename "$(ls "$DIST"/maas-image-*.tar.gz)")
MAAS_ARCH=$(make -s print-var VAR=MAAS_ARCH)
IMAGE_NAME=$(make -s print-var VAR=IMAGE_NAME)
BODY=$(cat <<BODYEOF
MAAS-deployable image of a Samba Active Directory domain controller.
- samba: \`${VERSION}\`
- Built: $(date -u +%Y-%m-%dT%H:%M:%SZ), run ${RUN}
- Verify: \`sha256sum -c ${IMAGE}.sha256\`
Upload to MAAS:
\`\`\`bash
maas \$PROFILE boot-resources create name='custom/${IMAGE_NAME}' \\
title='Samba AD DC' architecture='${MAAS_ARCH}' \\
filetype='tgz' content@=${IMAGE}
\`\`\`
The curtin preseed from this repository must also be installed on the MAAS region
controller, otherwise deployment fails — see the README.
\`SOURCES.md\` in this release carries the corresponding-source offer required by
the GPL/AGPL licences of the packages inside the image.
BODYEOF
)
PAYLOAD=$(TAG="$TAG" VERSION="$VERSION" BODY="$BODY" SHA="$SHA" python3 -c '
import json, os
print(json.dumps({
"tag_name": os.environ["TAG"],
"name": "Samba AD DC image (samba %s)" % os.environ["VERSION"],
"body": os.environ["BODY"],
"draft": False,
"prerelease": False,
"target_commitish": os.environ["SHA"],
}))')
ID=$(curl -fsS -X POST \
-H "Authorization: token ${GITEA_TOKEN}" \
-H 'Content-Type: application/json' \
-d "$PAYLOAD" "${GITEA_API}/releases" \
| python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
echo "release id: ${ID}"
for f in "$DIST"/*; do
[ -f "$f" ] || continue
echo "uploading $(basename "$f") ($(du -h "$f" | cut -f1))"
curl -fsS -X POST \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@${f}" \
"${GITEA_API}/releases/${ID}/assets?name=$(basename "$f")" >/dev/null
done
echo "published: ${REPO_URL}/releases/tag/${TAG}"

17
scripts/ci/upstream-version.sh Executable file
View File

@@ -0,0 +1,17 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Prints the newest samba version in the configured Debian suite.
set -euo pipefail
cd "$(dirname "$0")/../.."
SUITE=$(make -s print-var VAR=DEBIAN_SERIES)
ARCH=$(make -s print-var VAR=ARCH)
VER=$(curl -fsS "http://deb.debian.org/debian/dists/${SUITE}/main/binary-${ARCH}/Packages.gz" \
| gunzip \
| awk '/^Package: samba$/{p=1; next} p && /^Version: /{print $2; p=0}' \
| sort -V | tail -1)
[ -n "$VER" ] || { echo "samba not found in Debian ${SUITE}" >&2; exit 1; }
printf '%s\n' "$VER"

View File

@@ -0,0 +1,247 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# customize-samba-ad.sh - runs inside the packer-maas build VM.
#
# Installs everything a Samba Active Directory domain controller needs on top of
# the Debian cloud image, then removes every trace of domain state so the image
# is generic. The domain itself is created or joined on first boot by
# adc-maas-init, driven by the cloud-init user-data MAAS supplies.
#
# This file is a template; the Makefile fills in the @@...@@ placeholders and
# appends the overlay archive, base64 encoded, after the marker at the end.
#
# Packer runs this with expect_disconnect = true.
set -euo pipefail
DEBIAN_SUITE="@@DEBIAN_SERIES@@"
AD_EXTRA_PACKAGES="@@AD_EXTRA_PACKAGES@@"
PACKER_MAAS_REF="@@PM_REF@@"
export DEBIAN_FRONTEND=noninteractive
APT="apt-get -y -o Dpkg::Options::=--force-confold -o Dpkg::Options::=--force-confdef"
use_eatmydata() {
command -v eatmydata >/dev/null 2>&1 || return 0
APT="eatmydata ${APT}"
log "eatmydata enabled (dpkg fsync calls disabled)"
}
log() { echo "==> [ad-image] $*"; }
# ---------------------------------------------------------------------------
# 1. Unpack the overlay embedded at the end of this script
# ---------------------------------------------------------------------------
log "unpacking the overlay"
sed -n '/^__ADC_MAAS_OVERLAY__$/,$p' "$0" | tail -n +2 | base64 -d \
| tar xzf - -C / --no-same-owner --no-same-permissions
chown -R root:root /usr/local/sbin/adc-maas-init /usr/local/sbin/adc-sysvol-sync \
/etc/adc-maas /etc/systemd/system/adc-maas-init.service \
/etc/systemd/system/adc-sysvol-sync.service \
/etc/systemd/system/adc-sysvol-sync.timer /curtin
chmod 0755 /usr/local/sbin/adc-maas-init /usr/local/sbin/adc-sysvol-sync
chmod 0755 /curtin /curtin/curtin-hooks
chmod 0644 /etc/adc-maas/adc-maas.conf
mkdir -p /etc/adc-maas/conf.d /var/lib/adc-maas
# ---------------------------------------------------------------------------
# 2. The build hostname has to resolve while packages configure themselves
# ---------------------------------------------------------------------------
BUILD_HOST="$(hostname -s)"
BUILD_IP="$(ip -4 -o route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src") print $(i+1)}' | head -1)"
: "${BUILD_IP:=127.0.1.1}"
log "build hostname=${BUILD_HOST} ip=${BUILD_IP}"
cp -a /etc/hosts /etc/hosts.ad-image-backup
sed -i "/[[:space:]]${BUILD_HOST}\([[:space:]]\|$\)/d" /etc/hosts
echo "${BUILD_IP} ${BUILD_HOST}.local ${BUILD_HOST}" >> /etc/hosts
hostname -f || echo "WARNING: hostname -f does not resolve" >&2
# ---------------------------------------------------------------------------
# 3. Keep the MAAS-compatible cloud-init packer-maas installed
# ---------------------------------------------------------------------------
log "holding the cloud-init package"
apt-mark hold cloud-init || true
apt-get update
$APT install eatmydata || true
use_eatmydata
log "full-upgrade"
$APT full-upgrade
# ---------------------------------------------------------------------------
# 4. Answer the questions the packages would otherwise ask
# ---------------------------------------------------------------------------
# samba-common would offer to take WINS settings from DHCP, which is wrong for
# a DC. krb5-config wants a realm; the real one is not known until first boot,
# and adc-maas-init replaces /etc/krb5.conf with Samba's own anyway.
debconf-set-selections <<EOF
samba-common samba-common/dhcp boolean false
samba-common samba-common/do_debconf boolean false
krb5-config krb5-config/default_realm string EXAMPLE.LAN
krb5-config krb5-config/add_servers_realm string EXAMPLE.LAN
krb5-config krb5-config/read_conf boolean true
EOF
# ---------------------------------------------------------------------------
# 5. Defer initramfs regeneration until the end
# ---------------------------------------------------------------------------
log "diverting update-initramfs for the duration of the install"
dpkg-divert --local --rename --add /usr/sbin/update-initramfs >/dev/null
ln -sf /bin/true /usr/sbin/update-initramfs
# ---------------------------------------------------------------------------
# 6. The domain controller itself
#
# What an Active Directory domain actually consists of, all of it served by the
# single samba daemon unless noted:
#
# LDAP the directory: users, groups, computers, policy links
# Kerberos the KDC that issues the tickets clients authenticate with
# DNS AD is unusable without it — clients find DCs through SRV records
# SMB the SYSVOL and NETLOGON shares, where Group Policy lives
# NTP chrony; Kerberos rejects a clock skew over five minutes
# ---------------------------------------------------------------------------
log "installing the Samba AD domain controller"
$APT install \
samba samba-ad-dc samba-ad-provision samba-dsdb-modules \
winbind libnss-winbind libpam-winbind \
smbclient ldb-tools \
krb5-user \
chrony \
rsync
if [ -n "${AD_EXTRA_PACKAGES}" ]; then
log "installing extra packages: ${AD_EXTRA_PACKAGES}"
# shellcheck disable=SC2086
$APT install ${AD_EXTRA_PACKAGES}
fi
log "installed versions:"
dpkg-query -W -f='${Package} ${Version}\n' samba samba-ad-dc winbind krb5-user chrony || true
# Confirm this Samba can actually be a DC. Debian builds Samba against its
# bundled Heimdal; a build against system MIT Kerberos would make the AD DC role
# experimental, and samba-ad-dc would then pull in krb5-kdc.
if dpkg-query -W -f='${Depends}' samba-ad-dc 2>/dev/null | grep -q 'krb5-kdc'; then
echo "ERROR: this samba-ad-dc depends on the MIT KDC; the AD DC role is" >&2
echo " experimental in that configuration and is not used here." >&2
exit 1
fi
log "samba-ad-dc uses the bundled Heimdal KDC (the supported configuration)"
# ---------------------------------------------------------------------------
# 6b. Swap the cloud kernel for the generic one
#
# The Debian cloud image ships linux-image-cloud-amd64, which is built for
# virtual machines and leaves out most physical-hardware drivers. This image is
# deployed to bare metal by MAAS, so it needs the generic kernel or the node may
# come up with no disk or no network. curtin does not install a kernel here
# (see /curtin/curtin-hooks), so whatever is in the image is what boots.
# ---------------------------------------------------------------------------
DEB_ARCH="$(dpkg --print-architecture)"
log "installing the generic kernel (linux-image-${DEB_ARCH})"
$APT install "linux-image-${DEB_ARCH}"
CLOUD_KERNELS="$(dpkg-query -W -f='${Package}\n' 'linux-image-*cloud*' 2>/dev/null | grep -E '^linux-image' || true)"
if [ -n "${CLOUD_KERNELS}" ]; then
log "removing the cloud-only kernel: ${CLOUD_KERNELS}"
# shellcheck disable=SC2086
$APT purge ${CLOUD_KERNELS} || true
fi
$APT autoremove --purge || true
log "restoring update-initramfs and running it once"
rm -f /usr/sbin/update-initramfs
dpkg-divert --local --rename --remove /usr/sbin/update-initramfs >/dev/null
update-initramfs -u -k all
update-grub
# ---------------------------------------------------------------------------
# 7. Remove every trace of a domain
#
# Installing the packages leaves a default smb.conf and can leave TDB state. If
# any of it shipped in the image, every machine deployed from it would start
# from the same half-configured directory, and `samba-tool domain provision`
# would refuse to run at all.
# ---------------------------------------------------------------------------
log "clearing domain state so the image is generic"
systemctl stop samba-ad-dc smbd nmbd winbind 2>/dev/null || true
rm -f /etc/samba/smb.conf
rm -rf /var/lib/samba/private/* /var/lib/samba/sysvol/*
find /var/lib/samba -maxdepth 1 -name '*.tdb' -delete 2>/dev/null || true
find /var/cache/samba -type f -delete 2>/dev/null || true
rm -f /etc/krb5.keytab
# The standalone file-server daemons conflict with the AD DC daemon. Mask them
# now; adc-maas-init unmasks and starts samba-ad-dc once a domain exists.
systemctl disable smbd nmbd winbind 2>/dev/null || true
systemctl mask smbd nmbd winbind 2>/dev/null || true
systemctl disable samba-ad-dc 2>/dev/null || true
# Node-unique, must not be shared between machines built from this image.
rm -f /etc/iscsi/initiatorname.iscsi
rm -f /root/.ssh/known_hosts /etc/ssh/ssh_known_hosts
# ---------------------------------------------------------------------------
# 8. Leave the network to MAAS on the first boot
#
# ifupdown/ifupdown2 writes the build VM's interface name into
# /etc/network/interfaces. On a deployed node MAAS configures the network
# through netplan and systemd-networkd; if ifupdown also starts, it takes the
# real interface down using that stale definition and the node loses its network
# before any of our automation runs.
# ---------------------------------------------------------------------------
log "disabling networking.service (MAAS owns the network on first boot)"
cat > /etc/network/interfaces <<'EOF'
# Left deliberately minimal. The network on a deployed node is configured by
# MAAS through netplan and systemd-networkd.
auto lo
iface lo inet loopback
source /etc/network/interfaces.d/*
EOF
rm -f /etc/network/interfaces.d/* /etc/network/interfaces.new 2>/dev/null || true
systemctl disable networking.service 2>/dev/null || true
# ---------------------------------------------------------------------------
# 9. First-boot service, persistent logs, image metadata
# ---------------------------------------------------------------------------
log "enabling adc-maas-init.service"
systemctl daemon-reload
systemctl enable adc-maas-init.service
# The first boot can reboot once, and a volatile journal loses everything that
# happened before it — including why a stage failed.
log "enabling a persistent journal"
mkdir -p /var/log/journal
systemd-tmpfiles --create --prefix /var/log/journal 2>/dev/null || true
log "writing /etc/adc-maas/image-info"
{
echo "build_date=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "debian_suite=${DEBIAN_SUITE}"
echo "packer_maas_ref=${PACKER_MAAS_REF}"
dpkg-query -W -f='${Package}=${Version}\n' samba samba-ad-dc winbind krb5-user 2>/dev/null
echo "kernel=$(ls -1 /boot/vmlinuz-* 2>/dev/null | sed 's|.*/vmlinuz-||' | head -1)"
} > /etc/adc-maas/image-info
cat /etc/adc-maas/image-info
# ---------------------------------------------------------------------------
# 10. Clean up
# ---------------------------------------------------------------------------
log "cleaning up"
mv /etc/hosts.ad-image-backup /etc/hosts
$APT clean
rm -rf /var/lib/apt/lists/*
find /var/log/journal -mindepth 1 -delete 2>/dev/null || true
rm -rf /var/log/*.gz /var/log/*.1
: > /var/log/wtmp || true
: > /var/log/btmp || true
cloud-init clean --logs || true
log "image ready: Samba AD DC on Debian ${DEBIAN_SUITE}"
exit 0
# Everything after this marker is the base64 overlay archive the Makefile appends.

65
scripts/install-deps.sh Executable file
View File

@@ -0,0 +1,65 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# install-deps.sh - Ubuntu 22.04+ build host'una packer-maas bagimliliklarini kurar.
#
# Kullanim: sudo ./scripts/install-deps.sh
#
set -euo pipefail
if [ "$(id -u)" -ne 0 ]; then
echo "Bu script root olarak calistirilmali: sudo $0" >&2
exit 1
fi
. /etc/os-release
if [ "${ID:-}" != "ubuntu" ] && [ "${ID_LIKE:-}" != "debian" ]; then
echo "UYARI: Bu script Ubuntu/Debian icin yazildi (bulunan: ${PRETTY_NAME:-bilinmiyor})." >&2
fi
export DEBIAN_FRONTEND=noninteractive
echo "==> Temel paketler kuruluyor"
apt-get update
apt-get install -y --no-install-recommends \
ca-certificates curl gpg git make parted pigz jq \
qemu-system-x86 qemu-utils ovmf cloud-image-utils \
libnbd-bin nbdkit fuse2fs cpu-checker
# arm64 hedefi icin ek paketler. Varsayilan olarak kurulmaz: x86_64 host'ta
# arm64 derlemek TCG emulasyonu demektir (KVM yok) ve cok yavastir. Bu yol
# hic denenmedi - README'deki "Verified status" bolumune bakin.
if [ "${WITH_ARM64:-0}" = "1" ]; then
echo "==> arm64 hedefi icin ek paketler (WITH_ARM64=1)"
apt-get install -y --no-install-recommends qemu-system-arm qemu-efi-aarch64
fi
echo "==> HashiCorp APT deposu ekleniyor (packer)"
install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://apt.releases.hashicorp.com/gpg \
| gpg --dearmor --yes -o /etc/apt/keyrings/hashicorp-archive-keyring.gpg
chmod 0644 /etc/apt/keyrings/hashicorp-archive-keyring.gpg
cat > /etc/apt/sources.list.d/hashicorp.list <<REPO
deb [signed-by=/etc/apt/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com ${UBUNTU_CODENAME:-${VERSION_CODENAME}} main
REPO
apt-get update
apt-get install -y packer
echo "==> KVM kontrolu"
if ! kvm-ok; then
echo "HATA: KVM kullanilamiyor. VM'de nested virtualization acik mi? (Proxmox: cpu=host)" >&2
exit 1
fi
# Build root olarak kosuyor ama kullaniciyi da kvm grubuna alalim.
TARGET_USER="${SUDO_USER:-}"
if [ -n "$TARGET_USER" ] && [ "$TARGET_USER" != "root" ]; then
adduser "$TARGET_USER" kvm >/dev/null 2>&1 || true
fi
echo
echo "==> Hazir. Surumler:"
packer version
qemu-system-x86_64 --version | head -1

106
scripts/verify-image.sh Executable file
View File

@@ -0,0 +1,106 @@
#!/bin/bash
# Copyright (C) 2026 Ilker Manap
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# verify-image.sh - checks that the produced MAAS tarball contains what it should.
#
# Kullanim: ./scripts/verify-image.sh build/samba-ad-dc.tar.gz
#
set -uo pipefail
IMG="${1:-}"
[ -n "$IMG" ] && [ -f "$IMG" ] || { echo "Usage: $0 <imaj.tar.gz>" >&2; exit 2; }
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
echo "==> Imaj: $IMG ($(du -h "$IMG" | cut -f1))"
echo "==> Icerik listesi cikariliyor..."
tar tzf "$IMG" > "$TMP/list" || { echo "HATA: arsiv okunamadi"; exit 1; }
echo " $(wc -l < "$TMP/list") giris"
pass=0; fail=0
have() { grep -qx "\./$1" "$TMP/list" || grep -q "^\./$1$" "$TMP/list"; }
present() { grep -q "^\./$1" "$TMP/list"; }
check() {
local desc="$1" cond="$2"
if eval "$cond"; then
printf ' [ OK ] %s\n' "$desc"; pass=$((pass+1))
else
printf ' [FAIL] %s\n' "$desc"; fail=$((fail+1))
fi
}
echo
echo "=== Files that must be present ==="
check "adc-maas-init" 'present "usr/local/sbin/adc-maas-init"'
check "adc-sysvol-sync" 'present "usr/local/sbin/adc-sysvol-sync"'
check "adc-maas.conf" 'present "etc/adc-maas/adc-maas.conf"'
check "image-info" 'present "etc/adc-maas/image-info"'
check "adc-maas-init.service" 'present "etc/systemd/system/adc-maas-init.service"'
check "unit enabled for multi-user.target" 'present "etc/systemd/system/multi-user.target.wants/adc-maas-init.service"'
check "adc-sysvol-sync.timer" 'present "etc/systemd/system/adc-sysvol-sync.timer"'
check "curtin-hooks" 'present "curtin/curtin-hooks"'
check "samba daemon" 'present "usr/sbin/samba"'
check "samba-tool" 'present "usr/bin/samba-tool"'
check "winbindd" 'present "usr/sbin/winbindd"'
check "smbclient" 'present "usr/bin/smbclient"'
check "chronyd (Kerberos needs the clock)" 'present "usr/sbin/chronyd"'
check "rsync (SYSVOL replication)" 'present "usr/bin/rsync"'
check "cloud-init" 'present "usr/bin/cloud-init"'
check "generic kernel (not the cloud one)" 'grep -qE "^\\./boot/vmlinuz-.*-(amd64|arm64)$" "$TMP/list"'
echo
echo "=== Files that must NOT be present ==="
check "no smb.conf (image carries no domain)" '! present "etc/samba/smb.conf"'
check "no directory database (sam.ldb)" '! present "var/lib/samba/private/sam.ldb"'
check "no secrets.tdb" '! present "var/lib/samba/private/secrets.tdb"'
check "no krb5.keytab" '! present "etc/krb5.keytab"'
check "no iSCSI initiator name" '! present "etc/iscsi/initiatorname.iscsi"'
check "no SSH host keys" '! grep -qE "^\\./etc/ssh/ssh_host_.*_key$" "$TMP/list"'
check "networking.service NOT enabled" '! present "etc/systemd/system/multi-user.target.wants/networking.service"'
check "no interfaces.new" '! present "etc/network/interfaces.new"'
check "no cloud-only kernel" '! grep -qE "^\\./boot/vmlinuz-.*-cloud-(amd64|arm64)$" "$TMP/list"'
echo
echo "=== Kernel ==="
if grep -qE '^\./boot/vmlinuz-.*-(amd64|arm64)$' "$TMP/list"; then
printf ' [ OK ] generic kernel: %s\n' "$(grep -oE 'vmlinuz-[^ ]*' "$TMP/list" | head -1)"
pass=$((pass+1))
else
printf ' [FAIL] no generic (non-cloud) kernel under /boot\n'; fail=$((fail+1))
fi
echo
echo "==> Ayiklanan dosya icerikleri"
tar xzf "$IMG" -C "$TMP" \
./usr/local/sbin/adc-maas-init \
./etc/adc-maas/adc-maas.conf ./etc/adc-maas/image-info 2>/dev/null
tar xzf "$IMG" -C "$TMP" ./etc/network/interfaces 2>/dev/null
if [ -f "$TMP/etc/network/interfaces" ]; then
echo "--- /etc/network/interfaces ---"
sed 's/^/ /' "$TMP/etc/network/interfaces"
if grep -qE '^\s*(auto|iface)\s+(?!lo)' "$TMP/etc/network/interfaces" 2>/dev/null \
|| grep -qE '^[[:space:]]*iface[[:space:]]+[^l ]' "$TMP/etc/network/interfaces"; then
printf ' [FAIL] interfaces dosyasinda build VM artigi arayuz var\n'; fail=$((fail+1))
else
printf ' [ OK ] interfaces yalnizca loopback iceriyor\n'; pass=$((pass+1))
fi
fi
if [ -f "$TMP/etc/adc-maas/image-info" ]; then
echo "--- image-info ---"
sed 's/^/ /' "$TMP/etc/adc-maas/image-info"
fi
if [ -x "$TMP/usr/local/sbin/adc-maas-init" ]; then
printf ' [ OK ] adc-maas-init is executable\n'; pass=$((pass+1))
else
printf ' [FAIL] adc-maas-init is not executable\n'; fail=$((fail+1))
fi
echo
echo "==> Result: ${pass} passed, ${fail} failed"
[ "$fail" -eq 0 ]