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