summaryrefslogtreecommitdiff
path: root/dns.php
blob: 8a3454d2e1f037fb9db32d9c46a01db2f4e9ba87 (plain)
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
<!DOCTYPE html>
<html>
  <head>
    <title>BlaDNS</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  <body>
<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);

define("ZONEROOT", "/var/bind/pri/");
define("ZONESUFFIX", ".zone");

function incrementserial($zonetext) {
  $serial = array("");
  $newserial = "";

  // See if we can detect a serial number
  if (preg_match("/\(($|^|[[:space:]])*[0-9]{10}([[:space:]]|;|$|^)+/", $zonetext, $matches)) {;
    // Only bother with the first match
    preg_match("/[0-9]{10}/", $matches[0], $serial);

    $today = date("Ymd00");

    if ($serial[0] < $today) {
      $newserial = $today;
    } else {
      $newserial = $serial[0] + 1;
    }

    // The effort below is gone to to avoid replacing more than one match with our *one* new serial number

    // Prepare a string to replace the string we found the serial in
    $rebuiltstring = str_replace($serial[0], $newserial, $matches[0]);
    // Escape special regex characters since we need to use preg_replace below to limit to one replacement
    $escapedmatch = preg_quote($matches[0]);

    $zonetext = preg_replace("/" . $escapedmatch . "/", $rebuiltstring, $zonetext, 1);
  }

  return array($zonetext, $serial[0], $newserial);
}

function sshrun($command) {
  $host = "misc.tghost.co.uk";
  $user = "bladns.net";
  $keypub = "/home/bladns.net/.ssh/id_rsa.pub";
  $keypriv = "/home/bladns.net/.ssh/id_rsa";

  $connection = ssh2_connect($host, 22, array("hostkey" => "ssh-rsa"));

  ssh2_auth_pubkey_file($connection, $user, $keypub, $keypriv);

  $stream = ssh2_exec($connection, $command);
  stream_set_blocking($stream, true);
  $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
  return stream_get_contents($stream_out);
}

function getzone($domain, $password = null) {
  if (!preg_match('/^[0-9A-Za-z\.\-]*$/', $domain)) {
    die("invalid domain");
  }

  $string = sshrun("cat " . ZONEROOT . $domain . ZONESUFFIX);

  $zonelines = explode("\n", $string);
  $zonehash = explode(" ", $zonelines[0]);

  // Not all calls to this function need a password
  if (!$password) {
    return $string;
  } else if (strtolower($zonehash[sizeof($zonehash) - 1]) == strtolower($password)) {
    return $string;
  } else {
    return;
  }
}

function writezone($domain, $zonetext, $password = null) {
  if (!preg_match('/^[0-9A-Za-z\.\-]*$/', $domain)) {
    die("invalid domain");
  }

  // Not all calls to this function need a password. If passwords are in use,
  // check to make sure it is correct.
  if ($password && !getzone($domain, $password)) {
    die("somehow the password went bad");
  }

  $zonetext = str_replace('$', '\$', $zonetext);

  sshrun("echo -en \"$zonetext\" > " . ZONEROOT . "$domain" . ZONESUFFIX);
  sshrun("rndc reload $domain");
}

// Main entry point

