-
Notifications
You must be signed in to change notification settings - Fork 1
/
nsadmin
executable file
·3015 lines (2727 loc) · 68.5 KB
/
nsadmin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
#-
# Copyright (c) 2006-2013 Parker Lee Ranney TTEE
# Copyright (c) 2017-2022 Devin Teske <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
############################################################ IDENT(1)
#
# $Title: Distributed bind9 administration and management tool $
# $Id: nsadmin,v 1.1 2012/05/09 21:39:43 root Exp $
# $Copyright: 2017-2022 Devin Teske. All rights reserved. $
# $FrauBSD: nsadmin/nsadmin 2022-01-11 09:55:37 -0800 freebsdfrau $
#
############################################################ INFORMATION
#
# nsadmin -- Update Bind's installation on the master NS server. RCS
# is used for file history. All updates will be sent out as an
# email to the appropriate admin address. A lock is kept during
# the run of this program to prevent conflicting updates.
#
# --------------------------------------------------------------------
# Notes:
# - Requires bind server and nsadmin.conf on the master.
# - Users must be placed in the DNSOPS group in sudoers as a
# result of the commands that require root access.
# Commands used via sudo: awk chmod chown cp find mv rm service su
# (and possibly [depending on your system]: systemctl)
# - Users must also belong to the "bind" group in /etc/group to
# edit the files.
#
# Requirements to use AXFR transfer method ($transfer in nsadmin.conf):
# - nsaxfr on the secondary Bind servers.
# - User 'cm' and the authorized_keys2 file for that user must be
# installed on all secondary Bind servers. The 'cm' user account
# and ID file must be on the server with this script.
# - User 'cm' must be able to remotely execute via SSH the
# following command:
# sudo /usr/local/bin/nsaxfr
# Without password on the secondary Bind servers.
# --------------------------------------------------------------------
# Version History:
# Jan 2022: Release 5.6.6
# - Allow yes/no (instead of just y/n) for chance-acceptance
# Jan 2021: Release 5.6.5
# - Fix permissions even after no changes detected in edit
# Jan 2021: Release 5.6.4
# - Ignore emacs/vim recovery files in $nsadmindir
# Nov 2020: Release 5.6.3.1
# - Update sudo requirement comments
# Nov 2020: Release 5.6.3
# - Fix a typo
# Nov 2020: Release 5.6.2
# - Prevent editing zone if journal exists
# Nov 2020: Release 5.6.1
# - Prevent configuring non-text journal files in genconf()
# Nov 2020: Release 5.6
# - Allow config of extra options in named.conf(5) includes
# Nov 2020: Release 5.5
# - Transfer generated includes to secondaries
# Nov 2020: Release 5.4
# - Fix permission issues with transfer method
# Nov 2020: Release 5.3
# - Allow multiple admin/critical mail recipients
# (space-separated)
# Nov 2020: Release 5.2.1
# - Set default view in config and clarify separator
# Nov 2019: Release 5.2
# - Add a warn function
# - Warn when a jnl (journal) file exists for master zone
# - Fixup warnings about jnl (journal) files
# Oct 2019: Release 5.1.1
# - Prevent management of more invalid domain names
# - Comments
# Oct 2019: Release 5.1
# - Rename AXFR software and use modern terminology
# - Fix bug with some shells that fail on $( case ... )
# - Update comments for accuracy
# Oct 2019: Release 5.0
# - Fix bug on detecting revert of all changes after edit
# - Make backup of previous versions silent
# Oct 2019: Release 4.9.9
# - Show all pending diffs with `/diff' in edit mode
# - Improve pause() and change ENTER to return
# - Use pause() in place of peppered recipes to wait
# - Make a read that is ignored more visibly-so
# - Revert changed state if edit undoes a change
# Oct 2019: Release 4.9.8
# - Do not use sudo in sigquit()
# - Revert some previous changes around locking
# Oct 2019: Release 4.9.7
# - Add /diff command
# - Centralize definition of view/edit commands
# Oct 2019: Release 4.9.6
# - Whitespace
# - Trim leading blank lines from /log output
# Oct 2019: Release 4.9.5
# - Hide zone history unless in edit mode
# - Add /log command
# - Enable commands in view mode (/log only)
# Oct 2019: Release 4.9.4
# - Improve handling of commit message
# - Add user-provided commit message to checkin()
# - Optimize genconf() for performance
# Oct 2019: Release 4.9.3
# - Add /mv command
# - Make globals all-caps
# - Remove signal management variable (ransig)
# - Remove unused variable (vfail)
# - Improve security around /-command execution
# - Display deleted zones in menu, greyed-out
# - Add details on edit how to resurrect removed zones
# Oct 2019: Release 4.9.2
# - Revert reset of traps before generation tasks
# - Whitespace
# - Remove stray semi-colon
# Oct 2019: Release 4.9.1
# - Fix editmaster() read-only issue on re-edits
# - Fix unnecessary compound string in sigquit()
# - Re-checkout /rm'd zones on unclean exit
# - Remove /new'd zones on unclean exit
# - Make /rm require config regeneration and edit desc
# - Add `-u' and `-v' command-line options to checkout()
# - Use checkout() in newzone() instead of one-off `co'
# - Ensure /rm'd zones/revs are not resolvable after rm
# - Prevent `/' commands in view mode
# - Improve vimcat handling
# - Warn user when journal file exists
# - Move `local' definitions in rmzone() to top of function
# - Always forcefully lock files before ci in checkin()
# - Highlight rm'd zones as-such (red) during backups
# - Print config file paths during genconf()
# - Reset traps before entering generation stage
# Oct 2019: Release 4.9
# - Move vim filetype hint to top of new zone template
# - Move command-line option global definitions
# - Fix `-n host[,...]' config override
# - Show diff when importing changes detected during sync
# Oct 2019: Release 4.8.9
# - If running as root, require new `-u user' option
# - Check user after sourcing config so we can write to log
# - Fail immediately if log variable not set in config
# - Use green banner in edit mode, red when unsaved changes
# Oct 2019: Release 4.8.8
# - Ignore jnl files created by nsupdate in conf generation
# Oct 2019: Release 4.8.7
# - Add support for @ in zone2rev()
# Oct 2019: Release 4.8.6
# - Final fixup for /new RCS checkout
# - Improve backup efficiency
# - Skip checkin if no differences
# - Create new files with template contents
# Oct 2019: Release 4.8.5
# - Show files being backed up
# - Fixup /new RCS checkout
# Oct 2019: Release 4.8.4
# - User interface/log enhancement
# Oct 2019: Release 4.8.3
# - Fixup user interface and log nits
# Oct 2019: Release 4.8.2
# - Fixup creation of new/existing zone via /new
# Oct 2019: Release 4.8.1
# - Fixup RCS checkout by /new
# Oct 2019: Release 4.8
# - Make /new check for RCS files
# Oct 2019: Release 4.7.7
# - Add support for sender domain override
# Oct 2019: Release 4.7.6
# - Fix ANSI clear codes
# Oct 2019: Release 4.7.5
# - Fix ANSI escape sequences for BSD
# Oct 2019: Release 4.7.4
# - Remove log of sudo failure
# Oct 2019: Release 4.7.3
# - Fix detection of sudo failure in predit()
# Oct 2019: Release 4.7.2
# - Wordsmithing
# Oct 2019: Release 4.7.1
# - Fix version
# - Change header color when changes made
# Oct 2019: Release 4.7
# - Add /new and /rm commands to edit prompt
# Oct 2019: Release 4.6.5
# - Fix TLD record generation
# Oct 2019: Release 4.6.4
# - Fix error in genconf() when no rev maps exist
# Oct 2019: Release 4.6.3
# - Fix copy/pasta
# Oct 2019: Release 4.6.2
# - Minor edit
# Oct 2019: Release 4.6.1
# - Use sudo to create view directories
# Oct 2019: Release 4.6
# - Add support for TLD A/AAAA records
# - Create $nsadmindir on initial launch
# Oct 2019: Release 4.5.9
# - Use full paths in genconf()
# Oct 2019: Release 4.5.8
# - Fix configuration defaults
# Oct 2019: Release 4.5.7
# - Make mail optional with disabled defaults
# Oct 2019: Release 4.5.6
# - Make default $transfer empty in config
# Oct 2019: Release 4.5.5
# - Use BSD compatible ANSI escape sequences for printf
# Oct 2019: Release 4.5.4
# - Fix config
# Oct 2019: Release 4.5.3
# - Add OS Glue to config for FreeBSD
# Oct 2019: Release 4.5.2
# - Defer loading of config until after processing options
# - Defer check for root until after options processing
# - Comments
# - Look for config in proper directory based on OS
# Oct 2019: Release 4.5.1
# - Remove confusing line numbers from named-checkzone output
# - Comments and other Minor edits
# - Fix version
# Oct 2019: Release 4.5
# - Make include files for generated zones and rev maps
# Oct 2019: Release 4.4.1
# - Remove log if exiting due to running as root
# Oct 2019: Release 4.4
# - Show lock file location when locked
# - Do not use sudo in sigquit() if first use fails
# - Release lock if exiting due to sudo failure
# Oct 2019: Release 4.3
# - Fix sync (-s) based checkin from automated edits
# Oct 2019: Release 4.2.2
# - Add support for vimcat in read-only view mode
# - Improve vimcat support with PAGER in all modes
# Oct 2019: Release 4.2.1
# - Show progress as we generate rev maps
# - Only checkin sync'd files on exit if they pass syntax check
# - Fix memory leak in genrev()
# - Minimally improve and document sudo support
# Oct 2019: Release 4.2
# - checkin files after sync (-s)
# Oct 2019: Release 4.1.1
# - Lower sync verbosity
# Oct 2019: Release 4.1
# - Add support for inline custom TTL preceding protocol family
# Oct 2019: Release 4.0.4
# - Do not show contextual diff before review
# - Add whitespace after main menu prompt
# Oct 2019: Release 4.0.3
# - Fix rev map synchronization with `-s'
# - Trim trailing whitespace on code lines
# - Fix spurious error from `cd -' in sigquit()
# Oct 2019: Release 4.0.2
# - Fix permission issues for members of $bindgroup
# Oct 2019: Release 4.0.1
# - Fix hang on stdin from RCS co when file is writable
# Oct 2019: Release 4.0
# - Replace bash arrays with POSIX /bin/sh syntax
# - Do not overwrite config files if they exist on install
# - Change umask to 0022
# - Remove obsolete code
# - Improve check for duplicate running instances
# - Create required directories if they do not exist
# - Optimize usage of "cd" to fix errors
# - Improved debugging
# - Renamed *-var.inc to *.conf and cleanup
# - Merge *.inc files and zone2rev.awk into nsadmin
# - Set default view [required] to program basename (nsadmin)
# - Add support for `IN' protocol family in master zones
# - Fix `-l' to work with `-s'
# - Prevent Outlook from eating blank lines in diffs
# - Merge nsaxfr-centos7 into nsaxfr
# - Add support for vimcat
# - Add limited ANSI coloring to console output
# - Add support for `less -F' when viewing diffs
# - Add `-v' to get version
# Aug 2019: Release 3.2
# - Add Makefile
# Jul 2019: Release 3.1
# - Initial Public release.
# - Enable restriction to prevent anonymous root access.
# - Add secondary variable to `nsadmin-var.inc'.
# - Fix hard-coded primary/secondary in `GEN FUNCTIONS'.
# Jul 2018: Release 3.0
# - Major rewrite and code cleanup.
# - Improved error checking of zone files.
# - Support IPv6 AAAA records.
# Jul 2018: Release 2.6
# - Fix bug preventing some reverse entries from being created
# Jul 2018: Release 2.5
# - Fix bug preventing reverse lookup of A records ending in
# .0 or .255
# Jul 2017: Release 2.4
# - Ask the user for a message to describe changes.
# - Only allow one instance of nsadmin at a time.
# Jun 2017: Release 2.3
# - Add `-n hosts' syntax for selecting a subset of secondaries.
# - Ported to FreeBSD.
# Mar 2010: Release 2.2
# - Fixed comments.
# Jul 2006: Release 2.1
# - Modified to migrate zones manually as IXFR and AXFR
# are not reliable.
# Jun 2006: Release 2.0
# - Major rewrite and creation of includes.
# - Syntax checking.
# - Update only the rev maps with a changed IP.
# - Added read-only interface.
# - Added ability to generate zone files and rev maps
# from the master files without performing updates,
# known as sync.
# Apr 2006: Release 1.0
# - Basic interface and zone generation.
#
############################################################ INCLUDES
NSADMIN_CONF=nsadmin.conf # See OS Glue
############################################################ GLOBALS
VERSION='$Version: 5.6.6 $'
pgm="${0##*/}" # Program basename
progdir="${0%/*}" # Program directory
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
#
# Global exit status
#
SUCCESS=0
FAILURE=1
#
# Command-line options
#
USER= # -u user
EDITMODE= # -e
SYNC= # -s
SYNCALL= # -a
UPDZONES= # -l file[,...] (also used to track edited zones)
TRANSFER= # -n host[,...] (taken from $NSADMIN_CONF if unused or NULL)
#
# Commands
#
EDITCMDS="/diff /log /mv /new /rm"
VIEWCMDS="/diff /log"
#
# OS Glue
#
: ${UNAME_s:=$( uname -s )}
#
# Miscellaneous
#
COMMITMSG= # User-provided commit message
CHANGES= # Have changes been made?
FAILFILE= # File that failed zonetest()
FAILTYPE= # Type of file that failed
MVJNL= # Move journal for commit
MVJNLREV= # Reverse move journal for interrupt
NEWZONES= # Newly created zones
RMDREVS= # Rev maps of removed zones
RMDZONES= # Removed zones
ROOTFAIL= # Exited due to running as root
SEP=$( printf %75s | tr " " - ) # Separator
SEPDBL=$( printf %20s | tr " " = ) # Double separator
SUBNETS= # Subnets changed for rev maps
SYNCCNT=0 # Number of files sync'd
UPDATE=0 # Stage of master file updates
############################################################ FUNCTIONS
have(){ type "$@" > /dev/null 2>&1; }
# usage
#
# Print the help menu and exit.
#
usage()
{
exec >&2
echo
echo " Usage: $pgm ..."
echo
echo " Edit Mode:"
echo " Used to edit the master $pgm files:"
echo
echo " $pgm [-n hosts] -e"
echo
echo " Review Mode: (Default)"
echo " Used to view the master $pgm files:"
echo
echo " $pgm"
echo
echo " Sync Mode:"
echo " Used to update the Bind zone files with the data from"
echo " the master $pgm files. This does not allow"
echo " editing of the master files:"
echo
echo " $pgm -s [-ah?] [-n hosts] -l <file>[,<file>, ..."
echo
echo " -a Sync all master files."
echo " -l <file>[,<file>] Sync list of files."
echo " -n <host>[,<host>] Override transfer hosts."
echo
exit $FAILURE
}
############################################################ REV FUNCTIONS
# Functions for generating rev maps from master zones
# zone2rev [-cdilv] $file
#
# Read nsadmin zone $file and produce rev map.
#
# Options:
# -c Enable ANSI color. Implies `-d'
# -d Enable debug messages printed to stderr
# -i Initialize files to zero length
# -l List subnets on stdout and exit
# -r List reverse arpa subnets on stdout and exit
# -S Use sudo
# -s subnet Process only subnet from $file
# -V Verify contents and exit. Implies `-d'
# -v view Process only view from $file
#
exec 9<<'EOF'
function err(str)
{
if (verify) vstatus = 1
if (!debug) return
if (console)
printf "\033[35m%s\033[36m:\033[32m%d\033[36m:\033[m %s\n",
file, NR, str > "/dev/stderr"
else
printf "%s:%d: %s\n", file, NR, str > "/dev/stderr"
fflush()
}
# _asorti(src, dest)
#
# Like GNU awk's asorti() but works with any awk(1)
# NB: Named _asorti() to prevent conflict with GNU awk
#
function _asorti(src, dest, k, nitems, i, idx)
{
k = nitems = 0
for (i in src) dest[++nitems] = i
for (i = 1; i <= nitems; k = i++) {
idx = dest[i]
while ((k > 0) && (dest[k] > idx)) {
dest[k+1] = dest[k]; k--
}
dest[k+1] = idx
}
return nitems
}
# validate_ipaddr4(ip)
#
# Returns zero if the given argument (an IP address) is of the proper format.
#
# The return value for invalid IP address is one of:
# 1 One or more individual octets within the IP address (separated
# by dots) contains one or more invalid characters.
# 2 One or more individual octets within the IP address are null
# and/or missing.
# 3 One or more individual octets within the IP address exceeds the
# maximum of 255 (or 2^8-1, being an octet comprised of 8 bits).
# 4 The IP address has either too few or too many octets.
#
function validate_ipaddr4(ip, octets, noctets, n, octet)
{
# Split on `dot'
noctets = split(ip, octets, /\./)
if (noctets != 4) return 4
for (n = 1; n <= noctets; n++) {
octet = octets[n]
# Return error if the octet is null
if (octet == "") return 2
# Return error if not a whole/positive integer
if (octet ~ /[^0-9]/) return 1
# Return error if the octet exceeds 255
if (octet > 255) return 3
}
return 0
}
# validate_ipaddr6(ip)
#
# Returns zero if the given argument (an IPv6 address) is of the proper format.
#
# The return value for invalid IP address is one of:
# 1 One or more individual segments with the IP address
# (separated by colons) contains one or more invalid characters.
# Segments must contain only combinations of the characters 0-9,
# A-F, or a-f.
# 2 Too many/incorrent null segments. A single null segment is
# allowed within the IP address (separated by colons) but not
# allowed at the beginning or end (unless a double-null segment;
# i.e., "::*" or "*::").
# 3 One or more individual segments within the IP address
# (separated by colons) exceeds the length of 4 hex-digits.
# 4 The IP address entered has either too few (less than 3), too
# many (more than 8), or not enough segments, separated by
# colons.
# 5 The IPv4 address at the end of the IPv6 address is invalid.
#
function validate_ipaddr6(ip,
segments, nsegments, n, segment, h, short, nulls,
contains_ipv4_segment, maxsegments)
{
sub(/%.*$/, "", ip) # remove interface spec if-present
# Split on `colon'
nsegments = split(ip, segments, /:/)
# Return error if too many or too few segments
# Using 9 as max in case of leading or trailing null spanner
if (nsegments > 9 || nsegments < 3) return 4
h = "[0-9A-Fa-f]"
short = sprintf("^(%s|%s|%s|%s)$", h, h h, h h h, h h h h)
nulls = contains_ipv4_segment = 0
for (n = 1; n <= nsegments; n++) {
segment = segments[n]
#
# Return error if this segment makes one null too-many. A
# single null segment is allowed anywhere in the middle as well
# as double null segments are allowed at the beginning or end
# (but not both).
#
if (segment == "") {
nulls++
if (nulls == 3) {
# Only valid syntax for 3 nulls is `::'
if (ip != "::") return 2
} else if (nulls == 2) {
# Only valid if begins/ends with `::'
if (ip !~ /(^::|::$)/) return 2
}
continue
}
#
# Return error if not a valid hexadecimal short
#
if (segment ~ short) continue # Valid segment of 1-4 hex digits
if (segment ~ /[^0-9A-Fa-f]/) {
# Segment contains at least one invalid char
# Return error immediately if not last segment
if (n < nsegments) return 1
# Otherwise, check for legacy IPv4 notation
if (segment ~ /[^0-9.]/) {
# Segment contains at least one invalid
# character even for an IPv4 address
return 1
}
# Return error if not enough segments
if (nulls == 0) {
if (nsegments != 7) return 4
}
contains_ipv4_segment=1
# Validate ipv4_segment
if (validate_ipaddr4(segment)) return 5
} else {
# Segment characters are all valid but too many
return 3
}
}
if (nulls == 1) {
# Single null segment cannot be at beginning/end
if (ip ~ /(^:|:$)/) return 2
}
#
# A legacy IPv4 address can span the last two 16-bit segments,
# reducing the amount of maximum allowable segments by-one.
#
maxsegments = contains_ipv4_segment ? 7 : 8
if (nulls == 0) {
# Return error if missing segments with no null spanner
if (nsegments != maxsegments) return 4
} else if (nulls == 1) {
# Return error if null spanner with too many segments
if (nsegments > maxsegments) return 4
} else if (nulls == 2) {
# Return error if leading/trailing `::' with too many segments
if (nsegments > (maxsegments + 1)) return 4
}
return 0
}
# split6(ip, array)
#
# Split the elements of IPv6 ip into 32 hex-nibbles stored in array.
#
function split6(ip, nibbles, n, ip4, octs, s, i, nibs, nib, k)
{
for (n = 1; n <= 32; n++) nibbles[n] = 0
if (match(ip, /:[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/)) {
ip4 = substr(ip, RSTART + 1)
ip = substr(ip, 1, RSTART - 1)
split(ip4, octs, /\./)
ip = sprintf("%s:%02x%02x:%02x%02x",
ip, octs[1], octs[2], octs[3], octs[4])
}
if (sub(/^::/, "", ip)) {
n = 32
ip = sprintf("%04s", ip)
for (k = 4; k > 0; k--) nibbles[n--] = substr(ip, k, 1)
} else if (sub(/::$/, "", ip)) {
n = 1
ip = sprintf("%04s", ip)
for (k = 1; k <= 4; k++) nibbles[n++] = substr(ip, k, 1)
} else if (ip ~ /::/) {
left = right = ip
sub(/::.*$/, "", left)
sub(/^.*::/, "", right)
s = split(left, nibs, /:/)
for (i = 1; i <= s; i++) {
n = (i - 1) * 4 + 1
nib = sprintf("%04s", nibs[i])
for (k = 1; k <= 4; k++)
nibbles[n++] = substr(nib, k, 1)
}
s = split(right, nibs, /:/)
n = 32
for (i = s; i > 0; i--) {
nib = sprintf("%04s", nibs[i])
for (k = 4; k > 0; k--)
nibbles[n--] = substr(nib, k, 1)
}
} else {
s = split(ip, nibs, /:/)
for (i = 1; i <= s; i++) {
n = (i - 1) * 4 + 1
nib = sprintf("%04s", nibs[i])
for (k = 1; k <= 4; k++)
nibbles[n++] = substr(nib, k, 1)
}
}
}
BEGIN {
if (console || verify) debug = 1
if (list_reverse) list_subnets = 1
vstatus = 0
subnet = tolower(subnet)
delete initialized
delete files
NR = 0
rec = ""
while (getline < file > 0) {
NR++
if (/^[[:space:]]*;/) continue
if ($1 ~ "^" file) continue
if (/;*VIEW:/ && $0 !~ view) continue
if (/\*/) continue
gsub(/;.*/, "")
delete U
for (n = 1; n <= 5 && n <= NF; n++) U[n] = toupper($n)
if (NF == 2) {
type = U[1]
ip = $2
} else if (NF == 3) {
if ($1 !~ /^([0-9]+|IN)$/) rec = $1
type = U[2]
ip = $3
} else if (NF == 4 && U[2] ~ /^([0-9]+|IN)$/) {
if ($1 !~ /^[0-9]+$/) rec = $1
type = U[3]
ip = $4
} else if (NF == 5 && $2 ~ /^[0-9]+$/ && U[3] == "IN") {
rec = $1
type = U[4]
ip = $5
} else {
continue
}
if (type == "A") {
if ((errno = validate_ipaddr4(ip)) != 0) {
err(sprintf("bad A record `%s' for `%s' " \
"(ERR#%u)", ip, rec, errno))
continue
}
split(ip, oct, /\./)
net = sprintf("%u.%u.%u", oct[1], oct[2], oct[3])
if (!list_subnets && subnet && net != subnet) continue
rev = sprintf("%u.%u.%u", oct[3], oct[2], oct[1])
ptr = sprintf("%u\t\t\t\t\tPTR\t%s%s%s.",
oct[4], rec == "@" ? "" : rec,
rec ~ /^@?$/ ? "" : ".", file)
} else if (type == "AAAA") {
if ((errno = validate_ipaddr6(ip)) != 0) {
err(sprintf("bad AAAA record `%s' for `%s' " \
"(ERR#%u)", ip, rec, errno))
continue
}
delete nib
split6(ip, nib)
net = sprintf("%s%s%s%s:%s%s%s%s:%s%s%s%s:%s%s%s%s",
nib[1], nib[2], nib[3], nib[4],
nib[5], nib[6], nib[7], nib[8],
nib[9], nib[10], nib[11], nib[12],
nib[13], nib[14], nib[15], nib[16])
if (!list_subnets && subnet && tolower(net) != subnet)
continue
rev = tolower(sprintf( \
"%s.%s.%s.%s." \
"%s.%s.%s.%s." \
"%s.%s.%s.%s." \
"%s.%s.%s.%s",
nib[16], nib[15], nib[14], nib[13],
nib[12], nib[11], nib[10], nib[9],
nib[8], nib[7], nib[6], nib[5],
nib[4], nib[3], nib[2], nib[1]))
ptr = sprintf( \
"%s.%s.%s.%s." \
"%s.%s.%s.%s." \
"%s.%s.%s.%s." \
"%s.%s.%s.%s" \
"\t\tPTR\t%s%s%s.",
nib[32], nib[31], nib[30], nib[29],
nib[28], nib[27], nib[26], nib[25],
nib[24], nib[23], nib[22], nib[21],
nib[20], nib[19], nib[18], nib[17],
rec == "@" ? "" : rec,
rec ~ /^@?$/ ? "" : ".", file)
} else {
continue
}
if (list_subnets || list_reverse) {
if (list_reverse)
subnets[rev] = 1
else
subnets[net] = 1
continue
}
rev = ".new-" rev
if (initialize && !(rev in initialized)) {
printf "" > rev
initialized[rev] = 1
}
files[rev] = 1
print ptr >> rev
}
exit
}
END {
if (verify) exit vstatus
if (list_subnets) {
n = _asorti(subnets, subnets_sorted)
for (i = 1; i <= n; i++) print subnets_sorted[i]
exit
}
if (!debug) exit
fmt = console ? "\033[32m%5d\033[36m:\033[m %s\n" : "%5d: %s\n"
n = _asorti(files, files_sorted)
for (i = 1; i <= n; i++) {
rev = files_sorted[i]
if (console)
printf "\033[32m>\033[m %s\n", rev > "/dev/stderr"
else
printf "> %s\n", rev > "/dev/stderr"
while (getline < rev > 0)
printf fmt, ++NRr[rev], $0 > "/dev/stderr"
}
}
EOF
zone2rev_awk=$( cat <&9 )
zone2rev()
{
local console=0
local debug=0
local initialize=0
local list_reverse=0
local list_subnets=0
local subnet=
local sudo=
local verify=0
local view=
local OPTIND=1 OPTARG flag
while getopts cdilrSs:Vv: flag; do
case "$flag" in
c) console=1 ;;
d) debug=1 ;;
i) initialize=1 ;;
l) list_subnets=1 ;;
r) list_reverse=1 ;;
S) sudo=1 ;;
s) subnet="$OPTARG" ;;
V) verify=1 ;;
v) view="$OPTARG" ;;
esac
done
shift $(( $OPTIND - 1 ))
${sudo:+sudo} awk -v console=$console \
-v debug=$debug \
-v file="$1" \
-v initialize=$initialize \
-v list_reverse=$list_reverse \
-v list_subnets=$list_subnets \
-v subnet="$subnet" \
-v verify=$verify \
-v view="$view" \
"$zone2rev_awk"
}
############################################################ EDIT FUNCTIONS
# Functions to edit/change master files for zone and rev maps
# editmaster zone
#
# Edit the master files.
#
editmaster()
{
local file="$1"
log -d "Editing $file"
cd "$nsadmindir"
checkout "$file"
chmod ug+w "$file"
${EDITOR:-vi} "$file"
verify "$file"
cd - > /dev/null
}
# getlock
#
# Establish an exclusive lock for master file edits.
#
getlock()
{
local clobber=
local res
if [ -f "$lock" ]; then
res=$( ls -l "$lock" | awk '{print $3}' )
printf "\033[2mlock: %s\033[m\n" "$lock"
fatal "lock file exists, owner is $res" # NOTREACHED
fi
[ "$-" = "${-#*C}" ] && clobber=1
set -C
echo $$ > "$lock" || fatal "could not create '$lock'" # NOTREACHED
[ "$clobber" ] && set +C
}
# predit
#
# Prepare the editing of the master files.
#
predit()
{
local dir
trap sigquit EXIT
msg "$USER starting edits: $( date )"
sudo rm -rf "$log" "$tmp" .bak-* .revunq .updzones .view* ||
exit $FAILURE
trap "sigquit; exit" SIGHUP SIGINT SIGQUIT SIGTERM
echo > "$log"
log " Starting: $( date )"
mkdir -p -m 0770 "$tmp"
# Make tmp directory owned by BIND user/group and group-writable
dir="$tmp"
case "$dir" in
*/) dir="${dir%/}" ;;
esac
dir="${dir%/*}"
case "$dir" in
/) : skip ;;
*) sudo chown -R "$binduser:$bindgroup" "$dir"
sudo chmod -R g+w "$dir"
esac
}
# clear
#
# Like clear(1) but preserve scrollback.
#
clear()
{
local size rows cols
size=$( stty size 2> /dev/null )
set -- ${size:-24 80}
rows="$1"
cols="$2"
printf "\033[${rows}S\033[H\033[J"
}
############################################################ GEN FUNCTIONS
# Functions to generate zone files and reverse maps
# genmaster
#
# Generate the zone files and rev maps.
#
genmaster()
{
local file
local ignored
local subnet
#
# Save the master files that have changes to make sure they
# are not lost in the loop'ing below.
#
echo "$UPDZONES" > "$nsadmindir/.updzones"
#
# Generate a list of all subnets in the master file
#
if [ "$SYNC" -o "$MVJNL" ]; then
for subnet in $(
for file in $UPDZONES; do
zone2rev -l "$file"
done | sort -u
); do
# Only insert subnet if not existing in $SUBNETS
echo "$SUBNETS" | grep -q "\\<$(
echo "$subnet" | sed -e 's/\./\\&/g'
)$subnet\\>" || SUBNETS="$SUBNETS $subnet"
done
SUBNETS="${SUBNETS# }"
fi
#
# Loop through the zone file generation until each error is
# fixed. Secondary systems will not sync bad zone files nor will
# the master load them.
#
while :; do
echo
msg "Building zone files and revmaps: $( date )"
genzone $( cat "$nsadmindir/.updzones" )
genrev
zonetest
[ "$FAILFILE" ] || break
printf "\n\033[1mPress return when ready to re-edit.\033[m"
stty -echo
read ignored
stty echo
# Clean up the previous attempt