DnsServer/DnsServerCore/WebServiceLogsApi.cs

402 lines
18 KiB
C#
Raw Permalink Normal View History

2021-09-18 19:02:40 +05:30
/*
Technitium DNS Server
Copyright (C) 2025 Shreyas Zare (shreyas@technitium.com)
2021-09-18 19:02:40 +05:30
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using DnsServerCore.ApplicationCommon;
using DnsServerCore.Auth;
2021-09-18 19:02:40 +05:30
using DnsServerCore.Dns.Applications;
using Microsoft.AspNetCore.Http;
2021-09-18 19:02:40 +05:30
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
2022-12-24 13:11:25 +05:30
using System.Text.Json;
2021-09-18 19:02:40 +05:30
using System.Threading.Tasks;
using TechnitiumLibrary.Net;
using TechnitiumLibrary.Net.Dns;
2021-11-06 13:30:18 +05:30
using TechnitiumLibrary.Net.Dns.ResourceRecords;
2021-09-18 19:02:40 +05:30
namespace DnsServerCore
{
2025-02-15 12:51:16 +05:30
public partial class DnsWebService
2021-09-18 19:02:40 +05:30
{
2025-02-15 12:51:16 +05:30
class WebServiceLogsApi
{
#region variables
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
readonly DnsWebService _dnsWebService;
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
#endregion
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
#region constructor
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
public WebServiceLogsApi(DnsWebService dnsWebService)
{
_dnsWebService = dnsWebService;
}
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
#endregion
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
#region public
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
public void ListLogs(HttpContext context)
{
UserSession session = context.GetCurrentSession();
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.View))
throw new DnsWebServiceException("Access was denied.");
2025-02-15 12:51:16 +05:30
string[] logFiles = _dnsWebService._log.ListLogFiles();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
Array.Sort(logFiles);
Array.Reverse(logFiles);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
2025-02-15 12:51:16 +05:30
jsonWriter.WritePropertyName("logFiles");
jsonWriter.WriteStartArray();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
foreach (string logFile in logFiles)
{
jsonWriter.WriteStartObject();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
jsonWriter.WriteString("fileName", Path.GetFileNameWithoutExtension(logFile));
jsonWriter.WriteString("size", WebUtilities.GetFormattedSize(new FileInfo(logFile).Length));
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndArray();
2021-09-18 19:02:40 +05:30
}
2025-02-15 12:51:16 +05:30
public Task DownloadLogAsync(HttpContext context)
{
UserSession session = context.GetCurrentSession();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.View))
throw new DnsWebServiceException("Access was denied.");
2025-02-15 12:51:16 +05:30
HttpRequest request = context.Request;
2025-02-15 12:51:16 +05:30
string fileName = request.GetQueryOrForm("fileName");
int limit = request.GetQueryOrForm("limit", int.Parse, 0);
2025-02-15 12:51:16 +05:30
return _dnsWebService._log.DownloadLogAsync(context, fileName, limit * 1024 * 1024);
}
2025-02-15 12:51:16 +05:30
public void DeleteLog(HttpContext context)
{
UserSession session = context.GetCurrentSession();
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.Delete))
throw new DnsWebServiceException("Access was denied.");
2025-02-15 12:51:16 +05:30
HttpRequest request = context.Request;
2025-02-15 12:51:16 +05:30
string log = request.GetQueryOrForm("log");
2025-02-15 12:51:16 +05:30
_dnsWebService._log.DeleteLog(log);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
_dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] Log file was deleted: " + log);
}
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
public void DeleteAllLogs(HttpContext context)
{
UserSession session = context.GetCurrentSession();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.Delete))
throw new DnsWebServiceException("Access was denied.");
2025-02-15 12:51:16 +05:30
_dnsWebService._log.DeleteAllLogs();
2025-02-15 12:51:16 +05:30
_dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] All log files were deleted.");
}
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
public void DeleteAllStats(HttpContext context)
{
UserSession session = context.GetCurrentSession();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Dashboard, session.User, PermissionFlag.Delete))
throw new DnsWebServiceException("Access was denied.");
2025-02-15 12:51:16 +05:30
_dnsWebService._dnsServer.StatsManager.DeleteAllStats();
2025-02-15 12:51:16 +05:30
_dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] All stats files were deleted.");
}
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
public async Task QueryLogsAsync(HttpContext context)
{
UserSession session = context.GetCurrentSession();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.View))
throw new DnsWebServiceException("Access was denied.");
2025-02-15 12:51:16 +05:30
HttpRequest request = context.Request;
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
string name = request.GetQueryOrForm("name");
string classPath = request.GetQueryOrForm("classPath");
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._dnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
throw new DnsWebServiceException("DNS application was not found: " + name);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
if (!application.DnsQueryLogs.TryGetValue(classPath, out IDnsQueryLogs queryLogs))
throw new DnsWebServiceException("DNS application '" + classPath + "' class path was not found: " + name);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
long pageNumber = request.GetQueryOrForm("pageNumber", long.Parse, 1);
int entriesPerPage = request.GetQueryOrForm("entriesPerPage", int.Parse, 25);
bool descendingOrder = request.GetQueryOrForm("descendingOrder", bool.Parse, true);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
DateTime? start = null;
string strStart = request.QueryOrForm("start");
if (!string.IsNullOrEmpty(strStart))
start = DateTime.Parse(strStart, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
2025-02-15 12:51:16 +05:30
DateTime? end = null;
string strEnd = request.QueryOrForm("end");
if (!string.IsNullOrEmpty(strEnd))
end = DateTime.Parse(strEnd, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
IPAddress clientIpAddress = request.GetQueryOrForm("clientIpAddress", IPAddress.Parse, null);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
DnsTransportProtocol? protocol = null;
string strProtocol = request.QueryOrForm("protocol");
if (!string.IsNullOrEmpty(strProtocol))
protocol = Enum.Parse<DnsTransportProtocol>(strProtocol, true);
2025-02-15 12:51:16 +05:30
DnsServerResponseType? responseType = null;
string strResponseType = request.QueryOrForm("responseType");
if (!string.IsNullOrEmpty(strResponseType))
responseType = Enum.Parse<DnsServerResponseType>(strResponseType, true);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
DnsResponseCode? rcode = null;
string strRcode = request.QueryOrForm("rcode");
if (!string.IsNullOrEmpty(strRcode))
rcode = Enum.Parse<DnsResponseCode>(strRcode, true);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
string qname = request.GetQueryOrForm("qname", null);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
DnsResourceRecordType? qtype = null;
string strQtype = request.QueryOrForm("qtype");
if (!string.IsNullOrEmpty(strQtype))
qtype = Enum.Parse<DnsResourceRecordType>(strQtype, true);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
DnsClass? qclass = null;
string strQclass = request.QueryOrForm("qclass");
if (!string.IsNullOrEmpty(strQclass))
qclass = Enum.Parse<DnsClass>(strQclass, true);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
DnsLogPage page = await queryLogs.QueryLogsAsync(pageNumber, entriesPerPage, descendingOrder, start, end, clientIpAddress, protocol, responseType, rcode, qname, qtype, qclass);
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
jsonWriter.WriteNumber("pageNumber", page.PageNumber);
jsonWriter.WriteNumber("totalPages", page.TotalPages);
jsonWriter.WriteNumber("totalEntries", page.TotalEntries);
2025-02-15 12:51:16 +05:30
jsonWriter.WritePropertyName("entries");
jsonWriter.WriteStartArray();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
foreach (DnsLogEntry entry in page.Entries)
{
jsonWriter.WriteStartObject();
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
jsonWriter.WriteNumber("rowNumber", entry.RowNumber);
jsonWriter.WriteString("timestamp", entry.Timestamp);
jsonWriter.WriteString("clientIpAddress", entry.ClientIpAddress.ToString());
jsonWriter.WriteString("protocol", entry.Protocol.ToString());
jsonWriter.WriteString("responseType", entry.ResponseType.ToString());
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
if (entry.ResponseRtt.HasValue)
jsonWriter.WriteNumber("responseRtt", entry.ResponseRtt.Value);
2025-02-15 12:51:16 +05:30
jsonWriter.WriteString("rcode", entry.RCODE.ToString());
jsonWriter.WriteString("qname", entry.Question?.Name);
jsonWriter.WriteString("qtype", entry.Question?.Type.ToString());
jsonWriter.WriteString("qclass", entry.Question?.Class.ToString());
jsonWriter.WriteString("answer", entry.Answer);
2025-02-15 12:51:16 +05:30
jsonWriter.WriteEndObject();
}
2021-09-18 19:02:40 +05:30
2025-02-15 12:51:16 +05:30
jsonWriter.WriteEndArray();
2021-09-18 19:02:40 +05:30
}
2025-02-15 12:51:16 +05:30
public async Task ExportLogsAsync(HttpContext context)
{
UserSession session = context.GetCurrentSession();
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.View))
throw new DnsWebServiceException("Access was denied.");
2025-02-15 12:51:16 +05:30
HttpRequest request = context.Request;
2025-02-15 12:51:16 +05:30
string name = request.GetQueryOrForm("name");
string classPath = request.GetQueryOrForm("classPath");
2025-02-15 12:51:16 +05:30
if (!_dnsWebService._dnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
throw new DnsWebServiceException("DNS application was not found: " + name);
2025-02-15 12:51:16 +05:30
if (!application.DnsQueryLogs.TryGetValue(classPath, out IDnsQueryLogs queryLogs))
throw new DnsWebServiceException("DNS application '" + classPath + "' class path was not found: " + name);
2025-02-15 12:51:16 +05:30
DateTime? start = null;
string strStart = request.QueryOrForm("start");
if (!string.IsNullOrEmpty(strStart))
start = DateTime.Parse(strStart, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
2025-02-15 12:51:16 +05:30
DateTime? end = null;
string strEnd = request.QueryOrForm("end");
if (!string.IsNullOrEmpty(strEnd))
end = DateTime.Parse(strEnd, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
2025-02-15 12:51:16 +05:30
IPAddress clientIpAddress = request.GetQueryOrForm("clientIpAddress", IPAddress.Parse, null);
2025-02-15 12:51:16 +05:30
DnsTransportProtocol? protocol = null;
string strProtocol = request.QueryOrForm("protocol");
if (!string.IsNullOrEmpty(strProtocol))
protocol = Enum.Parse<DnsTransportProtocol>(strProtocol, true);
2025-02-15 12:51:16 +05:30
DnsServerResponseType? responseType = null;
string strResponseType = request.QueryOrForm("responseType");
if (!string.IsNullOrEmpty(strResponseType))
responseType = Enum.Parse<DnsServerResponseType>(strResponseType, true);
2025-02-15 12:51:16 +05:30
DnsResponseCode? rcode = null;
string strRcode = request.QueryOrForm("rcode");
if (!string.IsNullOrEmpty(strRcode))
rcode = Enum.Parse<DnsResponseCode>(strRcode, true);
2025-02-15 12:51:16 +05:30
string qname = request.GetQueryOrForm("qname", null);
2025-02-15 12:51:16 +05:30
DnsResourceRecordType? qtype = null;
string strQtype = request.QueryOrForm("qtype");
if (!string.IsNullOrEmpty(strQtype))
qtype = Enum.Parse<DnsResourceRecordType>(strQtype, true);
2025-02-15 12:51:16 +05:30
DnsClass? qclass = null;
string strQclass = request.QueryOrForm("qclass");
if (!string.IsNullOrEmpty(strQclass))
qclass = Enum.Parse<DnsClass>(strQclass, true);
2025-02-15 12:51:16 +05:30
static async Task WriteCsvFieldAsync(StreamWriter sW, string data)
{
2025-02-15 12:51:16 +05:30
if ((data is null) || (data.Length == 0))
return;
if (data.Contains('"', StringComparison.OrdinalIgnoreCase))
{
await sW.WriteAsync('"');
await sW.WriteAsync(data.Replace("\"", "\"\""));
await sW.WriteAsync('"');
}
else if (data.Contains(',', StringComparison.OrdinalIgnoreCase) || data.Contains(' ', StringComparison.OrdinalIgnoreCase))
{
await sW.WriteAsync('"');
await sW.WriteAsync(data);
await sW.WriteAsync('"');
}
else
{
await sW.WriteAsync(data);
}
}
2025-02-15 12:51:16 +05:30
DnsLogPage page;
long pageNumber = 1;
string tmpFile = Path.GetTempFileName();
2025-02-15 12:51:16 +05:30
try
{
2025-02-15 12:51:16 +05:30
using (FileStream csvFileStream = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
{
2025-02-15 12:51:16 +05:30
StreamWriter sW = new StreamWriter(csvFileStream, Encoding.UTF8);
await sW.WriteLineAsync("RowNumber,Timestamp,ClientIpAddress,Protocol,ResponseType,ResponseRtt,RCODE,Domain,Type,Class,Answer");
2025-02-15 12:51:16 +05:30
do
{
2025-02-15 12:51:16 +05:30
page = await queryLogs.QueryLogsAsync(pageNumber, 10000, false, start, end, clientIpAddress, protocol, responseType, rcode, qname, qtype, qclass);
foreach (DnsLogEntry entry in page.Entries)
{
await WriteCsvFieldAsync(sW, entry.RowNumber.ToString());
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.Timestamp.ToString("O"));
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.ClientIpAddress.ToString());
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.Protocol.ToString());
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.ResponseType.ToString());
await sW.WriteAsync(',');
if (entry.ResponseRtt.HasValue)
await WriteCsvFieldAsync(sW, entry.ResponseRtt.Value.ToString());
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.RCODE.ToString());
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.Question?.Name.ToString());
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.Question?.Type.ToString());
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.Question?.Class.ToString());
await sW.WriteAsync(',');
await WriteCsvFieldAsync(sW, entry.Answer);
await sW.WriteLineAsync();
}
}
2025-02-15 12:51:16 +05:30
while (pageNumber++ < page.TotalPages);
2025-02-15 12:51:16 +05:30
await sW.FlushAsync();
2025-02-15 12:51:16 +05:30
//send csv file
csvFileStream.Position = 0;
2025-02-15 12:51:16 +05:30
HttpResponse response = context.Response;
2025-02-15 12:51:16 +05:30
response.ContentType = "text/csv";
response.ContentLength = csvFileStream.Length;
response.Headers.ContentDisposition = "attachment;filename=" + _dnsWebService._dnsServer.ServerDomain + DateTime.UtcNow.ToString("_yyyy-MM-dd_HH-mm-ss") + "_query_logs.csv";
2025-02-15 12:51:16 +05:30
using (Stream output = response.Body)
{
await csvFileStream.CopyToAsync(output);
}
}
}
2025-02-15 12:51:16 +05:30
finally
{
2025-02-15 12:51:16 +05:30
try
{
File.Delete(tmpFile);
}
catch (Exception ex)
{
_dnsWebService._log.Write(ex);
}
}
}
2025-02-15 12:51:16 +05:30
#endregion
}
2021-09-18 19:02:40 +05:30
}
}