add a way to pass "-k" to nsupdate, and document all options in the sample config...
[dyn-nsupdate.git] / nsupd-wrapper / dyn-nsupdate.cpp
1 /* Copyright (c) 2014, Ralf Jung <post@ralfj.de>
2 * All rights reserved.
3
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6
7 * 1. Redistributions of source code must retain the above copyright notice, this
8 *    list of conditions and the following disclaimer. 
9 * 2. Redistributions in binary form must reproduce the above copyright notice,
10 *    this list of conditions and the following disclaimer in the documentation
11 *    and/or other materials provided with the distribution.
12
13 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
17 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 */
24
25 #include <iostream>
26 #include <fstream>
27 #include <sys/wait.h>
28
29 #include <boost/regex.hpp>
30 #include <boost/program_options.hpp>
31 #include <boost/property_tree/ptree.hpp>
32 #include <boost/property_tree/ini_parser.hpp>
33 #include <boost/iostreams/device/file_descriptor.hpp>
34 #include <boost/iostreams/stream.hpp>
35
36 namespace pt = boost::property_tree;
37 namespace po = boost::program_options;
38 using std::string;
39 using boost::regex;
40 using boost::optional;
41
42 static void write(int fd, const char *str)
43 {
44     size_t len = strlen(str);
45     ssize_t written = write(fd, str, len);
46     if (written < 0 || (size_t)written != len) {
47         std::cerr << "Error writing pipe." << std::endl;
48         exit(1);
49     }
50 }
51
52 int main(int argc, const char ** argv)
53 {
54     try {
55         static const regex regex_ipv4("\\d{1,3}(\\.\\d{1,3}){3}|");
56         static const regex regex_ipv6("[a-fA-F0-9]{1,4}(:[a-fA-F0-9]{1,4}){7}|");
57         static const regex regex_password("[a-zA-Z0-9.:;,_-]+");
58         static const regex regex_domain("[a-zA-Z0-9.]+");
59         
60         // Declare the supported options.
61         po::options_description desc("Allowed options");
62         desc.add_options()
63             ("help", "produce help message")
64             ("domain", po::value<string>()->required(), "the domain to update")
65             ("password", po::value<string>()->required(), "the password for the domain")
66             ("ipv4", po::value<string>(), "the new IPv4 address (empty to delete the A record)")
67             ("ipv6", po::value<string>(), "the new IPv6 address (empty to delete the AAAA record)")
68         ;
69         
70         // parse arguments
71         po::variables_map vm;
72         po::store(po::parse_command_line(argc, argv, desc), vm);
73         po::notify(vm);    
74         if (vm.count("help")) {
75             std::cout << "dyn-nsupdate -- a safe setuid wrapper for nsupdate" << std::endl << std::endl;
76             std::cout << desc << "\n";
77             return 1;
78         }
79         string domain = vm["domain"].as<string>();
80         string password = vm["password"].as<string>();
81         bool haveIPv4 = vm.count("ipv4");
82         string ipv4 = haveIPv4 ? vm["ipv4"].as<string>() : "";
83         bool haveIPv6 = vm.count("ipv6");
84         string ipv6 = haveIPv6 ? vm["ipv6"].as<string>() : "";
85         
86         /* Validate input */
87         if (!regex_match(ipv4, regex_ipv4)) {
88             throw std::runtime_error("Invalid IPv4 address" + ipv4);
89         }
90         if (!regex_match(ipv6, regex_ipv6)) {
91             throw std::runtime_error("Invalid IPv6 address: " + ipv6);
92         }
93         if (!regex_match(domain, regex_domain)) {
94             throw std::runtime_error("Invalid Domain: " + domain);
95         }
96         if (!regex_match(password, regex_password)) {
97            throw std::runtime_error("Invalid Password: " + password);
98         }
99         
100         /* read configuration */
101         pt::ptree config;
102         pt::ini_parser::read_ini(CONFIG_FILE, config);
103         std::string nsupdate = config.get<std::string>("nsupdate");
104         unsigned server_port = config.get<unsigned>("port", 53);
105         std::string keyfile = config.get<std::string>("keyfile", "");
106         std::string key = config.get<std::string>("key", "");
107         
108         /* check for some invalid configurations */
109         if (keyfile.size() > 0 && key.size() > 0) {
110             std::cerr << "You can only have either a keyfile or a key set. Please fix your configuration." << std::endl;
111             exit(1);
112         }
113         
114         /* Given the domain, check whether the password matches */
115         optional<std::string> correct_password = config.get_optional<std::string>(pt::ptree::path_type(domain+"/password", '/'));
116         if (!correct_password || *correct_password != password) {
117             std::cerr << "Password incorrect." << std::endl;
118             exit(1);
119         }
120         
121         /* preapre the pipe */
122         int pipe_ends[2];
123         if (pipe(pipe_ends) < 0) {
124             std::cerr << "Error opening pipe." << std::endl;
125             exit(1);
126         }
127
128         /* Launch nsupdate */
129         pid_t child_pid = fork();
130         if (child_pid < 0) {
131             std::cerr << "Error while forking." << std::endl;
132             exit(1);
133         }
134         if (child_pid == 0) {
135             /* We're in the child */
136             /* Close write end, use read end as stdin */
137             close(pipe_ends[1]);
138             if (dup2(pipe_ends[0], fileno(stdin)) < 0) {
139                 std::cerr << "There was an error redirecting stdin." << std::endl;
140                 exit(1);
141             }
142             /* exec nsupdate */
143             if (keyfile.size() > 0) {
144                 execl(nsupdate.c_str(), nsupdate.c_str(), "-k", keyfile.c_str(), "-p", std::to_string(server_port).c_str(), "-l", (char *)NULL);
145             }
146             else if (key.size() > 0) {
147                 execl(nsupdate.c_str(), nsupdate.c_str(), "-y", key.c_str(), "-p", std::to_string(server_port).c_str(), "-l", (char *)NULL);
148             }
149             else {
150                 execl(nsupdate.c_str(), nsupdate.c_str(), "-p", std::to_string(server_port).c_str(), "-l", (char *)NULL);
151             }
152             /* There was an error */
153             std::cerr << "There was an error executing nsupdate." << std::endl;
154             exit(1);
155         }
156         
157         /* Send it the command */
158         if (haveIPv4) {
159             write(pipe_ends[1], "update delete ");
160             write(pipe_ends[1], domain.c_str());
161             write(pipe_ends[1], ". A\n");
162             
163             if (!ipv4.empty()) {
164                 write(pipe_ends[1], "update add ");
165                 write(pipe_ends[1], domain.c_str());
166                 write(pipe_ends[1], ". 60 A ");
167                 write(pipe_ends[1], ipv4.c_str());
168                 write(pipe_ends[1], "\n");
169             }
170         }
171         
172         if (haveIPv6) {
173             write(pipe_ends[1], "update delete ");
174             write(pipe_ends[1], domain.c_str());
175             write(pipe_ends[1], ". AAAA\n");
176             
177             if (!ipv6.empty()) {
178                 write(pipe_ends[1], "update add ");
179                 write(pipe_ends[1], domain.c_str());
180                 write(pipe_ends[1], ". 60 AAAA ");
181                 write(pipe_ends[1], ipv6.c_str());
182                 write(pipe_ends[1], "\n");
183             }
184         }
185         
186         write(pipe_ends[1], "send\n");
187         
188         /* Close both ends */
189         close(pipe_ends[0]);
190         close(pipe_ends[1]);
191         
192         /* Wait for child to be gone */
193         int child_status;
194         waitpid(child_pid, &child_status, 0);
195         if (child_status != 0) {
196             std::cerr << "There was an error in the child." << std::endl;
197             exit(1);
198         }
199     }
200     catch(std::exception &e) {
201         std::cout << e.what() << "\n";
202         return 1;
203     } 
204     
205     return 0;
206 }