private async Task <DnsMessageBase> ProcessMessageAsync(DnsMessageBase query, ProtocolType protocolType, IPEndPoint remoteEndpoint) { QueryReceivedEventArgs eventArgs = new QueryReceivedEventArgs(query, protocolType, remoteEndpoint); await QueryReceived.RaiseAsync(this, eventArgs); return(eventArgs.Response); }
static async Task OnQueryReceived(object sender, QueryReceivedEventArgs e) { DnsMessage query = e.Query as DnsMessage; if (query == null) return; DnsMessage response = query.CreateResponseInstance(); foreach (var question in query.Questions) { //Console.WriteLine(question.Name.ToString()); DnsMessage upstreamResponse; Boolean useDefault = true; foreach (var domain in domains) { if (question.Name.ToString().ToLower().Contains(domain)) { useDefault = false; } } if (useDefault) { upstreamResponse = await defaultClient.ResolveAsync(question.Name, question.RecordType, question.RecordClass); } else { upstreamResponse = await netflixClient.ResolveAsync(question.Name, question.RecordType, question.RecordClass); } if (upstreamResponse != null) { foreach (DnsRecordBase record in (upstreamResponse.AnswerRecords)) { response.AnswerRecords.Add(record); } foreach (DnsRecordBase record in (upstreamResponse.AdditionalRecords)) { response.AdditionalRecords.Add(record); } response.ReturnCode = ReturnCode.NoError; e.Response = response; } } }
private async Task <DnsMessageBase> ProcessMessageAsync(DnsMessageBase query, ProtocolType protocolType, IPEndPoint remoteEndpoint) { if (query.TSigOptions != null) { switch (query.TSigOptions.ValidationResult) { case ReturnCode.BadKey: case ReturnCode.BadSig: query.IsQuery = false; query.ReturnCode = ReturnCode.NotAuthoritive; query.TSigOptions.Error = query.TSigOptions.ValidationResult; query.TSigOptions.KeyData = null; #pragma warning disable 4014 InvalidSignedMessageReceived.RaiseAsync(this, new InvalidSignedMessageEventArgs(query, protocolType, remoteEndpoint)); #pragma warning restore 4014 return(query); case ReturnCode.BadTime: query.IsQuery = false; query.ReturnCode = ReturnCode.NotAuthoritive; query.TSigOptions.Error = query.TSigOptions.ValidationResult; query.TSigOptions.OtherData = new byte[6]; int tmp = 0; TSigRecord.EncodeDateTime(query.TSigOptions.OtherData, ref tmp, DateTime.Now); #pragma warning disable 4014 InvalidSignedMessageReceived.RaiseAsync(this, new InvalidSignedMessageEventArgs(query, protocolType, remoteEndpoint)); #pragma warning restore 4014 return(query); } } QueryReceivedEventArgs eventArgs = new QueryReceivedEventArgs(query, protocolType, remoteEndpoint); await QueryReceived.RaiseAsync(this, eventArgs); return(eventArgs.Response); }
private static async Task OnQueryReceived(object sender, QueryReceivedEventArgs e) { var message = e.Query as DnsMessage; var response = message?.CreateResponseInstance(); if (message?.Questions.Count == 1) { // send query to upstream _servers var question = message.Questions[0]; var upstreamResponse = await DnsClient.Default.ResolveAsync(question.Name, question.RecordType, question.RecordClass); // if got an answer, copy it to the message sent to the client if (upstreamResponse != null) { foreach (var record in (upstreamResponse.AnswerRecords)) { response.AnswerRecords.Add(record); } foreach (var record in (upstreamResponse.AdditionalRecords)) { response.AdditionalRecords.Add(record); } response.ReturnCode = ReturnCode.NoError; // set the response e.Response = response; } } }
private async Task<DnsMessageBase> ProcessMessageAsync(DnsMessageBase query, ProtocolType protocolType, IPEndPoint remoteEndpoint) { if (query.TSigOptions != null) { switch (query.TSigOptions.ValidationResult) { case ReturnCode.BadKey: case ReturnCode.BadSig: query.IsQuery = false; query.ReturnCode = ReturnCode.NotAuthoritive; query.TSigOptions.Error = query.TSigOptions.ValidationResult; query.TSigOptions.KeyData = null; #pragma warning disable 4014 InvalidSignedMessageReceived.RaiseAsync(this, new InvalidSignedMessageEventArgs(query, protocolType, remoteEndpoint)); #pragma warning restore 4014 return query; case ReturnCode.BadTime: query.IsQuery = false; query.ReturnCode = ReturnCode.NotAuthoritive; query.TSigOptions.Error = query.TSigOptions.ValidationResult; query.TSigOptions.OtherData = new byte[6]; int tmp = 0; TSigRecord.EncodeDateTime(query.TSigOptions.OtherData, ref tmp, DateTime.Now); #pragma warning disable 4014 InvalidSignedMessageReceived.RaiseAsync(this, new InvalidSignedMessageEventArgs(query, protocolType, remoteEndpoint)); #pragma warning restore 4014 return query; } } QueryReceivedEventArgs eventArgs = new QueryReceivedEventArgs(query, protocolType, remoteEndpoint); await QueryReceived.RaiseAsync(this, eventArgs); return eventArgs.Response; }
private static void OnQueryReceived(object sender, QueryReceivedEventArgs e) { StringBuilder sb = new StringBuilder(); try { DnsMessage message = e.Query as DnsMessage; message.IsQuery = false; if (message == null || message.Questions.Count == 0) { e.Response = message; message.ReturnCode = ReturnCode.ServerFailure; e.Response = message; Console.WriteLine(sb); return; } //Log DNS query sb.AppendFormat("* {0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); for (int i = 0; i < message.Questions.Count; i++) { sb.AppendFormat("[{0}]\t{1}\t{2}\r\n", i, message.Questions[i].RecordType.ToString(), message.Questions[i].Name); } if (message.Questions.Count > 1) { sb.AppendFormat("Response: (x) ServerFailure -- Multiple questions\r\n"); e.Response = message; message.ReturnCode = ReturnCode.ServerFailure; e.Response = message; Console.WriteLine(sb); return; } DnsQuestion question = message.Questions[0]; if (!question.Name.Equals(domain, StringComparison.CurrentCultureIgnoreCase) && !question.Name.EndsWith(string.Concat(".", domain), StringComparison.CurrentCultureIgnoreCase)) { e.Response = message; message.ReturnCode = ReturnCode.ServerFailure; e.Response = message; sb.AppendFormat("Response: (x) ServerFailure -- Domain \"{0}\" is invalid\r\n", question.Name); Console.WriteLine(sb); return; } if (question.RecordType == RecordType.Txt) { //MX message.ReturnCode = ReturnCode.NoError; message.AnswerRecords.Add(new TxtRecord(domain, ttlSeconds, "Hello world")); message.ReturnCode = ReturnCode.NoError; e.Response = message; sb.AppendFormat("Response: OK!\r\n", question.Name); Console.WriteLine(sb); return; } else if (question.RecordType == RecordType.A) { //A string subdomain = question.Name.Substring(0, question.Name.LastIndexOf(domain)); if (subdomain.Length > 0) subdomain = subdomain.Substring(0, subdomain.Length - 1); //remove o ponto if (subdomain.Length == 0) { //raiz do domÃnio var record = new ARecord(question.Name, ttlSeconds, System.Net.IPAddress.Parse("192.168.1.1")); message.AnswerRecords.Add(record); message.ReturnCode = ReturnCode.NoError; e.Response = message; sb.AppendFormat("Response: OK!\r\n", question.Name); return; } else { //subdomÃnios if (subdomain.Length > 0 && subdomain.StartsWith("local_", StringComparison.CurrentCultureIgnoreCase)) { //recebe: local_192-168-10-10.[domain] e retorna: "192.168.10.10" string ipString = subdomain.Substring("local_".Length); ipString = ipString.Replace("-", "."); System.Net.IPAddress ipAddress; if (System.Net.IPAddress.TryParse(ipString, out ipAddress)) { var record = new ARecord(question.Name, ttlSeconds, ipAddress); message.AnswerRecords.Add(record); message.ReturnCode = ReturnCode.NoError; e.Response = message; sb.AppendFormat("Response: OK!\r\n", question.Name); Console.WriteLine(sb); return; } else { sb.AppendFormat("Response: (x) ServerFailure -- Invalid IP \"{0}\" invalid. Example of subdomain valid: \"local_192-168-10-10\"\r\n", ipString); message.ReturnCode = ReturnCode.ServerFailure; e.Response = message; Console.WriteLine(sb); return; } } else { sb.AppendFormat("Response: (x) ServerFailure -- Subdomain \"{0}\" invalid. Example of subdomain valid: \"local_192-168-10-10\"\r\n", subdomain); message.ReturnCode = ReturnCode.ServerFailure; e.Response = message; Console.WriteLine(sb); return; } } } sb.AppendFormat("Response: (x) ServerFailure -- Record Type \"{0}\" invalid\r\n", question.RecordType.ToString()); message.ReturnCode = ReturnCode.ServerFailure; e.Response = message; } catch (System.Exception ex) { sb.AppendFormat("{0} EXCEPTION: {1}\r\n{2}\r\n\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), ex.Message, ex.StackTrace); } Console.WriteLine(sb.ToString()); }
private async Task Server_QueryReceived(object sender, ARSoft.Tools.Net.Dns.QueryReceivedEventArgs e) { bool foundQuery = false; DnsMessage query = e.Query as DnsMessage; if (query == null) { return; } DnsMessage response = query.CreateResponseInstance(); try { C.WriteLine($"DnsServer: Questions: {query.Questions.Count}", true, "DNS"); for (int idx = 0; idx < query.Questions.Count; idx++) { var question = query.Questions[idx]; using (var connection = db.Connection()) { using (var command = new SqliteCommand( "SELECT * FROM DnsEntries WHERE RecordType = @RecordType AND RecordClass = @RecordClass AND DomainName = @DomainName;", connection)) { command.Parameters.AddWithValue("@RecordType", question.RecordType.ToString()); command.Parameters.AddWithValue("@RecordClass", question.RecordClass.ToString()); command.Parameters.AddWithValue("@DomainName", question.Name.ToString()); using (var reader = command.ExecuteReader()) { C.WriteLine($" Questions [{idx:000}] RES({reader.HasRows}): Type({question.RecordType}), Class({question.RecordClass}), {question.Name}", true, "DNS"); //Every new row will create a new dictionary that holds the columns while (reader.Read()) { try { var dnStr = reader["DomainName"] as string; var dn = DomainName.Parse(dnStr); if (dn == null) { continue; } var ttl = (System.Int64)reader["TTL"]; var rt = (RecordType)Enum.Parse(typeof(RecordType), reader["RecordType"] as string); var rc = (RecordClass)Enum.Parse(typeof(RecordClass), reader["RecordClass"] as string); if (rt == RecordType.A) { if (reader["Address"] == null) { continue; } var addr = reader["Address"] as string; var aRec = new ARecord(dn, Convert.ToInt32(ttl), IPAddress.Parse(addr)); response.AnswerRecords.Add(aRec); foundQuery = true; } } catch (Exception ex) { C.WriteLine($" Questions [{idx:000}]: {C.Red}Exception: {ex.ToString()}", true, "DNS:ERROR"); } } } } } } // Fallback if (dnsFallback != null && !foundQuery) { DnsQuestion question = query.Questions[0]; var resolve = dnsFallback.Resolve(question.Name); DnsMessage upstreamResponse = await dnsFallback.ResolveAsync( question.Name, question.RecordType, question.RecordClass); e.Response = upstreamResponse; return; } response.ReturnCode = ReturnCode.NoError; } catch (Exception ex) { response.ReturnCode = ReturnCode.ServerFailure; C.WriteLine($"{C.Red}{ex.ToString()}", true, "DNS:ERROR"); } // set the response e.Response = response; }