if (isset($_GET['mode']) && isset($_GET['zone']) && isset($_GET['hash'])) {
  // Some sort of mode (at the moment only "update" is supported
  if ($_GET['mode'] == "update") {
    // An auto update is being requested. This is where one or more zone records
    // are requested to be updated to the requester's IP address.
    $zonetext = getzone($_GET['zone']);
    // Only use \n for newlines
    $zonetext = str_replace("\r", "", $zonetext);
    // Split into individual lines
    $zonelines = explode("\n", $zonetext);
    $matches = array();
    // Find lines that ended with the hash provided (if any)
    $i = 0;
    foreach ($zonelines as $line) {
      if (preg_match("/" . $_GET['hash'] . "$/", $line)) {
        array_push($matches, array($i, $line));
      }
      $i++;
    }
    // Go through the lines that matched the hash and see if we can find an update to do
    foreach ($matches as $arrline) {
      $line = $arrline[1];
      // Get rid of the comment
      $exploded = explode(";", $line);
      $record = $exploded[0];
      // Split into individual components
      $parts = preg_split("/\s+/", $record);
      // Make sure the last element isn't blank (would happen if the comment had a space before it)
      while ($parts[sizeof($parts) - 1] == "") {
        array_pop($parts);
      }
      // See if the record type on this line matches the request address type (e.g. an A record update must be requested by an IPv4 address)
      if ($parts[sizeof($parts) - 2] == "A") {
        // Regex for IPv4 address
        if (preg_match("/\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b/", $_SERVER['REMOTE_ADDR'])) {
          $parts[sizeof($parts) - 1] = $_SERVER['REMOTE_ADDR'];
        } else {
          die("A record and non-IPv4 request - bad.");
        }
      } else if ($parts[sizeof($parts) - 2] == "AAAA") {
        // Regex for IPv6 address
        if (preg_match("/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/", $_SERVER['REMOTE_ADDR'])) {
          $parts[sizeof($parts) - 1] = $_SERVER['REMOTE_ADDR'];
        } else {
          die("AAAA record and non-IPv6 request - bad.");
        }
      } else {
        die("Unrecognised record type!");
      }
      // Update original zone file array with the new line at the correct position
      $zonelines[$arrline[0]] = preg_replace("/[A-Za-z0-9:\.]+([[:space:]]*;)/", $parts[sizeof($parts) - 1] . "$1", $line);
    }
    // Next we need to turn the zone file array back into a string again
    $newzonetext = "";
    // If the last element was blank, remove it since we'll add a new blank ourselves
    if ($zonelines[sizeof($zonelines) - 1] == "") {
      array_pop($zonelines);
    }
    // Do the actual converstion to string
    foreach ($zonelines as $line) {
      $newzonetext .= $line . "\n";
    }
    // See if there was actually a change as a result of this request...
    if ($zonetext == $newzonetext) {
      // ...if not, abandon ship
      echo "<p>no changes detected :)</p>";
    } else {
      // ...if so, increment the serial number and...
      $newzonetext = incrementserial($newzonetext)[0];
      // ...finally write the zone with the updated record(s)
      writezone($_GET['zone'], $newzonetext);
      echo "<p>record&#40;s&#41; updated :)</p>";
    }
  }
} else if (isset($_POST['domain']) && isset($_POST['password']) && !isset($_POST['zonetext'])) {
  if (!preg_match('/^[0-9A-Za-z\.\-]*$/', $_POST['domain'])) {
    die("invalid domain");
  }

  $password = hash("sha256", $_POST['password']);

  if ($zonefile = getzone($_POST['domain'], $password)) {
?>
    <p>1. Your zonefile is below.</p>
    <p>2. Ensure the first line always ends with a SHA-256 hash of your chosen password.</p>
    <p>3. To automatically update a particular record, give the line a comment ending with a secret ID &#40;e.g. a SHA-256 hash&#41;, e.g.:</p>
    <pre>
test    300     IN      A       192.168.0.1 ; sha256 = 7f480e744a79953eb916b68f540e0eeec6f9cf23edf4aa08cc1cdf5f077c0f6f
test    300     IN      AAAA    ::1 ; sha256 = b493d48364afe44d11c0165cf470a4164d1e2609911ef998be868d46ade3de4e
    </pre>
    <p>And then do an HTTP&#40;S&#41; request to:</p>
    <pre>https://bladns.net/dns.php?mode=update&zone=<strong>yourdomain.tld</strong>&hash=<strong>yourid</strong></pre>
    <p>Your record will be updated with the IP you did the request from.</p>
    <form action="dns.php" method="post">
    <textarea rows="24" cols="80" name="zonetext" autofocus><?php echo $zonefile; ?></textarea><br>
<?php
    $arrincrement = incrementserial($zonefile);
    if ($arrincrement[0] != $zonefile) {
?>
    <input type="checkbox" name="increment" checked>Automatically increment serial number from <?php echo $arrincrement[1] . " to " . $arrincrement[2]; ?>?</input><br>
<?php
    }
?>
    <input type="hidden" name="domain" value="<?php echo $_POST['domain']; ?>">
    <input type="hidden" name="password" value="<?php echo $password; ?>">
    <input type="submit" value="Update zonefile"><br>
    </form>
<?php
  } else {
    echo "<p>sorry, the domain or password is wrong :(</p>";
  }
} else if (isset($_POST['domain']) && isset($_POST['password']) && isset($_POST['zonetext'])) {
  $zonetext = str_replace("\r", '', $_POST['zonetext']);
  // Increment the serial number if the box was checked
  if (isset($_POST['increment'])) {
    $zonetext = incrementserial($zonetext)[0];
  }
  writezone($_POST['domain'], $zonetext, $_POST['password']);
  echo "<p>all done :)</p>";
} else {
?>
    <form name="login" action="dns.php" method="post">
      Domain name: <input type="text" name="domain" autofocus><br>
      Password: <input type="password" name="password"><br>
      <input type="submit" value="Login">
    </form>
<?php
}
?>
  </body>
</html>