Skip to content

Commit

Permalink
Ensure the DHCP leases file is removed
Browse files Browse the repository at this point in the history
On Debian 10 and others a machine specific identifier is generated and
written to the DHCP leases file. When requesting or renewing an address,
the identifier is sent to the DHCP server. This allows the server to
uniquely identify each client.
At shutdown, ifdown/dhclient will recreate the leases file if it is
missing. As such, to ensure the leases file is removed, we need to wait
for ifdown/dhclient to complete before attempting to remove the leases
file.
  • Loading branch information
DanHam committed Dec 29, 2019
1 parent 055c069 commit 79f144c
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions sysprep-op-dhcp-client-state.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!/usr/bin/env bash
#
# Remove DHCP client lease information
# Remove DHCP client lease information. Note that Debian 10, and possibly
# other OSes, now write a machine specific DUID (DHCP Unique ID) to the
# leases file
set -o errexit

lease_data_locations=(
Expand All @@ -11,9 +13,33 @@ lease_data_locations=(
# Include hidden files in glob
shopt -s nullglob dotglob

for lease_data in ${lease_data_locations[@]}
for lease_file in ${lease_data_locations[@]}
do
rm -rf ${lease_data}
# On shutdown ifdown/dhclient may write to (or recreate) the dhcp
# leases file when the interface is brought down. To ensure the leases
# file is removed we need to wait for the interface to be brought down.
# Timeout after 20secs.
iface="$(cat ${lease_file} | sed -nre 's/.*interface "(.*)";/\1/p' | uniq)"
timer=0
while grep up "/sys/class/net/${iface}/operstate" &>/dev/null && \
[[ timer -lt 20 ]]; do
sleep 1
let timer=${timer}+1
done
# If the interface was brought down successfully, wait a few secs
# for ifdown/dhclient to complete
sleep 2
# If we timed out we need to kill the dhcp client to prevent it
# recreating the dhcp leases file. Killing the client won't hurt if the
# interface was brought down sucessfully as the system is going down
# anyway
pid="$(ps aux | grep /sbin/dhclient | grep "${iface}" | tr -s " " | \
cut -d' ' -f2)"
if [ "x${pid}" != "x" ]; then
kill -9 "${pid}"
fi
# Finally remove the leases file
rm -f ${lease_file}
done

exit 0

0 comments on commit 79f144c

Please sign in to comment.