move the setuid wrapper binary into its own folder
[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 * The views and conclusions contained in the software and documentation are those
25 * of the authors and should not be interpreted as representing official policies, 
26 * either expressed or implied, of the FreeBSD Project.
27 */
28
29 #include <iostream>
30 #include <fstream>
31 #include <sys/wait.h>
32
33 #include <boost/regex.hpp>
34 #include <boost/program_options.hpp>
35 #include <boost/property_tree/ptree.hpp>
36 #include <boost/property_tree/ini_parser.hpp>
37 #include <boost/iostreams/device/file_descriptor.hpp>
38 #include <boost/iostreams/stream.hpp>
39
40 namespace pt = boost::property_tree;
41 namespace po = boost::program_options;
42 using std::string;
43 using boost::regex;
44 using boost::optional;
45
46 static void write(int fd, const char *str)
47 {
48     size_t len = strlen(str);
49     ssize_t written = write(fd, str, len);
50     if (written < 0 || (size_t)written != len) {
51         std::cerr << "Error writing pipe." << std::endl;
52         exit(1);
53     }
54 }
55
56 int main(int argc, const char ** argv)
57 {
58     try {
59         static const regex regex_ipv4("\\d{1,3}(\\.\\d{1,3}){3}|");
60         static const regex regex_ipv6("[a-fA-F0-9]{1,4}(:[a-fA-F0-9]{1,4}){7}|");
61         static const regex regex_password("[a-zA-Z0-9.:;,_-]+");
62         static const regex regex_domain("[a-zA-Z0-9.]+");
63         
64         // Declare the supported options.
65         po::options_description desc("Allowed options");
66         desc.add_options()
67             ("help", "produce help message")
68             ("domain", po::value<string>()->required(), "the domain to update")
69             ("password", po::value<string>()->required(), "the password for the domain")
70             ("ipv4", po::value<string>(), "the new IPv4 address (empty to delete the A record)")
71             ("ipv6", po::value<string>(), "the new IPv6 address (empty to delete the AAAA record)")
72         ;
73         
74         // parse arguments
75         po::variables_map vm;
76         po::store(po::parse_command_line(argc, argv, desc), vm);
77         po::notify(vm);    
78         if (vm.count("help")) {
79             std::cout << "dyn-nsupdate -- a safe setuid wrapper for nsupdate" << std::endl << std::endl;
80             std::cout << desc << "\n";
81             return 1;
82         }
83         string domain = vm["domain"].as<string>();
84         string password = vm["password"].as<string>();
85         bool haveIPv4 = vm.count("ipv4");
86         string ipv4 = haveIPv4 ? vm["ipv4"].as<string>() : "";
87         bool haveIPv6 = vm.count("ipv6");
88         string ipv6 = haveIPv6 ? vm["ipv6"].as<string>() : "";
89         
90         /* Validate input */
91         if (!regex_match(ipv4, regex_ipv4)) {
92             throw std::runtime_error("Invalid IPv4 address" + ipv4);
93         }
94         if (!regex_match(ipv6, regex_ipv6)) {
95             throw std::runtime_error("Invalid IPv6 address: " + ipv6);
96         }
97         if (!regex_match(domain, regex_domain)) {
98             throw std::runtime_error("Invalid Domain: " + domain);
99         }
100         if (!regex_match(password, regex_password)) {
101            throw std::runtime_error("Invalid Password: " + password);
102         }
103         
104         /* read configuration */
105         pt::ptree config;
106         pt::ini_parser::read_ini(CONFIG_FILE, config);
107         std::string nsupdate = config.get<std::string>("nsupdate");
108         unsigned server_port = config.get<unsigned>("port", 53);
109         
110         /* Given the domain, check whether the password matches */
111         optional<std::string> correct_password = config.get_optional<std::string>(pt::ptree::path_type(domain+"/password", '/'));
112         if (!correct_password || *correct_password != password) {
113             std::cerr << "Password incorrect." << std::endl;
114             exit(1);
115         }
116         
117         /* preapre the pipe */
118         int pipe_ends[2];
119         if (pipe(pipe_ends) < 0) {
120             std::cerr << "Error opening pipe." << std::endl;
121             exit(1);
122         }
123
124         /* Launch nsupdate */
125         pid_t child_pid = fork();
126         if (child_pid < 0) {
127             std::cerr << "Error while forking." << std::endl;
128             exit(1);
129         }
130         if (child_pid == 0) {
131             /* We're in the child */
132             /* Close write end, use read end as stdin */
133             close(pipe_ends[1]);
134             if (dup2(pipe_ends[0], fileno(stdin)) < 0) {
135                 std::cerr << "There was an error redirecting stdin." << std::endl;
136                 exit(1);
137             }
138             /* exec nsupdate */
139             execl(nsupdate.c_str(), nsupdate.c_str(), "-p", std::to_string(server_port).c_str(), "-l", (char *)NULL);
140             /* There was an error */
141             std::cerr << "There was an error executing nsupdate." << std::endl;
142             exit(1);
143         }
144         
145         /* Send it the command */
146         if (haveIPv4) {
147             write(pipe_ends[1], "update delete ");
148             write(pipe_ends[1], domain.c_str());
149             write(pipe_ends[1], ". A\n");
150             
151             if (!ipv4.empty()) {
152                 write(pipe_ends[1], "update add ");
153                 write(pipe_ends[1], domain.c_str());
154                 write(pipe_ends[1], ". 60 A ");
155                 write(pipe_ends[1], ipv4.c_str());
156                 write(pipe_ends[1], "\n");
157             }
158         }
159         
160         if (haveIPv6) {
161             write(pipe_ends[1], "update delete ");
162             write(pipe_ends[1], domain.c_str());
163             write(pipe_ends[1], ". AAAA\n");
164             
165             if (!ipv6.empty()) {
166                 write(pipe_ends[1], "update add ");
167                 write(pipe_ends[1], domain.c_str());
168                 write(pipe_ends[1], ". 60 AAAA ");
169                 write(pipe_ends[1], ipv6.c_str());
170                 write(pipe_ends[1], "\n");
171             }
172         }
173         
174         write(pipe_ends[1], "send\n");
175         
176         /* Close both ends */
177         close(pipe_ends[0]);
178         close(pipe_ends[1]);
179         
180         /* Wait for child to be gone */
181         int child_status;
182         waitpid(child_pid, &child_status, 0);
183         if (child_status != 0) {
184             std::cerr << "There was an error in the child." << std::endl;
185             exit(1);
186         }
187     }
188     catch(std::exception &e) {
189         std::cout << e.what() << "\n";
190         return 1;
191     } 
192     
193     return 0;
194 }