]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/ws-auth.cc
Merge pull request #6641 from pieterlexis/dnsdist-centos-6-postinst
[thirdparty/pdns.git] / pdns / ws-auth.cc
CommitLineData
12c86877 1/*
6edbf68a
PL
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
870a0fe4
AT
22#ifdef HAVE_CONFIG_H
23#include "config.h"
24#endif
9054d8a4 25#include "utility.hh"
d267d1bf 26#include "dynlistener.hh"
2470b36e 27#include "ws-auth.hh"
e611a06c 28#include "json.hh"
12c86877
BH
29#include "webserver.hh"
30#include "logger.hh"
31#include "statbag.hh"
32#include "misc.hh"
33#include "arguments.hh"
34#include "dns.hh"
6cc98ddf 35#include "comment.hh"
e611a06c 36#include "ueberbackend.hh"
dcc65f25 37#include <boost/format.hpp>
fa8fd4d2 38
9ac4a7c6 39#include "namespaces.hh"
6ec5e728 40#include "ws-api.hh"
ba1a571d 41#include "version.hh"
d29d5db7 42#include "dnsseckeeper.hh"
3c3c006b 43#include <iomanip>
0f0e73fe 44#include "zoneparser-tng.hh"
a426cb89 45#include "common_startup.hh"
bf269e28 46#include "auth-caches.hh"
8537b9f0 47
24afabad 48using json11::Json;
12c86877
BH
49
50extern StatBag S;
51
f63168e6 52static void patchZone(HttpRequest* req, HttpResponse* resp);
995473c8 53static void storeChangedPTRs(UeberBackend& B, vector<DNSResourceRecord>& new_ptrs);
f63168e6
CH
54static void makePtr(const DNSResourceRecord& rr, DNSResourceRecord* ptr);
55
dea47634 56AuthWebServer::AuthWebServer()
12c86877
BH
57{
58 d_start=time(0);
96d299db 59 d_min10=d_min5=d_min1=0;
c81c2ea8 60 d_ws = 0;
f17c93b4 61 d_tid = 0;
536ab56f 62 if(arg().mustDo("webserver") || arg().mustDo("api")) {
bbef8f04 63 d_ws = new WebServer(arg()["webserver-address"], arg().asNum("webserver-port"));
825fa717
CH
64 d_ws->bind();
65 }
12c86877
BH
66}
67
dea47634 68void AuthWebServer::go()
12c86877 69{
536ab56f
CH
70 S.doRings();
71 pthread_create(&d_tid, 0, webThreadHelper, this);
72 pthread_create(&d_tid, 0, statThreadHelper, this);
12c86877
BH
73}
74
dea47634 75void AuthWebServer::statThread()
12c86877
BH
76{
77 try {
78 for(;;) {
79 d_queries.submit(S.read("udp-queries"));
80 d_cachehits.submit(S.read("packetcache-hit"));
81 d_cachemisses.submit(S.read("packetcache-miss"));
82 d_qcachehits.submit(S.read("query-cache-hit"));
83 d_qcachemisses.submit(S.read("query-cache-miss"));
84 Utility::sleep(1);
85 }
86 }
87 catch(...) {
e6a9dde5 88 g_log<<Logger::Error<<"Webserver statThread caught an exception, dying"<<endl;
5bd2ea7b 89 _exit(1);
12c86877
BH
90 }
91}
92
dea47634 93void *AuthWebServer::statThreadHelper(void *p)
12c86877 94{
dea47634
CH
95 AuthWebServer *self=static_cast<AuthWebServer *>(p);
96 self->statThread();
12c86877
BH
97 return 0; // never reached
98}
99
dea47634 100void *AuthWebServer::webThreadHelper(void *p)
12c86877 101{
dea47634
CH
102 AuthWebServer *self=static_cast<AuthWebServer *>(p);
103 self->webThread();
12c86877
BH
104 return 0; // never reached
105}
106
9f3fdaa0
CH
107static string htmlescape(const string &s) {
108 string result;
109 for(string::const_iterator it=s.begin(); it!=s.end(); ++it) {
110 switch (*it) {
111 case '&':
c86a96f9 112 result += "&amp;";
9f3fdaa0
CH
113 break;
114 case '<':
115 result += "&lt;";
116 break;
117 case '>':
118 result += "&gt;";
119 break;
c7f59d62
PL
120 case '"':
121 result += "&quot;";
122 break;
9f3fdaa0
CH
123 default:
124 result += *it;
125 }
126 }
127 return result;
128}
129
12c86877
BH
130void printtable(ostringstream &ret, const string &ringname, const string &title, int limit=10)
131{
132 int tot=0;
133 int entries=0;
101b5d5d 134 vector<pair <string,unsigned int> >ring=S.getRing(ringname);
12c86877 135
1071abdd 136 for(vector<pair<string, unsigned int> >::const_iterator i=ring.begin(); i!=ring.end();++i) {
12c86877
BH
137 tot+=i->second;
138 entries++;
139 }
140
1071abdd 141 ret<<"<div class=\"panel\">";
c7f59d62 142 ret<<"<span class=resetring><i></i><a href=\"?resetring="<<htmlescape(ringname)<<"\">Reset</a></span>"<<endl;
1071abdd
CH
143 ret<<"<h2>"<<title<<"</h2>"<<endl;
144 ret<<"<div class=ringmeta>";
c7f59d62 145 ret<<"<a class=topXofY href=\"?ring="<<htmlescape(ringname)<<"\">Showing: Top "<<limit<<" of "<<entries<<"</a>"<<endl;
1071abdd 146 ret<<"<span class=resizering>Resize: ";
bb3c3f50 147 unsigned int sizes[]={10,100,500,1000,10000,500000,0};
12c86877
BH
148 for(int i=0;sizes[i];++i) {
149 if(S.getRingSize(ringname)!=sizes[i])
c7f59d62 150 ret<<"<a href=\"?resizering="<<htmlescape(ringname)<<"&amp;size="<<sizes[i]<<"\">"<<sizes[i]<<"</a> ";
12c86877
BH
151 else
152 ret<<"("<<sizes[i]<<") ";
153 }
1071abdd 154 ret<<"</span></div>";
12c86877 155
1071abdd 156 ret<<"<table class=\"data\">";
12c86877 157 int printed=0;
f5cb7e61 158 int total=max(1,tot);
bb3c3f50 159 for(vector<pair<string,unsigned int> >::const_iterator i=ring.begin();limit && i!=ring.end();++i,--limit) {
dea47634 160 ret<<"<tr><td>"<<htmlescape(i->first)<<"</td><td>"<<i->second<<"</td><td align=right>"<< AuthWebServer::makePercentage(i->second*100.0/total)<<"</td>"<<endl;
12c86877
BH
161 printed+=i->second;
162 }
163 ret<<"<tr><td colspan=3></td></tr>"<<endl;
164 if(printed!=tot)
dea47634 165 ret<<"<tr><td><b>Rest:</b></td><td><b>"<<tot-printed<<"</b></td><td align=right><b>"<< AuthWebServer::makePercentage((tot-printed)*100.0/total)<<"</b></td>"<<endl;
12c86877 166
e2a77e08 167 ret<<"<tr><td><b>Total:</b></td><td><b>"<<tot<<"</b></td><td align=right><b>100%</b></td>";
1071abdd 168 ret<<"</table></div>"<<endl;
12c86877
BH
169}
170
dea47634 171void AuthWebServer::printvars(ostringstream &ret)
12c86877 172{
1071abdd 173 ret<<"<div class=panel><h2>Variables</h2><table class=\"data\">"<<endl;
12c86877
BH
174
175 vector<string>entries=S.getEntries();
176 for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i) {
177 ret<<"<tr><td>"<<*i<<"</td><td>"<<S.read(*i)<<"</td><td>"<<S.getDescrip(*i)<<"</td>"<<endl;
178 }
e2a77e08 179
1071abdd 180 ret<<"</table></div>"<<endl;
12c86877
BH
181}
182
dea47634 183void AuthWebServer::printargs(ostringstream &ret)
12c86877 184{
e2a77e08 185 ret<<"<table border=1><tr><td colspan=3 bgcolor=\"#0000ff\"><font color=\"#ffffff\">Arguments</font></td>"<<endl;
12c86877
BH
186
187 vector<string>entries=arg().list();
188 for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i) {
189 ret<<"<tr><td>"<<*i<<"</td><td>"<<arg()[*i]<<"</td><td>"<<arg().getHelp(*i)<<"</td>"<<endl;
190 }
191}
192
dea47634 193string AuthWebServer::makePercentage(const double& val)
b6f57093
BH
194{
195 return (boost::format("%.01f%%") % val).str();
196}
197
dea47634 198void AuthWebServer::indexfunction(HttpRequest* req, HttpResponse* resp)
12c86877 199{
583ea80d
CH
200 if(!req->getvars["resetring"].empty()) {
201 if (S.ringExists(req->getvars["resetring"]))
202 S.resetRing(req->getvars["resetring"]);
d7b8730e 203 resp->status = 302;
0665b7e6 204 resp->headers["Location"] = req->url.path;
80d59cd1 205 return;
12c86877 206 }
583ea80d 207 if(!req->getvars["resizering"].empty()){
335da0ba 208 int size=std::stoi(req->getvars["size"]);
583ea80d 209 if (S.ringExists(req->getvars["resizering"]) && size > 0 && size <= 500000)
335da0ba 210 S.resizeRing(req->getvars["resizering"], std::stoi(req->getvars["size"]));
d7b8730e 211 resp->status = 302;
0665b7e6 212 resp->headers["Location"] = req->url.path;
80d59cd1 213 return;
12c86877
BH
214 }
215
216 ostringstream ret;
217
1071abdd
CH
218 ret<<"<!DOCTYPE html>"<<endl;
219 ret<<"<html><head>"<<endl;
220 ret<<"<title>PowerDNS Authoritative Server Monitor</title>"<<endl;
221 ret<<"<link rel=\"stylesheet\" href=\"style.css\"/>"<<endl;
222 ret<<"</head><body>"<<endl;
223
224 ret<<"<div class=\"row\">"<<endl;
225 ret<<"<div class=\"headl columns\">";
a1caa8b8 226 ret<<"<a href=\"/\" id=\"appname\">PowerDNS "<<htmlescape(VERSION);
1071abdd 227 if(!arg()["config-name"].empty()) {
a1caa8b8 228 ret<<" ["<<htmlescape(arg()["config-name"])<<"]";
1071abdd
CH
229 }
230 ret<<"</a></div>"<<endl;
231 ret<<"<div class=\"headr columns\"></div></div>";
232 ret<<"<div class=\"row\"><div class=\"all columns\">";
12c86877
BH
233
234 time_t passed=time(0)-s_starttime;
235
e2a77e08
KM
236 ret<<"<p>Uptime: "<<
237 humanDuration(passed)<<
238 "<br>"<<endl;
12c86877 239
395b07ea 240 ret<<"Queries/second, 1, 5, 10 minute averages: "<<std::setprecision(3)<<
3e1cd1f4 241 (int)d_queries.get1()<<", "<<
242 (int)d_queries.get5()<<", "<<
243 (int)d_queries.get10()<<". Max queries/second: "<<(int)d_queries.getMax()<<
12c86877 244 "<br>"<<endl;
1d6b70f9 245
f6154a3b 246 if(d_cachemisses.get10()+d_cachehits.get10()>0)
b6f57093 247 ret<<"Cache hitrate, 1, 5, 10 minute averages: "<<
f6154a3b
CH
248 makePercentage((d_cachehits.get1()*100.0)/((d_cachehits.get1())+(d_cachemisses.get1())))<<", "<<
249 makePercentage((d_cachehits.get5()*100.0)/((d_cachehits.get5())+(d_cachemisses.get5())))<<", "<<
250 makePercentage((d_cachehits.get10()*100.0)/((d_cachehits.get10())+(d_cachemisses.get10())))<<
b6f57093 251 "<br>"<<endl;
12c86877 252
f6154a3b 253 if(d_qcachemisses.get10()+d_qcachehits.get10()>0)
395b07ea 254 ret<<"Backend query cache hitrate, 1, 5, 10 minute averages: "<<std::setprecision(2)<<
f6154a3b
CH
255 makePercentage((d_qcachehits.get1()*100.0)/((d_qcachehits.get1())+(d_qcachemisses.get1())))<<", "<<
256 makePercentage((d_qcachehits.get5()*100.0)/((d_qcachehits.get5())+(d_qcachemisses.get5())))<<", "<<
257 makePercentage((d_qcachehits.get10()*100.0)/((d_qcachehits.get10())+(d_qcachemisses.get10())))<<
b6f57093 258 "<br>"<<endl;
12c86877 259
395b07ea 260 ret<<"Backend query load, 1, 5, 10 minute averages: "<<std::setprecision(3)<<
3e1cd1f4 261 (int)d_qcachemisses.get1()<<", "<<
262 (int)d_qcachemisses.get5()<<", "<<
263 (int)d_qcachemisses.get10()<<". Max queries/second: "<<(int)d_qcachemisses.getMax()<<
12c86877
BH
264 "<br>"<<endl;
265
1071abdd 266 ret<<"Total queries: "<<S.read("udp-queries")<<". Question/answer latency: "<<S.read("latency")/1000.0<<"ms</p><br>"<<endl;
583ea80d 267 if(req->getvars["ring"].empty()) {
12c86877
BH
268 vector<string>entries=S.listRings();
269 for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i)
270 printtable(ret,*i,S.getRingTitle(*i));
271
f6154a3b 272 printvars(ret);
12c86877 273 if(arg().mustDo("webserver-print-arguments"))
f6154a3b 274 printargs(ret);
12c86877 275 }
bea69e32 276 else if(S.ringExists(req->getvars["ring"]))
583ea80d 277 printtable(ret,req->getvars["ring"],S.getRingTitle(req->getvars["ring"]),100);
12c86877 278
1071abdd 279 ret<<"</div></div>"<<endl;
a4167e57 280 ret<<"<footer class=\"row\">"<<fullVersionString()<<"<br>&copy; 2013 - 2018 <a href=\"http://www.powerdns.com/\">PowerDNS.COM BV</a>.</footer>"<<endl;
12c86877
BH
281 ret<<"</body></html>"<<endl;
282
80d59cd1 283 resp->body = ret.str();
61f5d289 284 resp->status = 200;
12c86877
BH
285}
286
1d6b70f9
CH
287/** Helper to build a record content as needed. */
288static inline string makeRecordContent(const QType& qtype, const string& content, bool noDot) {
289 // noDot: for backend storage, pass true. for API users, pass false.
9a2c1e06 290 auto drc = DNSRecordContent::makeunique(qtype.getCode(), QClass::IN, content);
7fe1a82b 291 return drc->getZoneRepresentation(noDot);
1d6b70f9
CH
292}
293
294/** "Normalize" record content for API consumers. */
295static inline string makeApiRecordContent(const QType& qtype, const string& content) {
296 return makeRecordContent(qtype, content, false);
297}
298
299/** "Normalize" record content for backend storage. */
300static inline string makeBackendRecordContent(const QType& qtype, const string& content) {
301 return makeRecordContent(qtype, content, true);
302}
303
ce846be6 304static Json::object getZoneInfo(const DomainInfo& di, DNSSECKeeper *dk) {
290a083d 305 string zoneId = apiZoneNameToId(di.zone);
d622042f 306 vector<string> masters;
307 for(const auto& m : di.masters)
308 masters.push_back(m.toStringWithPortExcept(53));
24ded6cc 309
62a9a74c
CH
310 return Json::object {
311 // id is the canonical lookup key, which doesn't actually match the name (in some cases)
312 { "id", zoneId },
16e25450 313 { "url", "/api/v1/servers/localhost/zones/" + zoneId },
62a9a74c
CH
314 { "name", di.zone.toString() },
315 { "kind", di.getKindString() },
ce846be6 316 { "dnssec", dk->isSecuredZone(di.zone) },
62a9a74c 317 { "account", di.account },
d622042f 318 { "masters", masters },
62a9a74c
CH
319 { "serial", (double)di.serial },
320 { "notified_serial", (double)di.notified_serial },
321 { "last_check", (double)di.last_check }
322 };
c04b5870
CH
323}
324
986e4858
PL
325static bool shouldDoRRSets(HttpRequest* req) {
326 if (req->getvars.count("rrsets") == 0 || req->getvars["rrsets"] == "true")
327 return true;
328 if (req->getvars["rrsets"] == "false")
329 return false;
330 throw ApiException("'rrsets' request parameter value '"+req->getvars["rrsets"]+"' is not supported");
331}
332
333static void fillZone(const DNSName& zonename, HttpResponse* resp, bool doRRSets) {
1abb81f4 334 UeberBackend B;
1abb81f4 335 DomainInfo di;
77bfe8de
PL
336 if(!B.getDomainInfo(zonename, di)) {
337 throw HttpNotFoundException();
338 }
1abb81f4 339
adef67eb 340 DNSSECKeeper dk(&B);
ce846be6 341 Json::object doc = getZoneInfo(di, &dk);
62a9a74c 342 // extra stuff getZoneInfo doesn't do for us (more expensive)
d29d5db7
CH
343 string soa_edit_api;
344 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api);
62a9a74c 345 doc["soa_edit_api"] = soa_edit_api;
6bb25159
MS
346 string soa_edit;
347 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit);
62a9a74c 348 doc["soa_edit"] = soa_edit;
986e4858
PL
349 string nsec3param;
350 di.backend->getDomainMetadataOne(zonename, "NSEC3PARAM", nsec3param);
351 doc["nsec3param"] = nsec3param;
352 string nsec3narrow;
353 bool nsec3narrowbool = false;
354 di.backend->getDomainMetadataOne(zonename, "NSEC3NARROW", nsec3narrow);
355 if (nsec3narrow == "1")
356 nsec3narrowbool = true;
357 doc["nsec3narrow"] = nsec3narrowbool;
358
359 string api_rectify;
360 di.backend->getDomainMetadataOne(zonename, "API-RECTIFY", api_rectify);
361 doc["api_rectify"] = (api_rectify == "1");
362
363 if (doRRSets) {
364 vector<DNSResourceRecord> records;
365 vector<Comment> comments;
366
367 // load all records + sort
368 {
369 DNSResourceRecord rr;
370 di.backend->list(zonename, di.id, true); // incl. disabled
371 while(di.backend->get(rr)) {
372 if (!rr.qtype.getCode())
373 continue; // skip empty non-terminals
374 records.push_back(rr);
375 }
376 sort(records.begin(), records.end(), [](const DNSResourceRecord& a, const DNSResourceRecord& b) {
377 if (a.qname == b.qname) {
378 return b.qtype < a.qtype;
379 }
380 return b.qname < a.qname;
381 });
6754ef71 382 }
6754ef71 383
986e4858
PL
384 // load all comments + sort
385 {
386 Comment comment;
387 di.backend->listComments(di.id);
388 while(di.backend->getComment(comment)) {
389 comments.push_back(comment);
390 }
391 sort(comments.begin(), comments.end(), [](const Comment& a, const Comment& b) {
392 if (a.qname == b.qname) {
393 return b.qtype < a.qtype;
394 }
395 return b.qname < a.qname;
396 });
6754ef71 397 }
6754ef71 398
986e4858
PL
399 Json::array rrsets;
400 Json::object rrset;
401 Json::array rrset_records;
402 Json::array rrset_comments;
403 DNSName current_qname;
404 QType current_qtype;
405 uint32_t ttl;
406 auto rit = records.begin();
407 auto cit = comments.begin();
408
409 while (rit != records.end() || cit != comments.end()) {
410 if (cit == comments.end() || (rit != records.end() && (cit->qname.toString() <= rit->qname.toString() || cit->qtype < rit->qtype || cit->qtype == rit->qtype))) {
411 current_qname = rit->qname;
412 current_qtype = rit->qtype;
413 ttl = rit->ttl;
414 } else {
415 current_qname = cit->qname;
416 current_qtype = cit->qtype;
417 ttl = 0;
418 }
6754ef71 419
986e4858
PL
420 while(rit != records.end() && rit->qname == current_qname && rit->qtype == current_qtype) {
421 ttl = min(ttl, rit->ttl);
422 rrset_records.push_back(Json::object {
423 { "disabled", rit->disabled },
424 { "content", makeApiRecordContent(rit->qtype, rit->content) }
425 });
426 rit++;
427 }
428 while (cit != comments.end() && cit->qname == current_qname && cit->qtype == current_qtype) {
429 rrset_comments.push_back(Json::object {
430 { "modified_at", (double)cit->modified_at },
431 { "account", cit->account },
432 { "content", cit->content }
433 });
434 cit++;
435 }
436
437 rrset["name"] = current_qname.toString();
438 rrset["type"] = current_qtype.getName();
439 rrset["records"] = rrset_records;
440 rrset["comments"] = rrset_comments;
441 rrset["ttl"] = (double)ttl;
442 rrsets.push_back(rrset);
443 rrset.clear();
444 rrset_records.clear();
445 rrset_comments.clear();
6754ef71
CH
446 }
447
986e4858 448 doc["rrsets"] = rrsets;
6754ef71
CH
449 }
450
669822d0 451 resp->setBody(doc);
1abb81f4
CH
452}
453
6ec5e728
CH
454void productServerStatisticsFetch(map<string,string>& out)
455{
a45303b8 456 vector<string> items = S.getEntries();
ff05fd12 457 for(const string& item : items) {
335da0ba 458 out[item] = std::to_string(S.read(item));
a45303b8
CH
459 }
460
461 // add uptime
335da0ba 462 out["uptime"] = std::to_string(time(0) - s_starttime);
c67bf8c5
CH
463}
464
24ded6cc
CHB
465static void validateGatheredRRType(const DNSResourceRecord& rr) {
466 if (rr.qtype.getCode() == QType::OPT || rr.qtype.getCode() == QType::TSIG) {
467 throw ApiException("RRset "+rr.qname.toString()+" IN "+rr.qtype.getName()+": invalid type given");
468 }
469}
470
6754ef71 471static void gatherRecords(const Json container, const DNSName& qname, const QType qtype, const int ttl, vector<DNSResourceRecord>& new_records, vector<DNSResourceRecord>& new_ptrs) {
f63168e6
CH
472 UeberBackend B;
473 DNSResourceRecord rr;
6754ef71
CH
474 rr.qname = qname;
475 rr.qtype = qtype;
476 rr.auth = 1;
477 rr.ttl = ttl;
24ded6cc
CHB
478
479 validateGatheredRRType(rr);
1f68b185 480 for(auto record : container["records"].array_items()) {
1f68b185 481 string content = stringFromJson(record, "content");
1f68b185
CH
482 rr.disabled = boolFromJson(record, "disabled");
483
1f68b185
CH
484 // validate that the client sent something we can actually parse, and require that data to be dotted.
485 try {
486 if (rr.qtype.getCode() != QType::AAAA) {
487 string tmp = makeApiRecordContent(rr.qtype, content);
488 if (!pdns_iequals(tmp, content)) {
489 throw std::runtime_error("Not in expected format (parsed as '"+tmp+"')");
490 }
491 } else {
492 struct in6_addr tmpbuf;
493 if (inet_pton(AF_INET6, content.c_str(), &tmpbuf) != 1 || content.find('.') != string::npos) {
494 throw std::runtime_error("Invalid IPv6 address");
1e5b9ab9 495 }
f63168e6 496 }
1f68b185
CH
497 rr.content = makeBackendRecordContent(rr.qtype, content);
498 }
499 catch(std::exception& e)
500 {
501 throw ApiException("Record "+rr.qname.toString()+"/"+rr.qtype.getName()+" '"+content+"': "+e.what());
502 }
f63168e6 503
1f68b185
CH
504 if ((rr.qtype.getCode() == QType::A || rr.qtype.getCode() == QType::AAAA) &&
505 boolFromJson(record, "set-ptr", false) == true) {
506 DNSResourceRecord ptr;
507 makePtr(rr, &ptr);
f63168e6 508
1f68b185 509 // verify that there's a zone for the PTR
1f68b185 510 SOAData sd;
cec52de6 511 if (!B.getAuth(ptr.qname, QType(QType::PTR), &sd, false))
1f68b185 512 throw ApiException("Could not find domain for PTR '"+ptr.qname.toString()+"' requested for '"+ptr.content+"'");
f63168e6 513
1f68b185
CH
514 ptr.domain_id = sd.domain_id;
515 new_ptrs.push_back(ptr);
f63168e6 516 }
1f68b185
CH
517
518 new_records.push_back(rr);
f63168e6
CH
519 }
520}
521
6754ef71 522static void gatherComments(const Json container, const DNSName& qname, const QType qtype, vector<Comment>& new_comments) {
f63168e6 523 Comment c;
6754ef71
CH
524 c.qname = qname;
525 c.qtype = qtype;
f63168e6
CH
526
527 time_t now = time(0);
1f68b185 528 for (auto comment : container["comments"].array_items()) {
1f68b185
CH
529 c.modified_at = intFromJson(comment, "modified_at", now);
530 c.content = stringFromJson(comment, "content");
531 c.account = stringFromJson(comment, "account");
532 new_comments.push_back(c);
f63168e6
CH
533 }
534}
6cc98ddf 535
986e4858
PL
536static void checkDefaultDNSSECAlgos() {
537 int k_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-ksk-algorithm"]);
538 int z_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-zsk-algorithm"]);
539 int k_size = arg().asNum("default-ksk-size");
540 int z_size = arg().asNum("default-zsk-size");
541
542 // Sanity check DNSSEC parameters
543 if (::arg()["default-zsk-algorithm"] != "") {
544 if (k_algo == -1)
545 throw ApiException("default-ksk-algorithm setting is set to unknown algorithm: " + ::arg()["default-ksk-algorithm"]);
546 else if (k_algo <= 10 && k_size == 0)
547 throw ApiException("default-ksk-algorithm is set to an algorithm("+::arg()["default-ksk-algorithm"]+") that requires a non-zero default-ksk-size!");
548 }
549
550 if (::arg()["default-zsk-algorithm"] != "") {
551 if (z_algo == -1)
552 throw ApiException("default-zsk-algorithm setting is set to unknown algorithm: " + ::arg()["default-zsk-algorithm"]);
553 else if (z_algo <= 10 && z_size == 0)
554 throw ApiException("default-zsk-algorithm is set to an algorithm("+::arg()["default-zsk-algorithm"]+") that requires a non-zero default-zsk-size!");
555 }
556}
557
89a7e706
PL
558static void throwUnableToSecure(const DNSName& zonename) {
559 throw ApiException("No backend was able to secure '" + zonename.toString() + "', most likely because no DNSSEC"
560 + "capable backends are loaded, or because the backends have DNSSEC disabled. Check your configuration.");
561}
562
986e4858 563static void updateDomainSettingsFromDocument(UeberBackend& B, const DomainInfo& di, const DNSName& zonename, const Json document) {
1f68b185 564 string zonemaster;
986e4858 565 bool shouldRectify = false;
1f68b185
CH
566 for(auto value : document["masters"].array_items()) {
567 string master = value.string_value();
568 if (master.empty())
569 throw ApiException("Master can not be an empty string");
570 zonemaster += master + " ";
bb9fd223
CH
571 }
572
986e4858
PL
573 if (zonemaster != "") {
574 di.backend->setMaster(zonename, zonemaster);
575 }
576 if (document["kind"].is_string()) {
577 di.backend->setKind(zonename, DomainInfo::stringToKind(stringFromJson(document, "kind")));
578 }
1f68b185
CH
579 if (document["soa_edit_api"].is_string()) {
580 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT-API", document["soa_edit_api"].string_value());
d29d5db7 581 }
1f68b185
CH
582 if (document["soa_edit"].is_string()) {
583 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT", document["soa_edit"].string_value());
6bb25159 584 }
c00908f1
PL
585 try {
586 bool api_rectify = boolFromJson(document, "api_rectify");
587 di.backend->setDomainMetadataOne(zonename, "API-RECTIFY", api_rectify ? "1" : "0");
986e4858 588 }
819861fa 589 catch (const JsonException&) {}
c00908f1 590
1f68b185
CH
591 if (document["account"].is_string()) {
592 di.backend->setAccount(zonename, document["account"].string_value());
79532aa7 593 }
986e4858
PL
594
595 DNSSECKeeper dk(&B);
596 bool dnssecInJSON = false;
597 bool dnssecDocVal = false;
598
599 try {
600 dnssecDocVal = boolFromJson(document, "dnssec");
601 dnssecInJSON = true;
602 }
819861fa 603 catch (const JsonException&) {}
986e4858
PL
604
605 bool isDNSSECZone = dk.isSecuredZone(zonename);
606
607 if (dnssecInJSON) {
608 if (dnssecDocVal) {
609 if (!isDNSSECZone) {
610 checkDefaultDNSSECAlgos();
611
612 int k_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-ksk-algorithm"]);
613 int z_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-zsk-algorithm"]);
614 int k_size = arg().asNum("default-ksk-size");
615 int z_size = arg().asNum("default-zsk-size");
616
617 if (k_algo != -1) {
618 int64_t id;
619 if (!dk.addKey(zonename, true, k_algo, id, k_size)) {
89a7e706 620 throwUnableToSecure(zonename);
986e4858
PL
621 }
622 }
623
624 if (z_algo != -1) {
625 int64_t id;
626 if (!dk.addKey(zonename, false, z_algo, id, z_size)) {
89a7e706 627 throwUnableToSecure(zonename);
986e4858
PL
628 }
629 }
630
631 // Used later for NSEC3PARAM
632 isDNSSECZone = dk.isSecuredZone(zonename);
633
634 if (!isDNSSECZone) {
89a7e706 635 throwUnableToSecure(zonename);
986e4858
PL
636 }
637 shouldRectify = true;
638 }
639 } else {
640 // "dnssec": false in json
641 if (isDNSSECZone) {
cbe8b186
PL
642 string info, error;
643 if (!dk.unSecureZone(zonename, error, info)) {
644 throw ApiException("Error while un-securing zone '"+ zonename.toString()+"': " + error);
645 }
646 isDNSSECZone = dk.isSecuredZone(zonename);
647 if (isDNSSECZone) {
648 throw ApiException("Unable to un-secure zone '"+ zonename.toString()+"'");
649 }
650 shouldRectify = true;
986e4858
PL
651 }
652 }
653 }
654
655 if(document["nsec3param"].string_value().length() > 0) {
656 shouldRectify = true;
657 NSEC3PARAMRecordContent ns3pr(document["nsec3param"].string_value());
658 string error_msg = "";
659 if (!isDNSSECZone) {
660 throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"', but zone is not DNSSEC secured.");
661 }
662 if (!dk.checkNSEC3PARAM(ns3pr, error_msg)) {
663 throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"' are invalid. " + error_msg);
664 }
665 if (!dk.setNSEC3PARAM(zonename, ns3pr, boolFromJson(document, "nsec3narrow", false))) {
666 throw ApiException("NSEC3PARAMs provided for zone '" + zonename.toString() +
667 "' passed our basic sanity checks, but cannot be used with the current backend.");
668 }
669 }
670
a843c67e
KM
671 if (shouldRectify && !dk.isPresigned(zonename)) {
672 // Rectify
673 string api_rectify;
674 di.backend->getDomainMetadataOne(zonename, "API-RECTIFY", api_rectify);
675 if (api_rectify == "1") {
676 string info;
677 string error_msg;
678 if (!dk.rectifyZone(zonename, error_msg, info, true)) {
679 throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg);
680 }
681 }
682
683 // Increase serial
684 string soa_edit_api_kind;
685 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind);
686 if (!soa_edit_api_kind.empty()) {
687 SOAData sd;
688 if (!B.getSOAUncached(zonename, sd, true))
689 return;
690
691 string soa_edit_kind;
692 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit_kind);
693
694 DNSResourceRecord rr;
695 if (makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, rr)) {
696 if (!di.backend->replaceRRSet(di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
697 throw ApiException("Hosting backend does not support editing records.");
698 }
699 }
a843c67e 700 }
986e4858 701 }
bb9fd223
CH
702}
703
24e11043
CJ
704static bool isValidMetadataKind(const string& kind, bool readonly) {
705 static vector<string> builtinOptions {
706 "ALLOW-AXFR-FROM",
707 "AXFR-SOURCE",
708 "ALLOW-DNSUPDATE-FROM",
709 "TSIG-ALLOW-DNSUPDATE",
710 "FORWARD-DNSUPDATE",
711 "SOA-EDIT-DNSUPDATE",
4c5b6925 712 "NOTIFY-DNSUPDATE",
24e11043
CJ
713 "ALSO-NOTIFY",
714 "AXFR-MASTER-TSIG",
715 "GSS-ALLOW-AXFR-PRINCIPAL",
716 "GSS-ACCEPTOR-PRINCIPAL",
717 "IXFR",
718 "LUA-AXFR-SCRIPT",
719 "NSEC3NARROW",
720 "NSEC3PARAM",
721 "PRESIGNED",
722 "PUBLISH-CDNSKEY",
723 "PUBLISH-CDS",
724 "SOA-EDIT",
725 "TSIG-ALLOW-AXFR",
726 "TSIG-ALLOW-DNSUPDATE"
727 };
728
729 // the following options do not allow modifications via API
730 static vector<string> protectedOptions {
986e4858 731 "API-RECTIFY",
24e11043
CJ
732 "NSEC3NARROW",
733 "NSEC3PARAM",
734 "PRESIGNED",
735 "LUA-AXFR-SCRIPT"
736 };
737
9ac4e6d5
PL
738 if (kind.find("X-") == 0)
739 return true;
740
24e11043
CJ
741 bool found = false;
742
d8043c73 743 for (const string& s : builtinOptions) {
24e11043 744 if (kind == s) {
d8043c73 745 for (const string& s2 : protectedOptions) {
24e11043
CJ
746 if (!readonly && s == s2)
747 return false;
748 }
749 found = true;
750 break;
751 }
752 }
753
754 return found;
755}
756
757static void apiZoneMetadata(HttpRequest* req, HttpResponse *resp) {
758 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
d38e81e6 759
24e11043 760 UeberBackend B;
d38e81e6 761 DomainInfo di;
77bfe8de
PL
762 if (!B.getDomainInfo(zonename, di)) {
763 throw HttpNotFoundException();
764 }
24e11043
CJ
765
766 if (req->method == "GET") {
767 map<string, vector<string> > md;
768 Json::array document;
769
770 if (!B.getAllDomainMetadata(zonename, md))
771 throw HttpNotFoundException();
772
773 for (const auto& i : md) {
774 Json::array entries;
775 for (string j : i.second)
776 entries.push_back(j);
777
778 Json::object key {
779 { "type", "Metadata" },
780 { "kind", i.first },
781 { "metadata", entries }
782 };
783
784 document.push_back(key);
785 }
786
787 resp->setBody(document);
788 } else if (req->method == "POST" && !::arg().mustDo("api-readonly")) {
789 auto document = req->json();
790 string kind;
791 vector<string> entries;
792
793 try {
794 kind = stringFromJson(document, "kind");
819861fa 795 } catch (const JsonException&) {
24e11043
CJ
796 throw ApiException("kind is not specified or not a string");
797 }
798
799 if (!isValidMetadataKind(kind, false))
800 throw ApiException("Unsupported metadata kind '" + kind + "'");
801
802 vector<string> vecMetadata;
c6720e79
CJ
803
804 if (!B.getDomainMetadata(zonename, kind, vecMetadata))
805 throw ApiException("Could not retrieve metadata entries for domain '" +
806 zonename.toString() + "'");
807
24e11043
CJ
808 auto& metadata = document["metadata"];
809 if (!metadata.is_array())
810 throw ApiException("metadata is not specified or not an array");
811
812 for (const auto& i : metadata.array_items()) {
813 if (!i.is_string())
814 throw ApiException("metadata must be strings");
c6720e79
CJ
815 else if (std::find(vecMetadata.cbegin(),
816 vecMetadata.cend(),
817 i.string_value()) == vecMetadata.cend()) {
818 vecMetadata.push_back(i.string_value());
819 }
24e11043
CJ
820 }
821
822 if (!B.setDomainMetadata(zonename, kind, vecMetadata))
c6720e79
CJ
823 throw ApiException("Could not update metadata entries for domain '" +
824 zonename.toString() + "'");
825
826 Json::array respMetadata;
827 for (const string& s : vecMetadata)
828 respMetadata.push_back(s);
829
830 Json::object key {
831 { "type", "Metadata" },
832 { "kind", document["kind"] },
833 { "metadata", respMetadata }
834 };
24e11043 835
24e11043 836 resp->status = 201;
c6720e79 837 resp->setBody(key);
24e11043
CJ
838 } else
839 throw HttpMethodNotAllowedException();
840}
841
842static void apiZoneMetadataKind(HttpRequest* req, HttpResponse* resp) {
843 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
d38e81e6 844
24e11043 845 UeberBackend B;
d38e81e6 846 DomainInfo di;
77bfe8de
PL
847 if (!B.getDomainInfo(zonename, di)) {
848 throw HttpNotFoundException();
849 }
d38e81e6
PL
850
851 string kind = req->parameters["kind"];
24e11043
CJ
852
853 if (req->method == "GET") {
854 vector<string> metadata;
855 Json::object document;
856 Json::array entries;
857
858 if (!B.getDomainMetadata(zonename, kind, metadata))
859 throw HttpNotFoundException();
860 else if (!isValidMetadataKind(kind, true))
861 throw ApiException("Unsupported metadata kind '" + kind + "'");
862
863 document["type"] = "Metadata";
864 document["kind"] = kind;
865
866 for (const string& i : metadata)
867 entries.push_back(i);
868
869 document["metadata"] = entries;
870 resp->setBody(document);
871 } else if (req->method == "PUT" && !::arg().mustDo("api-readonly")) {
872 auto document = req->json();
873
874 if (!isValidMetadataKind(kind, false))
875 throw ApiException("Unsupported metadata kind '" + kind + "'");
876
877 vector<string> vecMetadata;
878 auto& metadata = document["metadata"];
879 if (!metadata.is_array())
880 throw ApiException("metadata is not specified or not an array");
881
882 for (const auto& i : metadata.array_items()) {
883 if (!i.is_string())
884 throw ApiException("metadata must be strings");
885 vecMetadata.push_back(i.string_value());
886 }
887
888 if (!B.setDomainMetadata(zonename, kind, vecMetadata))
889 throw ApiException("Could not update metadata entries for domain '" + zonename.toString() + "'");
890
891 Json::object key {
892 { "type", "Metadata" },
893 { "kind", kind },
894 { "metadata", metadata }
895 };
896
897 resp->setBody(key);
898 } else if (req->method == "DELETE" && !::arg().mustDo("api-readonly")) {
899 if (!isValidMetadataKind(kind, false))
900 throw ApiException("Unsupported metadata kind '" + kind + "'");
901
902 vector<string> md; // an empty vector will do it
903 if (!B.setDomainMetadata(zonename, kind, md))
904 throw ApiException("Could not delete metadata for domain '" + zonename.toString() + "' (" + kind + ")");
905 } else
906 throw HttpMethodNotAllowedException();
907}
908
60b0a236
BZ
909static void apiZoneCryptokeysGET(DNSName zonename, int inquireKeyId, HttpResponse *resp, DNSSECKeeper *dk) {
910 DNSSECKeeper::keyset_t keyset=dk->getKeys(zonename, false);
4b7f120a 911
997cab68
BZ
912 bool inquireSingleKey = inquireKeyId >= 0;
913
24afabad 914 Json::array doc;
29704f66 915 for(const auto& value : keyset) {
997cab68 916 if (inquireSingleKey && (unsigned)inquireKeyId != value.second.id) {
29704f66 917 continue;
38809e97 918 }
24afabad 919
b6bd795c 920 string keyType;
60b0a236 921 switch (value.second.keyType) {
b6bd795c
PL
922 case DNSSECKeeper::KSK: keyType="ksk"; break;
923 case DNSSECKeeper::ZSK: keyType="zsk"; break;
924 case DNSSECKeeper::CSK: keyType="csk"; break;
925 }
926
24afabad 927 Json::object key {
997cab68
BZ
928 { "type", "Cryptokey" },
929 { "id", (int)value.second.id },
930 { "active", value.second.active },
931 { "keytype", keyType },
932 { "flags", (uint16_t)value.first.d_flags },
5d9c6182
PL
933 { "dnskey", value.first.getDNSKEY().getZoneRepresentation() },
934 { "algorithm", DNSSECKeeper::algorithm2name(value.first.d_algorithm) },
935 { "bits", value.first.getKey()->getBits() }
24afabad
CH
936 };
937
b6bd795c 938 if (value.second.keyType == DNSSECKeeper::KSK || value.second.keyType == DNSSECKeeper::CSK) {
24afabad 939 Json::array dses;
8455425c 940 for(const uint8_t keyid : { DNSSECKeeper::SHA1, DNSSECKeeper::SHA256, DNSSECKeeper::GOST, DNSSECKeeper::SHA384 })
997cab68
BZ
941 try {
942 dses.push_back(makeDSFromDNSKey(zonename, value.first.getDNSKEY(), keyid).getZoneRepresentation());
943 } catch (...) {}
24afabad 944 key["ds"] = dses;
4b7f120a 945 }
29704f66
CH
946
947 if (inquireSingleKey) {
948 key["privatekey"] = value.first.getKey()->convertToISC();
949 resp->setBody(key);
950 return;
951 }
24afabad 952 doc.push_back(key);
4b7f120a
MS
953 }
954
29704f66
CH
955 if (inquireSingleKey) {
956 // we came here because we couldn't find the requested key.
957 throw HttpNotFoundException();
958 }
4b7f120a 959 resp->setBody(doc);
997cab68
BZ
960
961}
962
963/*
964 * This method handles DELETE requests for URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
965 * It deletes a key from :zone_name specified by :cryptokey_id.
966 * Server Answers:
60b0a236
BZ
967 * Case 1: the backend returns true on removal. This means the key is gone.
968 * The server returns 200 OK, no body.
955cbfd0 969 * Case 2: the backend returns false on removal. An error occurred.
60b0a236 970 * The sever returns 422 Unprocessable Entity with message "Could not DELETE :cryptokey_id".
997cab68 971 * */
60b0a236
BZ
972static void apiZoneCryptokeysDELETE(DNSName zonename, int inquireKeyId, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
973 if (dk->removeKey(zonename, inquireKeyId)) {
974 resp->body = "";
975 resp->status = 200;
997cab68
BZ
976 } else {
977 resp->setErrorResult("Could not DELETE " + req->parameters["key_id"], 422);
978 }
979}
980
981/*
982 * This method adds a key to a zone by generate it or content parameter.
983 * Parameter:
984 * {
5d9c6182 985 * "privatekey" : "key The format used is compatible with BIND and NSD/LDNS" <string>
997cab68
BZ
986 * "keytype" : "ksk|zsk" <string>
987 * "active" : "true|false" <value>
5d9c6182 988 * "algorithm" : "key generation algorithm name as default"<string> https://doc.powerdns.com/md/authoritative/dnssec/#supported-algorithms
997cab68
BZ
989 * "bits" : number of bits <int>
990 * }
991 *
992 * Response:
993 * Case 1: keytype isn't ksk|zsk
994 * The server returns 422 Unprocessable Entity {"error" : "Invalid keytype 'keytype'"}
60b0a236
BZ
995 * Case 2: 'bits' must be a positive integer value.
996 * The server returns 422 Unprocessable Entity {"error" : "'bits' must be a positive integer value."}
5d9c6182 997 * Case 3: The "algorithm" isn't supported
997cab68 998 * The server returns 422 Unprocessable Entity {"error" : "Unknown algorithm: 'algo'"}
60b0a236 999 * Case 4: Algorithm <= 10 and no bits were passed
997cab68 1000 * The server returns 422 Unprocessable Entity {"error" : "Creating an algorithm algo key requires the size (in bits) to be passed"}
60b0a236
BZ
1001 * Case 5: The wrong keysize was passed
1002 * The server returns 422 Unprocessable Entity {"error" : "The algorithm does not support the given bit size."}
1003 * Case 6: If the server cant guess the keysize
1004 * The server returns 422 Unprocessable Entity {"error" : "Can not guess key size for algorithm"}
1005 * Case 7: The key-creation failed
997cab68 1006 * The server returns 422 Unprocessable Entity {"error" : "Adding key failed, perhaps DNSSEC not enabled in configuration?"}
60b0a236
BZ
1007 * Case 8: The key in content has the wrong format
1008 * The server returns 422 Unprocessable Entity {"error" : "Key could not be parsed. Make sure your key format is correct."}
1009 * Case 9: The wrong combination of fields is submitted
1010 * The server returns 422 Unprocessable Entity {"error" : "Either you submit just the 'content' field or you leave 'content' empty and submit the other fields."}
1011 * Case 10: No content and everything was fine
1012 * The server returns 201 Created and all public data about the new cryptokey
1013 * Case 11: With specified content
1014 * The server returns 201 Created and all public data about the added cryptokey
997cab68
BZ
1015 */
1016
60b0a236 1017static void apiZoneCryptokeysPOST(DNSName zonename, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
997cab68 1018 auto document = req->json();
5d9c6182
PL
1019 string privatekey_fieldname = "privatekey";
1020 auto privatekey = document["privatekey"];
1021 if (privatekey.is_null()) {
1022 // Fallback to the old "content" behaviour
1023 privatekey = document["content"];
1024 privatekey_fieldname = "content";
1025 }
997cab68 1026 bool active = boolFromJson(document, "active", false);
997cab68 1027 bool keyOrZone;
60b0a236 1028
eefd15b3 1029 if (stringFromJson(document, "keytype") == "ksk" || stringFromJson(document, "keytype") == "csk") {
997cab68
BZ
1030 keyOrZone = true;
1031 } else if (stringFromJson(document, "keytype") == "zsk") {
1032 keyOrZone = false;
1033 } else {
1034 throw ApiException("Invalid keytype " + stringFromJson(document, "keytype"));
1035 }
1036
b727e19b 1037 int64_t insertedId = -1;
997cab68 1038
5d9c6182 1039 if (privatekey.is_null()) {
43215ca6 1040 int bits = keyOrZone ? ::arg().asNum("default-ksk-size") : ::arg().asNum("default-zsk-size");
60b0a236
BZ
1041 auto docbits = document["bits"];
1042 if (!docbits.is_null()) {
1043 if (!docbits.is_number() || (fmod(docbits.number_value(), 1.0) != 0) || docbits.int_value() < 0) {
1044 throw ApiException("'bits' must be a positive integer value");
1045 } else {
1046 bits = docbits.int_value();
1047 }
1048 }
43215ca6 1049 int algorithm = DNSSECKeeper::shorthand2algorithm(keyOrZone ? ::arg()["default-ksk-algorithm"] : ::arg()["default-zsk-algorithm"]);
5d9c6182 1050 auto providedAlgo = document["algorithm"];
997cab68 1051 if (providedAlgo.is_string()) {
60b0a236
BZ
1052 algorithm = DNSSECKeeper::shorthand2algorithm(providedAlgo.string_value());
1053 if (algorithm == -1)
997cab68 1054 throw ApiException("Unknown algorithm: " + providedAlgo.string_value());
997cab68
BZ
1055 } else if (providedAlgo.is_number()) {
1056 algorithm = providedAlgo.int_value();
60b0a236
BZ
1057 } else if (!providedAlgo.is_null()) {
1058 throw ApiException("Unknown algorithm: " + providedAlgo.string_value());
997cab68
BZ
1059 }
1060
60b0a236 1061 try {
b727e19b
RG
1062 if (!dk->addKey(zonename, keyOrZone, algorithm, insertedId, bits, active)) {
1063 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
1064 }
60b0a236 1065 } catch (std::runtime_error& error) {
997cab68
BZ
1066 throw ApiException(error.what());
1067 }
997cab68
BZ
1068 if (insertedId < 0)
1069 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
5d9c6182
PL
1070 } else if (document["bits"].is_null() && document["algorithm"].is_null()) {
1071 auto keyData = stringFromJson(document, privatekey_fieldname);
997cab68
BZ
1072 DNSKEYRecordContent dkrc;
1073 DNSSECPrivateKey dpk;
60b0a236 1074 try {
997cab68
BZ
1075 shared_ptr<DNSCryptoKeyEngine> dke(DNSCryptoKeyEngine::makeFromISCString(dkrc, keyData));
1076 dpk.d_algorithm = dkrc.d_algorithm;
5d9c6182 1077 // TODO remove in 4.2.0
902c4e9c
CH
1078 if(dpk.d_algorithm == DNSSECKeeper::RSASHA1NSEC3SHA1)
1079 dpk.d_algorithm = DNSSECKeeper::RSASHA1;
997cab68
BZ
1080
1081 if (keyOrZone)
1082 dpk.d_flags = 257;
1083 else
1084 dpk.d_flags = 256;
1085
1086 dpk.setKey(dke);
997cab68 1087 }
60b0a236
BZ
1088 catch (std::runtime_error& error) {
1089 throw ApiException("Key could not be parsed. Make sure your key format is correct.");
1090 } try {
b727e19b
RG
1091 if (!dk->addKey(zonename, dpk,insertedId, active)) {
1092 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
1093 }
60b0a236 1094 } catch (std::runtime_error& error) {
997cab68
BZ
1095 throw ApiException(error.what());
1096 }
1097 if (insertedId < 0)
1098 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
60b0a236 1099 } else {
5d9c6182 1100 throw ApiException("Either you submit just the 'privatekey' field or you leave 'privatekey' empty and submit the other fields.");
997cab68 1101 }
60b0a236 1102 apiZoneCryptokeysGET(zonename, insertedId, resp, dk);
997cab68 1103 resp->status = 201;
60b0a236 1104}
997cab68
BZ
1105
1106/*
1107 * This method handles PUT (execute) requests for URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
1108 * It de/activates a key from :zone_name specified by :cryptokey_id.
1109 * Server Answers:
60b0a236 1110 * Case 1: invalid JSON data
997cab68 1111 * The server returns 400 Bad Request
60b0a236
BZ
1112 * Case 2: the backend returns true on de/activation. This means the key is de/active.
1113 * The server returns 204 No Content
955cbfd0 1114 * Case 3: the backend returns false on de/activation. An error occurred.
997cab68
BZ
1115 * The sever returns 422 Unprocessable Entity with message "Could not de/activate Key: :cryptokey_id in Zone: :zone_name"
1116 * */
60b0a236 1117static void apiZoneCryptokeysPUT(DNSName zonename, int inquireKeyId, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
997cab68
BZ
1118 //throws an exception if the Body is empty
1119 auto document = req->json();
1120 //throws an exception if the key does not exist or is not a bool
1121 bool active = boolFromJson(document, "active");
60b0a236
BZ
1122 if (active) {
1123 if (!dk->activateKey(zonename, inquireKeyId)) {
997cab68
BZ
1124 resp->setErrorResult("Could not activate Key: " + req->parameters["key_id"] + " in Zone: " + zonename.toString(), 422);
1125 return;
1126 }
1127 } else {
60b0a236 1128 if (!dk->deactivateKey(zonename, inquireKeyId)) {
997cab68
BZ
1129 resp->setErrorResult("Could not deactivate Key: " + req->parameters["key_id"] + " in Zone: " + zonename.toString(), 422);
1130 return;
1131 }
1132 }
60b0a236
BZ
1133 resp->body = "";
1134 resp->status = 204;
1135 return;
997cab68
BZ
1136}
1137
1138/*
1139 * This method chooses the right functionality for the request. It also checks for a cryptokey_id which has to be passed
1140 * by URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
1141 * If the the HTTP-request-method isn't supported, the function returns a response with the 405 code (method not allowed).
1142 * */
1143static void apiZoneCryptokeys(HttpRequest *req, HttpResponse *resp) {
1144 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
1145
60b0a236
BZ
1146 UeberBackend B;
1147 DNSSECKeeper dk(&B);
1148 DomainInfo di;
77bfe8de
PL
1149 if (!B.getDomainInfo(zonename, di)) {
1150 throw HttpNotFoundException();
1151 }
60b0a236 1152
997cab68
BZ
1153 int inquireKeyId = -1;
1154 if (req->parameters.count("key_id")) {
1155 inquireKeyId = std::stoi(req->parameters["key_id"]);
1156 }
1157
1158 if (req->method == "GET") {
60b0a236 1159 apiZoneCryptokeysGET(zonename, inquireKeyId, resp, &dk);
1abc1df5 1160 } else if (req->method == "DELETE" && !::arg().mustDo("api-readonly")) {
60b0a236
BZ
1161 if (inquireKeyId == -1)
1162 throw HttpBadRequestException();
1163 apiZoneCryptokeysDELETE(zonename, inquireKeyId, req, resp, &dk);
1abc1df5 1164 } else if (req->method == "POST" && !::arg().mustDo("api-readonly")) {
60b0a236 1165 apiZoneCryptokeysPOST(zonename, req, resp, &dk);
1abc1df5 1166 } else if (req->method == "PUT" && !::arg().mustDo("api-readonly")) {
60b0a236
BZ
1167 if (inquireKeyId == -1)
1168 throw HttpBadRequestException();
1169 apiZoneCryptokeysPUT(zonename, inquireKeyId, req, resp, &dk);
997cab68
BZ
1170 } else {
1171 throw HttpMethodNotAllowedException(); //Returns method not allowed
1172 }
4b7f120a
MS
1173}
1174
1f68b185 1175static void gatherRecordsFromZone(const std::string& zonestring, vector<DNSResourceRecord>& new_records, DNSName zonename) {
0f0e73fe
MS
1176 DNSResourceRecord rr;
1177 vector<string> zonedata;
1f68b185 1178 stringtok(zonedata, zonestring, "\r\n");
0f0e73fe
MS
1179
1180 ZoneParserTNG zpt(zonedata, zonename);
1181
1182 bool seenSOA=false;
1183
1184 string comment = "Imported via the API";
1185
1186 try {
1187 while(zpt.get(rr, &comment)) {
1188 if(seenSOA && rr.qtype.getCode() == QType::SOA)
1189 continue;
1190 if(rr.qtype.getCode() == QType::SOA)
1191 seenSOA=true;
24ded6cc 1192 validateGatheredRRType(rr);
0f0e73fe 1193
0f0e73fe
MS
1194 new_records.push_back(rr);
1195 }
1196 }
1197 catch(std::exception& ae) {
1af62161 1198 throw ApiException("An error occurred while parsing the zonedata: "+string(ae.what()));
0f0e73fe
MS
1199 }
1200}
1201
e3675a8a
CH
1202/** Throws ApiException if records with duplicate name/type/content are present.
1203 * NOTE: sorts records in-place.
1204 */
1205static void checkDuplicateRecords(vector<DNSResourceRecord>& records) {
1206 sort(records.begin(), records.end(),
1207 [](const DNSResourceRecord& rec_a, const DNSResourceRecord& rec_b) -> bool {
1208 return rec_a.qname.toString() > rec_b.qname.toString() || \
1209 rec_a.qtype.getCode() > rec_b.qtype.getCode() || \
1210 rec_a.content < rec_b.content;
1211 }
1212 );
1213 DNSResourceRecord previous;
1214 for(const auto& rec : records) {
1215 if (previous.qtype == rec.qtype && previous.qname == rec.qname && previous.content == rec.content) {
1216 throw ApiException("Duplicate record in RRset " + rec.qname.toString() + " IN " + rec.qtype.getName() + " with content \"" + rec.content + "\"");
1217 }
1218 previous = rec;
1219 }
1220}
1221
80d59cd1 1222static void apiServerZones(HttpRequest* req, HttpResponse* resp) {
e2dba705 1223 UeberBackend B;
53942520 1224 DNSSECKeeper dk(&B);
d07bf7ff 1225 if (req->method == "POST" && !::arg().mustDo("api-readonly")) {
e2dba705 1226 DomainInfo di;
1f68b185 1227 auto document = req->json();
c576d0c5 1228 DNSName zonename = apiNameToDNSName(stringFromJson(document, "name"));
1d6b70f9 1229 apiCheckNameAllowedCharacters(zonename.toString());
e3675a8a 1230 zonename.makeUsLowerCase();
4ebf78b1 1231
1d6b70f9 1232 bool exists = B.getDomainInfo(zonename, di);
e2dba705 1233 if(exists)
331d3062 1234 throw HttpConflictException();
e2dba705 1235
bb9fd223 1236 // validate 'kind' is set
4bdff352 1237 DomainInfo::DomainKind zonekind = DomainInfo::stringToKind(stringFromJson(document, "kind"));
bb9fd223 1238
6754ef71
CH
1239 string zonestring = document["zone"].string_value();
1240 auto rrsets = document["rrsets"];
1241 if (rrsets.is_array() && zonestring != "")
1242 throw ApiException("You cannot give rrsets AND zone data as text");
0f0e73fe 1243
1f68b185
CH
1244 auto nameservers = document["nameservers"];
1245 if (!nameservers.is_array() && zonekind != DomainInfo::Slave)
f63168e6 1246 throw ApiException("Nameservers list must be given (but can be empty if NS records are supplied)");
e2dba705 1247
f63168e6 1248 string soa_edit_api_kind;
1f68b185
CH
1249 if (document["soa_edit_api"].is_string()) {
1250 soa_edit_api_kind = document["soa_edit_api"].string_value();
a6448d95
CH
1251 }
1252 else {
1253 soa_edit_api_kind = "DEFAULT";
1254 }
1f68b185 1255 string soa_edit_kind = document["soa_edit"].string_value();
e90b4e38 1256
f63168e6
CH
1257 // if records/comments are given, load and check them
1258 bool have_soa = false;
33e6c3e9 1259 bool have_zone_ns = false;
f63168e6
CH
1260 vector<DNSResourceRecord> new_records;
1261 vector<Comment> new_comments;
1262 vector<DNSResourceRecord> new_ptrs;
0f0e73fe 1263
6754ef71
CH
1264 if (rrsets.is_array()) {
1265 for (const auto& rrset : rrsets.array_items()) {
1266 DNSName qname = apiNameToDNSName(stringFromJson(rrset, "name"));
1267 apiCheckQNameAllowedCharacters(qname.toString());
1268 QType qtype;
1269 qtype = stringFromJson(rrset, "type");
1270 if (qtype.getCode() == 0) {
1271 throw ApiException("RRset "+qname.toString()+" IN "+stringFromJson(rrset, "type")+": unknown type given");
1272 }
1273 if (rrset["records"].is_array()) {
1274 int ttl = intFromJson(rrset, "ttl");
1275 gatherRecords(rrset, qname, qtype, ttl, new_records, new_ptrs);
1276 }
1277 if (rrset["comments"].is_array()) {
1278 gatherComments(rrset, qname, qtype, new_comments);
1279 }
1280 }
0f0e73fe 1281 } else if (zonestring != "") {
1f68b185 1282 gatherRecordsFromZone(zonestring, new_records, zonename);
0f0e73fe
MS
1283 }
1284
1f68b185 1285 for(auto& rr : new_records) {
e3675a8a 1286 rr.qname.makeUsLowerCase();
1d6b70f9 1287 if (!rr.qname.isPartOf(zonename) && rr.qname != zonename)
561434a6 1288 throw ApiException("RRset "+rr.qname.toString()+" IN "+rr.qtype.getName()+": Name is out of zone");
cb9b5901 1289 apiCheckQNameAllowedCharacters(rr.qname.toString());
f63168e6 1290
1d6b70f9 1291 if (rr.qtype.getCode() == QType::SOA && rr.qname==zonename) {
f63168e6 1292 have_soa = true;
a6448d95 1293 increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind);
f63168e6 1294 }
33e6c3e9
CH
1295 if (rr.qtype.getCode() == QType::NS && rr.qname==zonename) {
1296 have_zone_ns = true;
1297 }
f63168e6 1298 }
f7bfeb30
CH
1299
1300 // synthesize RRs as needed
1301 DNSResourceRecord autorr;
1d6b70f9 1302 autorr.qname = zonename;
f7bfeb30
CH
1303 autorr.auth = 1;
1304 autorr.ttl = ::arg().asNum("default-ttl");
e2dba705 1305
4de11a54 1306 if (!have_soa && zonekind != DomainInfo::Slave) {
f63168e6 1307 // synthesize a SOA record so the zone "really" exists
13f9e280 1308 string soa = (boost::format("%s %s %ul")
1d6b70f9
CH
1309 % ::arg()["default-soa-name"]
1310 % (::arg().isEmpty("default-soa-mail") ? (DNSName("hostmaster.") + zonename).toString() : ::arg()["default-soa-mail"])
1f68b185 1311 % document["serial"].int_value()
1d6b70f9 1312 ).str();
f63168e6 1313 SOAData sd;
1d6b70f9 1314 fillSOAData(soa, sd); // fills out default values for us
13f9e280
CH
1315 autorr.qtype = QType::SOA;
1316 autorr.content = makeSOAContent(sd)->getZoneRepresentation(true);
f7bfeb30
CH
1317 increaseSOARecord(autorr, soa_edit_api_kind, soa_edit_kind);
1318 new_records.push_back(autorr);
f63168e6
CH
1319 }
1320
1321 // create NS records if nameservers are given
1f68b185
CH
1322 for (auto value : nameservers.array_items()) {
1323 string nameserver = value.string_value();
1324 if (nameserver.empty())
1325 throw ApiException("Nameservers must be non-empty strings");
1326 if (!isCanonical(nameserver))
1327 throw ApiException("Nameserver is not canonical: '" + nameserver + "'");
1328 try {
1329 // ensure the name parses
8f955653 1330 autorr.content = DNSName(nameserver).toStringRootDot();
1f68b185
CH
1331 } catch (...) {
1332 throw ApiException("Unable to parse DNS Name for NS '" + nameserver + "'");
4bdff352 1333 }
13f9e280 1334 autorr.qtype = QType::NS;
1f68b185 1335 new_records.push_back(autorr);
33e6c3e9
CH
1336 if (have_zone_ns) {
1337 throw ApiException("Nameservers list MUST NOT be mixed with zone-level NS in rrsets");
1338 }
e2dba705
CH
1339 }
1340
e3675a8a
CH
1341 checkDuplicateRecords(new_records);
1342
986e4858
PL
1343 if (boolFromJson(document, "dnssec", false)) {
1344 checkDefaultDNSSECAlgos();
1345
1346 if(document["nsec3param"].string_value().length() > 0) {
1347 NSEC3PARAMRecordContent ns3pr(document["nsec3param"].string_value());
1348 string error_msg = "";
1349 if (!dk.checkNSEC3PARAM(ns3pr, error_msg)) {
1350 throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"' are invalid. " + error_msg);
1351 }
1352 }
1353 }
1354
f63168e6 1355 // no going back after this
1d6b70f9
CH
1356 if(!B.createDomain(zonename))
1357 throw ApiException("Creating domain '"+zonename.toString()+"' failed");
f63168e6 1358
1d6b70f9
CH
1359 if(!B.getDomainInfo(zonename, di))
1360 throw ApiException("Creating domain '"+zonename.toString()+"' failed: lookup of domain ID failed");
f63168e6 1361
9440a9f0
CH
1362 // updateDomainSettingsFromDocument does NOT fill out the default we've established above.
1363 if (!soa_edit_api_kind.empty()) {
1364 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind);
1365 }
1366
1d6b70f9 1367 di.backend->startTransaction(zonename, di.id);
f63168e6 1368
abb873ee 1369 for(auto rr : new_records) {
f63168e6 1370 rr.domain_id = di.id;
c9b43446 1371 di.backend->feedRecord(rr, DNSName());
e2dba705 1372 }
1d6b70f9 1373 for(Comment& c : new_comments) {
f63168e6
CH
1374 c.domain_id = di.id;
1375 di.backend->feedComment(c);
1376 }
e2dba705 1377
986e4858 1378 updateDomainSettingsFromDocument(B, di, zonename, document);
e2dba705 1379
f63168e6
CH
1380 di.backend->commitTransaction();
1381
3fe7c7d6
CH
1382 storeChangedPTRs(B, new_ptrs);
1383
986e4858 1384 fillZone(zonename, resp, shouldDoRRSets(req));
64a36f0d 1385 resp->status = 201;
e2dba705
CH
1386 return;
1387 }
1388
c67bf8c5
CH
1389 if(req->method != "GET")
1390 throw HttpMethodNotAllowedException();
1391
c67bf8c5 1392 vector<DomainInfo> domains;
cea26350 1393 B.getAllDomains(&domains, true); // incl. disabled
c67bf8c5 1394
62a9a74c
CH
1395 Json::array doc;
1396 for(const DomainInfo& di : domains) {
ce846be6 1397 doc.push_back(getZoneInfo(di, &dk));
c67bf8c5 1398 }
669822d0 1399 resp->setBody(doc);
c67bf8c5
CH
1400}
1401
05776d2f 1402static void apiServerZoneDetail(HttpRequest* req, HttpResponse* resp) {
290a083d 1403 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
05776d2f 1404
77bfe8de
PL
1405 UeberBackend B;
1406 DomainInfo di;
1407 if (!B.getDomainInfo(zonename, di)) {
1408 throw HttpNotFoundException();
1409 }
1410
d07bf7ff 1411 if(req->method == "PUT" && !::arg().mustDo("api-readonly")) {
7c0ba3d2 1412 // update domain settings
7c0ba3d2 1413
986e4858 1414 updateDomainSettingsFromDocument(B, di, zonename, req->json());
7c0ba3d2 1415
f0e76cee
CH
1416 resp->body = "";
1417 resp->status = 204; // No Content, but indicate success
7c0ba3d2
CH
1418 return;
1419 }
d07bf7ff 1420 else if(req->method == "DELETE" && !::arg().mustDo("api-readonly")) {
a462a01d 1421 // delete domain
a462a01d 1422 if(!di.backend->deleteDomain(zonename))
290a083d 1423 throw ApiException("Deleting domain '"+zonename.toString()+"' failed: backend delete failed/unsupported");
a462a01d
CH
1424
1425 // empty body on success
1426 resp->body = "";
37663c3b 1427 resp->status = 204; // No Content: declare that the zone is gone now
a462a01d 1428 return;
d07bf7ff 1429 } else if (req->method == "PATCH" && !::arg().mustDo("api-readonly")) {
d708640f 1430 patchZone(req, resp);
6cc98ddf
CH
1431 return;
1432 } else if (req->method == "GET") {
986e4858 1433 fillZone(zonename, resp, shouldDoRRSets(req));
6cc98ddf 1434 return;
a462a01d 1435 }
6cc98ddf 1436 throw HttpMethodNotAllowedException();
05776d2f
CH
1437}
1438
a83004d3 1439static void apiServerZoneExport(HttpRequest* req, HttpResponse* resp) {
290a083d 1440 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a83004d3
CH
1441
1442 if(req->method != "GET")
1443 throw HttpMethodNotAllowedException();
1444
1445 ostringstream ss;
1446
1447 UeberBackend B;
1448 DomainInfo di;
77bfe8de
PL
1449 if (!B.getDomainInfo(zonename, di)) {
1450 throw HttpNotFoundException();
1451 }
a83004d3
CH
1452
1453 DNSResourceRecord rr;
1454 SOAData sd;
1455 di.backend->list(zonename, di.id);
1456 while(di.backend->get(rr)) {
1457 if (!rr.qtype.getCode())
1458 continue; // skip empty non-terminals
1459
a83004d3 1460 ss <<
675fa24c 1461 rr.qname.toString() << "\t" <<
a83004d3
CH
1462 rr.ttl << "\t" <<
1463 rr.qtype.getName() << "\t" <<
1d6b70f9 1464 makeApiRecordContent(rr.qtype, rr.content) <<
a83004d3
CH
1465 endl;
1466 }
1467
1468 if (req->accept_json) {
41873e7c 1469 resp->setBody(Json::object { { "zone", ss.str() } });
a83004d3
CH
1470 } else {
1471 resp->headers["Content-Type"] = "text/plain; charset=us-ascii";
1472 resp->body = ss.str();
1473 }
1474}
1475
a426cb89 1476static void apiServerZoneAxfrRetrieve(HttpRequest* req, HttpResponse* resp) {
290a083d 1477 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a426cb89 1478
136965be 1479 if(req->method != "PUT" || ::arg().mustDo("api-readonly"))
a426cb89
CH
1480 throw HttpMethodNotAllowedException();
1481
1482 UeberBackend B;
1483 DomainInfo di;
77bfe8de
PL
1484 if (!B.getDomainInfo(zonename, di)) {
1485 throw HttpNotFoundException();
1486 }
a426cb89
CH
1487
1488 if(di.masters.empty())
290a083d 1489 throw ApiException("Domain '"+zonename.toString()+"' is not a slave domain (or has no master defined)");
a426cb89
CH
1490
1491 random_shuffle(di.masters.begin(), di.masters.end());
1492 Communicator.addSuckRequest(zonename, di.masters.front());
9b0f144f 1493 resp->setSuccessResult("Added retrieval request for '"+zonename.toString()+"' from master "+di.masters.front().toLogString());
a426cb89
CH
1494}
1495
1496static void apiServerZoneNotify(HttpRequest* req, HttpResponse* resp) {
290a083d 1497 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a426cb89 1498
136965be 1499 if(req->method != "PUT" || ::arg().mustDo("api-readonly"))
a426cb89
CH
1500 throw HttpMethodNotAllowedException();
1501
1502 UeberBackend B;
1503 DomainInfo di;
77bfe8de
PL
1504 if (!B.getDomainInfo(zonename, di)) {
1505 throw HttpNotFoundException();
1506 }
a426cb89
CH
1507
1508 if(!Communicator.notifyDomain(zonename))
1509 throw ApiException("Failed to add to the queue - see server log");
1510
692829aa 1511 resp->setSuccessResult("Notification queued");
a426cb89
CH
1512}
1513
4bc8379e
PL
1514static void apiServerZoneRectify(HttpRequest* req, HttpResponse* resp) {
1515 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
1516
1517 if(req->method != "PUT")
1518 throw HttpMethodNotAllowedException();
1519
1520 UeberBackend B;
1521 DomainInfo di;
77bfe8de
PL
1522 if (!B.getDomainInfo(zonename, di)) {
1523 throw HttpNotFoundException();
1524 }
4bc8379e
PL
1525
1526 DNSSECKeeper dk(&B);
1527
1528 if (!dk.isSecuredZone(zonename))
1529 throw ApiException("Zone '" + zonename.toString() + "' is not DNSSEC signed, not rectifying.");
1530
1531 if (di.kind == DomainInfo::Slave)
1532 throw ApiException("Zone '" + zonename.toString() + "' is a slave zone, not rectifying.");
1533
1534 string error_msg = "";
59102608
RG
1535 string info;
1536 if (!dk.rectifyZone(zonename, error_msg, info, true))
4bc8379e
PL
1537 throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg);
1538
1539 resp->setSuccessResult("Rectified");
1540}
1541
d1587ceb
CH
1542static void makePtr(const DNSResourceRecord& rr, DNSResourceRecord* ptr) {
1543 if (rr.qtype.getCode() == QType::A) {
1544 uint32_t ip;
1545 if (!IpToU32(rr.content, &ip)) {
1546 throw ApiException("PTR: Invalid IP address given");
1547 }
1d6b70f9 1548 ptr->qname = DNSName((boost::format("%u.%u.%u.%u.in-addr.arpa.")
d1587ceb
CH
1549 % ((ip >> 24) & 0xff)
1550 % ((ip >> 16) & 0xff)
1551 % ((ip >> 8) & 0xff)
1552 % ((ip ) & 0xff)
1d6b70f9 1553 ).str());
d1587ceb
CH
1554 } else if (rr.qtype.getCode() == QType::AAAA) {
1555 ComboAddress ca(rr.content);
5fb3aa58 1556 char buf[3];
d1587ceb 1557 ostringstream ss;
5fb3aa58
CH
1558 for (int octet = 0; octet < 16; ++octet) {
1559 if (snprintf(buf, sizeof(buf), "%02x", ca.sin6.sin6_addr.s6_addr[octet]) != (sizeof(buf)-1)) {
1560 // this should be impossible: no byte should give more than two digits in hex format
1561 throw PDNSException("Formatting IPv6 address failed");
1562 }
1563 ss << buf[0] << '.' << buf[1] << '.';
d1587ceb 1564 }
5fb3aa58
CH
1565 string tmp = ss.str();
1566 tmp.resize(tmp.size()-1); // remove last dot
1567 // reverse and append arpa domain
1d6b70f9 1568 ptr->qname = DNSName(string(tmp.rbegin(), tmp.rend())) + DNSName("ip6.arpa.");
d1587ceb 1569 } else {
675fa24c 1570 throw ApiException("Unsupported PTR source '" + rr.qname.toString() + "' type '" + rr.qtype.getName() + "'");
d1587ceb
CH
1571 }
1572
1573 ptr->qtype = "PTR";
1574 ptr->ttl = rr.ttl;
1575 ptr->disabled = rr.disabled;
8f955653 1576 ptr->content = rr.qname.toStringRootDot();
d1587ceb
CH
1577}
1578
995473c8
CH
1579static void storeChangedPTRs(UeberBackend& B, vector<DNSResourceRecord>& new_ptrs) {
1580 for(const DNSResourceRecord& rr : new_ptrs) {
995473c8 1581 SOAData sd;
cec52de6 1582 if (!B.getAuth(rr.qname, QType(QType::PTR), &sd, false))
995473c8
CH
1583 throw ApiException("Could not find domain for PTR '"+rr.qname.toString()+"' requested for '"+rr.content+"' (while saving)");
1584
1585 string soa_edit_api_kind;
1586 string soa_edit_kind;
1587 bool soa_changed = false;
1588 DNSResourceRecord soarr;
1589 sd.db->getDomainMetadataOne(sd.qname, "SOA-EDIT-API", soa_edit_api_kind);
1590 sd.db->getDomainMetadataOne(sd.qname, "SOA-EDIT", soa_edit_kind);
1591 if (!soa_edit_api_kind.empty()) {
13f9e280 1592 soa_changed = makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, soarr);
995473c8
CH
1593 }
1594
1595 sd.db->startTransaction(sd.qname);
1596 if (!sd.db->replaceRRSet(sd.domain_id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
1597 sd.db->abortTransaction();
1598 throw ApiException("PTR-Hosting backend for "+rr.qname.toString()+"/"+rr.qtype.getName()+" does not support editing records.");
1599 }
1600
1601 if (soa_changed) {
1602 sd.db->replaceRRSet(sd.domain_id, soarr.qname, soarr.qtype, vector<DNSResourceRecord>(1, soarr));
1603 }
1604
1605 sd.db->commitTransaction();
bf269e28 1606 purgeAuthCachesExact(rr.qname);
995473c8
CH
1607 }
1608}
1609
d708640f 1610static void patchZone(HttpRequest* req, HttpResponse* resp) {
b3905a3d
CH
1611 UeberBackend B;
1612 DomainInfo di;
290a083d 1613 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
77bfe8de
PL
1614 if (!B.getDomainInfo(zonename, di)) {
1615 throw HttpNotFoundException();
1616 }
b3905a3d 1617
f63168e6
CH
1618 vector<DNSResourceRecord> new_records;
1619 vector<Comment> new_comments;
d708640f
CH
1620 vector<DNSResourceRecord> new_ptrs;
1621
1f68b185 1622 Json document = req->json();
b3905a3d 1623
1f68b185
CH
1624 auto rrsets = document["rrsets"];
1625 if (!rrsets.is_array())
d708640f 1626 throw ApiException("No rrsets given in update request");
b3905a3d 1627
d708640f 1628 di.backend->startTransaction(zonename);
6cc98ddf 1629
d708640f 1630 try {
d29d5db7 1631 string soa_edit_api_kind;
a6448d95 1632 string soa_edit_kind;
d29d5db7 1633 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind);
a6448d95 1634 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit_kind);
d29d5db7
CH
1635 bool soa_edit_done = false;
1636
6754ef71
CH
1637 for (const auto& rrset : rrsets.array_items()) {
1638 string changetype = toUpper(stringFromJson(rrset, "changetype"));
c576d0c5 1639 DNSName qname = apiNameToDNSName(stringFromJson(rrset, "name"));
cb9b5901 1640 apiCheckQNameAllowedCharacters(qname.toString());
6754ef71 1641 QType qtype;
d708640f 1642 qtype = stringFromJson(rrset, "type");
6754ef71
CH
1643 if (qtype.getCode() == 0) {
1644 throw ApiException("RRset "+qname.toString()+" IN "+stringFromJson(rrset, "type")+": unknown type given");
1645 }
d708640f 1646
d708640f 1647 if (changetype == "DELETE") {
b7f21ab1 1648 // delete all matching qname/qtype RRs (and, implicitly comments).
d708640f
CH
1649 if (!di.backend->replaceRRSet(di.id, qname, qtype, vector<DNSResourceRecord>())) {
1650 throw ApiException("Hosting backend does not support editing records.");
6cc98ddf 1651 }
d708640f
CH
1652 }
1653 else if (changetype == "REPLACE") {
1d6b70f9 1654 // we only validate for REPLACE, as DELETE can be used to "fix" out of zone records.
e325f20c 1655 if (!qname.isPartOf(zonename) && qname != zonename)
edda67a2 1656 throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Name is out of zone");
34df6ecc 1657
6754ef71
CH
1658 bool replace_records = rrset["records"].is_array();
1659 bool replace_comments = rrset["comments"].is_array();
f63168e6 1660
6754ef71
CH
1661 if (!replace_records && !replace_comments) {
1662 throw ApiException("No change for RRset " + qname.toString() + " IN " + qtype.getName());
1663 }
f63168e6 1664
6754ef71
CH
1665 new_records.clear();
1666 new_comments.clear();
f63168e6 1667
6754ef71
CH
1668 if (replace_records) {
1669 // ttl shouldn't be part of DELETE, and it shouldn't be required if we don't get new records.
1670 int ttl = intFromJson(rrset, "ttl");
1671 // new_ptrs is merged.
1672 gatherRecords(rrset, qname, qtype, ttl, new_records, new_ptrs);
1673
1674 for(DNSResourceRecord& rr : new_records) {
1675 rr.domain_id = di.id;
1676 if (rr.qtype.getCode() == QType::SOA && rr.qname==zonename) {
1677 soa_edit_done = increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind);
6754ef71 1678 }
d708640f 1679 }
e3675a8a 1680 checkDuplicateRecords(new_records);
6cc98ddf
CH
1681 }
1682
6754ef71
CH
1683 if (replace_comments) {
1684 gatherComments(rrset, qname, qtype, new_comments);
f63168e6 1685
6754ef71
CH
1686 for(Comment& c : new_comments) {
1687 c.domain_id = di.id;
1688 }
d708640f 1689 }
b3905a3d 1690
d708640f 1691 if (replace_records) {
8560f36a
CH
1692 di.backend->lookup(QType(QType::ANY), qname);
1693 DNSResourceRecord rr;
1694 while (di.backend->get(rr)) {
1695 if (qtype.getCode() == QType::CNAME && rr.qtype.getCode() != QType::CNAME) {
1696 throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Conflicts with pre-existing non-CNAME RRset");
1697 } else if (qtype.getCode() != QType::CNAME && rr.qtype.getCode() == QType::CNAME) {
1698 throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Conflicts with pre-existing CNAME RRset");
1699 }
1700 }
1701
d708640f
CH
1702 if (!di.backend->replaceRRSet(di.id, qname, qtype, new_records)) {
1703 throw ApiException("Hosting backend does not support editing records.");
1704 }
1705 }
1706 if (replace_comments) {
1707 if (!di.backend->replaceComments(di.id, qname, qtype, new_comments)) {
1708 throw ApiException("Hosting backend does not support editing comments.");
1709 }
1710 }
6cc98ddf 1711 }
d708640f
CH
1712 else
1713 throw ApiException("Changetype not understood");
6cc98ddf 1714 }
d29d5db7
CH
1715
1716 // edit SOA (if needed)
1717 if (!soa_edit_api_kind.empty() && !soa_edit_done) {
1718 SOAData sd;
13f9e280 1719 if (!B.getSOAUncached(zonename, sd, true))
290a083d 1720 throw ApiException("No SOA found for domain '"+zonename.toString()+"'");
d29d5db7
CH
1721
1722 DNSResourceRecord rr;
13f9e280
CH
1723 if (makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, rr)) {
1724 if (!di.backend->replaceRRSet(di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
1725 throw ApiException("Hosting backend does not support editing records.");
1726 }
d29d5db7 1727 }
3ae63ca8 1728
478de03b
KW
1729 // return old and new serials in headers
1730 resp->headers["X-PDNS-Old-Serial"] = std::to_string(sd.serial);
3ae63ca8 1731 fillSOAData(rr.content, sd);
478de03b 1732 resp->headers["X-PDNS-New-Serial"] = std::to_string(sd.serial);
d29d5db7
CH
1733 }
1734
d708640f
CH
1735 } catch(...) {
1736 di.backend->abortTransaction();
1737 throw;
1738 }
986e4858 1739
b0486ea5 1740 DNSSECKeeper dk(&B);
986e4858
PL
1741 string api_rectify;
1742 di.backend->getDomainMetadataOne(zonename, "API-RECTIFY", api_rectify);
1743 if (dk.isSecuredZone(zonename) && !dk.isPresigned(zonename) && api_rectify == "1") {
1744 string error_msg = "";
59102608
RG
1745 string info;
1746 if (!dk.rectifyZone(zonename, error_msg, info, false))
986e4858
PL
1747 throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg);
1748 }
1749
d708640f 1750 di.backend->commitTransaction();
b3905a3d 1751
bf269e28 1752 purgeAuthCachesExact(zonename);
d1587ceb 1753
d708640f 1754 // now the PTRs
995473c8 1755 storeChangedPTRs(B, new_ptrs);
b3905a3d 1756
f0e76cee
CH
1757 resp->body = "";
1758 resp->status = 204; // No Content, but indicate success
1759 return;
b3905a3d
CH
1760}
1761
b1902fab
CH
1762static void apiServerSearchData(HttpRequest* req, HttpResponse* resp) {
1763 if(req->method != "GET")
1764 throw HttpMethodNotAllowedException();
1765
583ea80d 1766 string q = req->getvars["q"];
720ed2bd
AT
1767 string sMax = req->getvars["max"];
1768 int maxEnts = 100;
1769 int ents = 0;
1770
b1902fab
CH
1771 if (q.empty())
1772 throw ApiException("Query q can't be blank");
606c8752 1773 if (!sMax.empty())
335da0ba 1774 maxEnts = std::stoi(sMax);
720ed2bd
AT
1775 if (maxEnts < 1)
1776 throw ApiException("Maximum entries must be larger than 0");
b1902fab 1777
720ed2bd 1778 SimpleMatch sm(q,true);
b1902fab 1779 UeberBackend B;
b1902fab 1780 vector<DomainInfo> domains;
720ed2bd
AT
1781 vector<DNSResourceRecord> result_rr;
1782 vector<Comment> result_c;
1d6b70f9
CH
1783 map<int,DomainInfo> zoneIdZone;
1784 map<int,DomainInfo>::iterator val;
00963dea 1785 Json::array doc;
b1902fab 1786
720ed2bd 1787 B.getAllDomains(&domains, true);
d2d194a9 1788
720ed2bd 1789 for(const DomainInfo di: domains)
1d6b70f9 1790 {
720ed2bd 1791 if (ents < maxEnts && sm.match(di.zone)) {
00963dea
CH
1792 doc.push_back(Json::object {
1793 { "object_type", "zone" },
1794 { "zone_id", apiZoneNameToId(di.zone) },
1795 { "name", di.zone.toString() }
1796 });
720ed2bd 1797 ents++;
b1902fab 1798 }
1d6b70f9 1799 zoneIdZone[di.id] = di; // populate cache
720ed2bd 1800 }
b1902fab 1801
720ed2bd
AT
1802 if (B.searchRecords(q, maxEnts, result_rr))
1803 {
1804 for(const DNSResourceRecord& rr: result_rr)
1805 {
7cbc5255
CH
1806 if (!rr.qtype.getCode())
1807 continue; // skip empty non-terminals
1808
00963dea
CH
1809 auto object = Json::object {
1810 { "object_type", "record" },
1811 { "name", rr.qname.toString() },
1812 { "type", rr.qtype.getName() },
1813 { "ttl", (double)rr.ttl },
1814 { "disabled", rr.disabled },
1815 { "content", makeApiRecordContent(rr.qtype, rr.content) }
1816 };
720ed2bd 1817 if ((val = zoneIdZone.find(rr.domain_id)) != zoneIdZone.end()) {
00963dea
CH
1818 object["zone_id"] = apiZoneNameToId(val->second.zone);
1819 object["zone"] = val->second.zone.toString();
720ed2bd 1820 }
00963dea 1821 doc.push_back(object);
b1902fab 1822 }
720ed2bd 1823 }
b1902fab 1824
720ed2bd
AT
1825 if (B.searchComments(q, maxEnts, result_c))
1826 {
1827 for(const Comment &c: result_c)
1828 {
00963dea
CH
1829 auto object = Json::object {
1830 { "object_type", "comment" },
25dcc05f 1831 { "name", c.qname.toString() },
00963dea
CH
1832 { "content", c.content }
1833 };
720ed2bd 1834 if ((val = zoneIdZone.find(c.domain_id)) != zoneIdZone.end()) {
00963dea
CH
1835 object["zone_id"] = apiZoneNameToId(val->second.zone);
1836 object["zone"] = val->second.zone.toString();
720ed2bd 1837 }
00963dea 1838 doc.push_back(object);
b1902fab
CH
1839 }
1840 }
4bd3d119 1841
b1902fab
CH
1842 resp->setBody(doc);
1843}
1844
c0f6a1da 1845void apiServerCacheFlush(HttpRequest* req, HttpResponse* resp) {
136965be 1846 if(req->method != "PUT" || ::arg().mustDo("api-readonly"))
a426cb89 1847 throw HttpMethodNotAllowedException();
80d59cd1 1848
c0f6a1da
CH
1849 DNSName canon = apiNameToDNSName(req->getvars["domain"]);
1850
bf269e28 1851 uint64_t count = purgeAuthCachesExact(canon);
f682752a 1852 resp->setBody(Json::object {
bf269e28
RG
1853 { "count", (int) count },
1854 { "result", "Flushed cache." }
f682752a 1855 });
ddc84d12
CH
1856}
1857
dea47634 1858void AuthWebServer::cssfunction(HttpRequest* req, HttpResponse* resp)
c67bf8c5 1859{
80d59cd1
CH
1860 resp->headers["Cache-Control"] = "max-age=86400";
1861 resp->headers["Content-Type"] = "text/css";
c67bf8c5 1862
1071abdd 1863 ostringstream ret;
1071abdd
CH
1864 ret<<"* { box-sizing: border-box; margin: 0; padding: 0; }"<<endl;
1865 ret<<"body { color: black; background: white; margin-top: 1em; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 10pt; position: relative; }"<<endl;
1866 ret<<"a { color: #0959c2; }"<<endl;
1867 ret<<"a:hover { color: #3B8EC8; }"<<endl;
1868 ret<<".row { width: 940px; max-width: 100%; min-width: 768px; margin: 0 auto; }"<<endl;
1869 ret<<".row:before, .row:after { display: table; content:\" \"; }"<<endl;
1870 ret<<".row:after { clear: both; }"<<endl;
1871 ret<<".columns { position: relative; min-height: 1px; float: left; }"<<endl;
1872 ret<<".all { width: 100%; }"<<endl;
1873 ret<<".headl { width: 60%; }"<<endl;
1874 ret<<".headr { width: 39.5%; float: right; background-repeat: no-repeat; margin-top: 7px; ";
1875 ret<<"background-image: url(data:image/png;base64,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);";
1876 ret<<" width: 154px; height: 20px; }"<<endl;
1877 ret<<"a#appname { margin: 0; font-size: 27px; color: #666; text-decoration: none; font-weight: bold; display: block; }"<<endl;
1878 ret<<"footer { border-top: 1px solid #ddd; padding-top: 4px; font-size: 12px; }"<<endl;
1879 ret<<"footer.row { margin-top: 1em; margin-bottom: 1em; }"<<endl;
1880 ret<<".panel { background: #f2f2f2; border: 1px solid #e6e6e6; margin: 0 0 22px 0; padding: 20px; }"<<endl;
1881 ret<<"table.data { width: 100%; border-spacing: 0; border-top: 1px solid #333; }"<<endl;
1882 ret<<"table.data td { border-bottom: 1px solid #333; padding: 2px; }"<<endl;
1883 ret<<"table.data tr:nth-child(2n) { background: #e2e2e2; }"<<endl;
1884 ret<<"table.data tr:hover { background: white; }"<<endl;
1885 ret<<".ringmeta { margin-bottom: 5px; }"<<endl;
1886 ret<<".resetring {float: right; }"<<endl;
1887 ret<<".resetring i { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAA/klEQVQY01XPP04UUBgE8N/33vd2XZUWEuzYuMZEG4KFCQn2NhA4AIewAOMBPIG2xhNYeAcKGqkNCdmYlVBZGBIT4FHsbuE0U8xk/kAbqm9TOfI/nicfhmwgDNhvylUT58kxCp4l31L8SfH9IetJ2ev6PwyIwyZWsdb11/gbTK55Co+r8rmJaRPTFJcpZil+pTit7C5awMpA+Zpi1sRFE9MqflYOloYCjY2uP8EdYiGU4CVGUBubxKfOOLjrtOBmzvEilbVb/aQWvhRl0unBZVXe4XdnK+bprwqnhoyTsyZ+JG8Wk0apfExxlcp7PFruXH8gdxamWB4cyW2sIO4BG3czIp78jUIAAAAASUVORK5CYII=); width: 10px; height: 10px; margin-right: 2px; display: inline-block; background-repeat: no-repeat; }"<<endl;
1888 ret<<".resetring:hover i { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAA2ElEQVQY013PMUoDcRDF4c+kEzxCsNNCrBQvIGhnlcYm11EkBxAraw8gglgIoiJpAoKIYlBcgrgopsma3c3fwt1k9cHA480M8xvQp/nMjorOWY5ov7IAYlpjQk7aYxcuWBpwFQgJnUcaYk7GhEDIGL5w+MVpKLIRyR2b4JOjvGhUKzHTv2W7iuSN479Dvu9plf1awbQ6y3x1sU5tjpVJcMbakF6Ycoas8Dl5xEHJ160wRdfqzXfa6XQ4PLDlicWUjxHxZfndL/N+RhiwNzl/Q6PDhn/qsl76H7prcApk2B1aAAAAAElFTkSuQmCC);}"<<endl;
1889 ret<<".resizering {float: right;}"<<endl;
80d59cd1 1890 resp->body = ret.str();
c146576d 1891 resp->status = 200;
1071abdd
CH
1892}
1893
dea47634 1894void AuthWebServer::webThread()
12c86877
BH
1895{
1896 try {
479e0976 1897 if(::arg().mustDo("api")) {
c0f6a1da 1898 d_ws->registerApiHandler("/api/v1/servers/localhost/cache/flush", &apiServerCacheFlush);
46d06a12 1899 d_ws->registerApiHandler("/api/v1/servers/localhost/config", &apiServerConfig);
46d06a12
PL
1900 d_ws->registerApiHandler("/api/v1/servers/localhost/search-log", &apiServerSearchLog);
1901 d_ws->registerApiHandler("/api/v1/servers/localhost/search-data", &apiServerSearchData);
1902 d_ws->registerApiHandler("/api/v1/servers/localhost/statistics", &apiServerStatistics);
1903 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/axfr-retrieve", &apiServerZoneAxfrRetrieve);
1904 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/cryptokeys/<key_id>", &apiZoneCryptokeys);
1905 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/cryptokeys", &apiZoneCryptokeys);
1906 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/export", &apiServerZoneExport);
24e11043
CJ
1907 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/metadata/<kind>", &apiZoneMetadataKind);
1908 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/metadata", &apiZoneMetadata);
46d06a12 1909 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/notify", &apiServerZoneNotify);
4bc8379e 1910 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/rectify", &apiServerZoneRectify);
46d06a12
PL
1911 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>", &apiServerZoneDetail);
1912 d_ws->registerApiHandler("/api/v1/servers/localhost/zones", &apiServerZones);
1913 d_ws->registerApiHandler("/api/v1/servers/localhost", &apiServerDetail);
1914 d_ws->registerApiHandler("/api/v1/servers", &apiServer);
9e6d2033 1915 d_ws->registerApiHandler("/api", &apiDiscovery);
c67bf8c5 1916 }
536ab56f
CH
1917 if (::arg().mustDo("webserver")) {
1918 d_ws->registerWebHandler("/style.css", boost::bind(&AuthWebServer::cssfunction, this, _1, _2));
1919 d_ws->registerWebHandler("/", boost::bind(&AuthWebServer::indexfunction, this, _1, _2));
1920 }
96d299db 1921 d_ws->go();
12c86877
BH
1922 }
1923 catch(...) {
e6a9dde5 1924 g_log<<Logger::Error<<"AuthWebServer thread caught an exception, dying"<<endl;
5bd2ea7b 1925 _exit(1);
12c86877
BH
1926 }
1927}