Esempio n. 1
0
        public bool CheckRecord(string domain)
        {
            var dnsResolver = new DnsStubResolver();
            var mxRecords   = dnsResolver.Resolve <MxRecord>(domain, RecordType.Mx);
            var priority    = mxRecords.ToArray().Min().Preference;

            //check priority if there is any MXrecords

            if (mxRecords.Count == 0)
            {
                return(false);
            }
            else
            {
                foreach (var record in mxRecords)
                {
                    Console.WriteLine(record.Preference + " " + record.ExchangeDomainName?.ToString());
                }

                for (int i = 0; i < mxRecords.Count; i++)
                {
                    if (mxRecords[i].Preference == priority)
                    {
                        provider = mxRecords[i].ExchangeDomainName?.ToString();
                    }
                }
                return(true);
            }
        }
Esempio n. 2
0
        public async Task <ParsedSPFRecord> GetSPF(string domainName, int lookupCount)
        {
            try
            {
                if (lookupCount <= 15)
                {
                    string           spfRecord  = null;
                    IDnsResolver     resolver   = new DnsStubResolver();
                    List <TxtRecord> txtRecords = resolver.Resolve <TxtRecord>(domainName, RecordType.Txt);

                    foreach (TxtRecord ip in txtRecords)
                    {
                        if (ip.TextData.Contains("v=spf1 "))
                        {
                            spfRecord = ip.TextData;
                        }
                    }
                    if (spfRecord.IsNullOrWhiteSpace())
                    {
                        return(null);
                    }
                    return(await ParseSPFOutput(spfRecord.Split(' '), domainName, lookupCount));
                }
                return(null);
            }
            catch
            {
                return(null);
            }
        }
        /// <summary>
        /// Applies this configuration to the specified <paramref name="resolver"/>.
        /// </summary>
        /// <param name="resolver">The resolver to be configured.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="resolver"/> is <see langword="null"/>.
        /// </exception>
        public override void Apply(IDnsResolver resolver)
        {
            DnsStubResolver stub = (DnsStubResolver)resolver;

            base.Apply(resolver);
            lock (stub.Servers) {
                stub.Servers.Clear();
                if (this.DiscoverServers)
                {
                    this.Log.Info("discovering network servers");
                    foreach (IPEndPoint server in DiscoverNetworkServers())
                    {
                        stub.Servers.Add(server);
                        this.Log.InfoFormat("discovered server, ep={0}", server);
                    }
                }
                foreach (DnsEndPointElement element in this.Servers)
                {
                    stub.Servers.Add(element.Endpoint);
                }
                if (stub.Servers.Count == 0)
                {
                    this.Log.Error("no servers specified in configuration and dicovery of network servers " +
                                   "failed to yield any servers or is disabled");
                }
            }
        }
        public DetectedProviderDTO DetectProviderFromEmailAddress(string emailAddress)
        {
            // validating the input parameter (mail address)
            if (!MailValidator.IsValidEmail(emailAddress))
            {
                throw new ApplicationException("Invalid e-mail format");
            }
            DetectedProviderDTO detectedProvider = new DetectedProviderDTO();

            detectedProvider.EmailAddress = emailAddress;

            //get the name of the host from the email address
            var address = emailAddress.Split("@")[1];

            // with DnsResolver we search from the Mx records to see what mail exchange server is responsible
            var resolver = new DnsStubResolver();
            var records  = resolver.Resolve <MxRecord>(address, RecordType.Mx);

            List <string> exchangeDomainServersResult = new List <string>();

            foreach (var record in records)
            {
                exchangeDomainServersResult.Add(record.ExchangeDomainName?.ToString());
            }

            var providerName = ProvidersInfo.GetProviderNameByExchangeName(exchangeDomainServersResult);

            detectedProvider.ProviderName = providerName;

            return(detectedProvider);
        }
Esempio n. 5
0
    /// <summary>
    /// Pulls the IP address(es) in use by the Azure App Service. This is used to check that A records are configured properly towards the App Service.
    /// If the App Service is in an ASE, the name is setup as follows: {App Service name}.{ASE name}.p.azurewebsites.net
    /// If the App Service is in the multi-tenant service, the name is setup as follows: {App Service name}.azurewebsites.net
    /// Puts the IP address list into the AppService object sent in as an argument so it can be used later.
    /// </summary>
    /// <param name="appService">Object containing all of the information on the App Service we are checking. Includes the ASE name and App Service name, which are directly used here.</param>
    public static void GetAppServiceIPAddress(AppService appService, DNSCheckErrors dnsCheckErrors)
    {
        string fullAppServiceURL = "";

        if (appService.IsASE)
        {
            fullAppServiceURL = appService.AppServiceName + "." + appService.AseName + ".p." + appService.AppServiceURLEnding;
        }
        else
        {
            fullAppServiceURL = appService.AppServiceName + "." + appService.AppServiceURLEnding;
        }

        IDnsResolver resolver = new DnsStubResolver();

        try
        {
            List <IPAddress> addresses = DnsResolverExtensions.ResolveHost(resolver, fullAppServiceURL);

            List <string> addressesString = new List <string>();
            foreach (IPAddress address in addresses)
            {
                addressesString.Add(address.ToString());
            }

            appService.IPAddresses = addressesString;
        }
        catch
        {
            dnsCheckErrors.appServiceIPLookupFailed = true;
            dnsCheckErrors.currentDNSFailures++;
        }
    }
Esempio n. 6
0
        public List <ParsedMXARecord> CustomDNSLookup(string domainName, string recordType)
        {
            List <ParsedMXARecord> customLookup = new List <ParsedMXARecord>();
            IDnsResolver           resolver     = new DnsStubResolver();

            try
            {
                if (recordType == "mx")
                {
                    List <MxRecord>          mxRecords = resolver.Resolve <MxRecord>(domainName, RecordType.Mx);
                    List <ARecord>           aRecords  = null;
                    List <IPVulnerabilities> ipVulns   = new List <IPVulnerabilities>();
                    foreach (MxRecord mxRecord in mxRecords)
                    {
                        aRecords = resolver.Resolve <ARecord>(mxRecord.ExchangeDomainName, RecordType.A);
                        foreach (ARecord aRecord in aRecords)
                        {
                            if (!aRecord.Address.ToString().IsNullOrWhiteSpace())
                            {
                                ipVulns.Add(SPFIPWhoIsLookup(aRecord.Address.ToString(), domainName));
                            }
                        }
                    }
                    customLookup.Add(new ParsedMXARecord()
                    {
                        ipLookup = ipVulns, lookupDomain = domainName
                    });
                }
                if (recordType == "a")
                {
                    List <ARecord>           aRecords = resolver.Resolve <ARecord>(domainName, RecordType.A);
                    List <IPVulnerabilities> ipVulns  = new List <IPVulnerabilities>();
                    foreach (ARecord aRecord in aRecords)
                    {
                        if (!aRecord.Address.ToString().IsNullOrWhiteSpace())
                        {
                            ipVulns.Add(SPFIPWhoIsLookup(aRecord.Address.ToString(), domainName));
                        }
                    }
                    customLookup.Add(new ParsedMXARecord()
                    {
                        ipLookup = ipVulns, lookupDomain = domainName
                    });
                }

                return(customLookup);
            }
            catch
            {
                return(customLookup);
            }
        }
Esempio n. 7
0
        public ActionResult EmailVerify(string email)
        {
            var resolver = new DnsStubResolver();
            var records  = resolver.Resolve <MxRecord>("gmail.com", RecordType.Mx);

            foreach (var record in records)
            {
                Console.WriteLine(record.ExchangeDomainName?.ToString());
            }
            var addr = new System.Net.Mail.MailAddress(email);

            return(Json((new EmailAddressAttribute().IsValid(email)).ToString()));
        }
Esempio n. 8
0
        }//end host resolve

        public static string recordResolve(string fqdn)
        {
            bldr.Clear();
            var resolver = new DnsStubResolver();

            bldr.Append("---------A RECORDS---------" + Environment.NewLine);
            var arecords = resolver.Resolve <ARecord>(fqdn, RecordType.A);

            foreach (var record in arecords)
            {
                bldr.Append(record.ToString() + Environment.NewLine);
            }
            bldr.Append("---------NS RECORDS---------" + Environment.NewLine);
            var nsrecords = resolver.Resolve <NsRecord>(fqdn, RecordType.Ns);

            foreach (var record in nsrecords)
            {
                bldr.Append(record.ToString() + Environment.NewLine);
            }
            bldr.Append("---------CNAME RECORDS---------" + Environment.NewLine);
            var crecords = resolver.Resolve <CNameRecord>(fqdn, RecordType.CName);

            foreach (var record in crecords)
            {
                bldr.Append(record.ToString() + Environment.NewLine);
            }
            bldr.Append("---------MX RECORDS---------" + Environment.NewLine);
            var mxrecords = resolver.Resolve <MxRecord>(fqdn, RecordType.Mx);

            foreach (var record in mxrecords)
            {
                bldr.Append(record.ToString() + Environment.NewLine);
            }
            bldr.Append("---------TXT RECORDS---------" + Environment.NewLine);
            var txtrecords = resolver.Resolve <TxtRecord>(fqdn, RecordType.Txt);

            foreach (var record in txtrecords)
            {
                bldr.Append(record.ToString() + Environment.NewLine);
            }
            bldr.Append("---------CAA RECORDS---------" + Environment.NewLine);
            var carecords = resolver.Resolve <CAARecord>(fqdn, RecordType.CAA);

            foreach (var record in carecords)
            {
                bldr.Append(record.ToString() + Environment.NewLine);
            }

            return(bldr.ToString());
        }//end record resolve
Esempio n. 9
0
        private static void Process(string addr)
        {
            writelogfile();
            writelogfile(addr);

            if (IsValidEmail(addr) == false)
            {
                writelogfile();
                writelogfile(addr + " is invalid mail address");
                //   WaitAnyKey();
                return;
            }

            string[] host     = (addr.Split('@'));
            string   hostname = host[1];

            var resolver = new DnsStubResolver();

            try
            {
                var records = resolver.Resolve <MxRecord>(hostname, RecordType.Mx);

                if (records.Count == 0)
                {
                    writelogfile("MX server don't exists");
                    return;
                }
                else
                {
                    int exist = 0;
                    foreach (var record in records)
                    {
                        if (record.ExchangeDomainName?.ToString() != null)
                        {
                            string server = record.ExchangeDomainName?.ToString();
                            writelogfile();
                            writelogfile(server);
                            exist = IsEmailAccountValid(server, addr);

                            //  if (exist != 0) writelogfile("\tResp:" + exist.ToString() + ":   email account exists");
                            //  else writelogfile("\temail account don't exists");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                writelogfile("Error : " + ex.Message);
            }
        }
Esempio n. 10
0
        private IEnumerable <ConnectorInfo> GroupByHost(SendableMail mail)
        {
            foreach (var recipientGroup in
                     mail.Recipients
                     .GroupBy(r => r.Host))
            {
                var host      = recipientGroup.Key;
                var connector = mail.Settings as ISendConnector
                                ?? sendConnectors.GetByDomain(host)
                                ?? sendConnectors.DefaultConnector;

                string remoteHost;
                int    remotePort;

                if (!connector.UseSmarthost)
                {
                    var records = new DnsStubResolver().Resolve <MxRecord>(recipientGroup.Key);
                    var record  = records.OrderBy(r => r.Preference).FirstOrDefault();

                    if (record == null)
                    {
                        TriggerMailError(mail, new ConnectorInfo
                        {
                            Connector = connector,
                            Host      = recipientGroup.Key,
                            Port      = 25,
                            Addresses = recipientGroup
                        }, null, new NoMailHostFoundException(recipientGroup.Key));
                        continue;
                    }
                    remoteHost = record.ExchangeDomainName.ToString();
                    remotePort = 25;
                }
                else
                {
                    remoteHost = connector.RemoteAddress.ToString();
                    remotePort = connector.RemotePort;
                }

                yield return(new ConnectorInfo
                {
                    Connector = connector,
                    Host = remoteHost,
                    Port = remotePort,
                    Addresses = recipientGroup
                });
            }
        }
Esempio n. 11
0
        // Get all MX records for a domain using a recursive resolver
        public static void Test4()
        {
            System.Net.NetworkInformation.IPGlobalProperties ipgp =
                System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();

            // IDnsResolver resolver = new RecursiveDnsResolver(); // Warning: Doesn't work
            IDnsResolver     resolver   = new DnsStubResolver();
            List <SrvRecord> srvRecords = resolver.Resolve <SrvRecord>("_ldap._tcp." + ipgp.DomainName, RecordType.Srv);

            foreach (SrvRecord thisRecord in srvRecords)
            {
                // System.Console.WriteLine(thisRecord.Name);
                System.Console.WriteLine(thisRecord.Target);
                System.Console.WriteLine(thisRecord.Port);

                string url = "LDAP://" + thisRecord.Target + ":" + thisRecord.Port; // Note: OR LDAPS:// - but Novell doesn't want these parts anyway
                System.Console.WriteLine(url);
            } // Next thisRecord
        }
Esempio n. 12
0
 private void LoadConfiguration()
 {
     // These could easily be made into configuration points but I think that users would
     // find their persistence annoying.
     this.DefaultQueryType  = DnsQueryType.A;
     this.DefaultQueryClass = DnsQueryClass.IN;
     this.Resolver          = DnsStubResolver.Instance();
     try {
         this.ExeConfig     = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
         this.ConfigSection = (NDigSection)this.ExeConfig.Sections[NDigSection.DefaultLocation];
         if (this.ConfigSection == null)
         {
             this.ConfigSection = new NDigSection();
             this.ExeConfig.Sections.Add(NDigSection.DefaultLocation, this.ConfigSection);
         }
     } catch (ConfigurationErrorsException exc) {
         _log.Error(exc);
         this.ConfigSection = new NDigSection();
         WriteLine("WARNING: failed to load configuration: '{0}'", exc.Message);
         WritePageBreak();
     }
 }
Esempio n. 13
0
        public static bool IsValidEmail(string email)
        {
            bool retVal = false;

            if (!string.IsNullOrEmpty(email))
            {
                int index = email.IndexOf('@');
                if (index > 0)
                {
                    string domain = email.Substring(index + 1);

                    if (validDomains.Contains(domain))
                    {
                        return(true);
                    }
                    if (invalidDomains.Contains(domain))
                    {
                        return(false);
                    }

                    DnsStubResolver resolver = new DnsStubResolver();
                    List <MxRecord> records  = resolver.Resolve <MxRecord>(domain, RecordType.Mx);
                    retVal = records.Count > 0;
                    if (retVal)
                    {
                        validDomains.Add(domain);
                    }
                    else
                    {
                        invalidDomains.Add(domain);
                        Console.WriteLine($"Invalid email {email}");
                    }
                }
            }
            return(retVal);
        }
Esempio n. 14
0
        public bool SubDomainSPFNotExists(string domainName)
        {
            try
            {
                IDnsResolver     resolver     = new DnsStubResolver();
                List <TxtRecord> txtRecords   = resolver.Resolve <TxtRecord>(domainName, RecordType.Txt);
                DomainParser     domainParser = new DomainParser(new WebTldRuleProvider());
                string           parentDomain = domainParser.Get(domainName).RegistrableDomain;

                txtRecords = resolver.Resolve <TxtRecord>("test1231312312." + parentDomain, RecordType.Txt);
                foreach (TxtRecord ip in txtRecords)
                {
                    if (ip.TextData.Contains("v=spf1 "))
                    {
                        return(false);
                    }
                }
                return(true);
            }
            catch
            {
                return(true);
            }
        }
Esempio n. 15
0
    private static Task <List <TxtRecord> > GetTxtRecords(string hostname)
    {
        var resolver = new DnsStubResolver();

        return(resolver.ResolveAsync <TxtRecord>(hostname, RecordType.Txt));
    }
Esempio n. 16
0
        private void ButtonStart_Click(object sender, EventArgs e)
        {
            try
            {
                // Резолв имени домена
                System.Net.IPAddress[] ip = System.Net.Dns.GetHostAddresses(domainName.Text);

                // Определение вхождения IP-адреса в подсеть и вывод информации в поле 'IP-адрес'
                if (okby.Contains(ip[0].ToString()))
                {
                    ipAddress.Text = ip[0].ToString() + " (наш хостинг)";
                }
                else if (hosterby.MatchExists(ip[0].ToString()))
                {
                    ipAddress.Text = ip[0].ToString() + " (hoster.by)";
                }
                else
                {
                    ipAddress.Text = ip[0].ToString();
                }
            }
            catch (Exception)
            {
                ipAddress.Clear();
                mxRecord.Clear();
                nsRecords.Clear();
                MessageBox.Show("Введено неверное имя домена или данный домен не существует");
                return;
            }

            // инициализация резолвера ресурсных записей домена
            var resolver = new DnsStubResolver();

            // определение MX-записи домена
            var    mxs = resolver.Resolve <MxRecord>(domainName.Text, RecordType.Mx);
            String s1;

            String[] words = { };
            System.Net.IPAddress[] mxip = null;
            if (mxs.Any())
            {
                s1    = mxs[0].ToString();
                words = s1.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                // Резолв IP-адреса MX-записи
                mxip = System.Net.Dns.GetHostAddresses(words.Last().TrimEnd('.'));
            }



            // Определение вхождения IP-адреса MX-записи в подсеть и вывод информации в поле 'Почта (MX-запись)'
            if (mxs.Any() == false)
            {
                mxRecord.Text = "Почтовые записи отсутствуют";
            }
            else if (okby.Contains(mxip[0].ToString()))
            {
                mxRecord.Text = words.Last().TrimEnd('.') + " (наш хостинг)";
            }
            else if (hosterby.MatchExists(mxip[0].ToString()))
            {
                mxRecord.Text = words.Last().TrimEnd('.') + " hoster.by";
            }
            else
            {
                mxRecord.Text = words.Last().TrimEnd('.');
            }

            // определение NS-записей домена
            var nss = resolver.Resolve <NsRecord>(domainName.Text, RecordType.Ns);

            // вывод NS-записей домена в поле 'DNS-серверы (NS-записи)'
            nsRecords.Clear();
            nss.Sort();
            foreach (NsRecord element in nss)
            {
                s1 = element.ToString();
                String[] wns = s1.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                nsRecords.Text += wns.Last().TrimEnd('.') + '\n';
            }
        }
Esempio n. 17
0
        public void DoGetHostEntry(string hostname)
        {
            IDnsResolver resolver = new DnsStubResolver();

            RecordType mx = new RecordType();

            mx = RecordType.Mx;

            //IPHostEntry host;

            try
            {
                //host = Dns.GetHostEntry(hostname);

                // This block works but has a problem with parsing only IPs
                // becuase it has no AnswerRecords method so you can't filter
                // record. It comes with hostname and TTL

                List <DnsRecordBase> addresses = resolver.Resolve <DnsRecordBase>(hostname, mx);
                //Console.WriteLine("GetHostEntry({0}) returns:", hostname);

                // This Block Resolves IP adress depending on DnsClient class
                // Has a problem with hostname beacuse it does not takes string
                // but a DnsHostname class

                /*var response = DnsClient.Default.Resolve(hostname,RecordType.Mx);
                 * var records = response.AnswerRecords.OfType<MxRecord>();
                 * foreach (var record in records)
                 * {
                 *  textBox2.Text = record.ExchangeDomainName.ToString();
                 * }
                 */


                //Console.WriteLine("    {0}", ip);
                //textBox2.Text = ip.ToString();
                foreach (DnsRecordBase host in addresses)
                {
                    textBox2.Text = host.ToString();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException caught!!!");
                Console.WriteLine("Source : " + e.Source);
                Console.WriteLine("Message : " + e.Message);
                textBox2.Text = "Not Found!";
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException caught!!!");
                Console.WriteLine("Source : " + e.Source);
                Console.WriteLine("Message : " + e.Message);
                textBox2.Text = "Not Found!";
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught!!!");
                Console.WriteLine("Source : " + e.Source);
                Console.WriteLine("Message : " + e.Message);
                textBox2.Text = "Error!";
            }
        }
Esempio n. 18
0
        } // End Sub Test1

        // Get reverse domain name for a specified IP address using local configured DNS servers
        public static void Test2()
        {
            IDnsResolver resolver = new DnsStubResolver();

            ARSoft.Tools.Net.DomainName name = resolver.ResolvePtr(System.Net.IPAddress.Parse("192.0.2.1"));
        } // End Sub Test2
Esempio n. 19
0
 // Get reverse domain name for a specified IP address using local configured DNS servers
 public static void Test2()
 {
     IDnsResolver resolver = new DnsStubResolver();
     DomainName   name     = resolver.ResolvePtr(IPAddress.Parse("192.0.2.1"));
 }
Esempio n. 20
0
 // Get all addresses for a domain name using the local configured DNS servers
 public static void Test1()
 {
     IDnsResolver     resolver  = new DnsStubResolver();
     List <IPAddress> addresses = resolver.ResolveHost("www.example.com");
 }
Esempio n. 21
0
        // Get all addresses for a domain name using the local configured DNS servers
        public static void Test1()
        {
            IDnsResolver resolver = new DnsStubResolver();

            System.Collections.Generic.List <System.Net.IPAddress> addresses = resolver.ResolveHost("www.example.com");
        } // End Sub Test1
Esempio n. 22
0
        public SPFDMARCRecord GetSPFDMARCRecord(string domainName)
        {
            bool           longSPF   = false;
            SPFDMARCRecord dnsRecord = new SPFDMARCRecord();

            dnsRecord.domainName = domainName;
            try
            {
                IDnsResolver     resolver   = new DnsStubResolver();
                List <TxtRecord> txtRecords = resolver.Resolve <TxtRecord>(domainName, RecordType.Txt);
                foreach (TxtRecord ip in Enumerable.Reverse(txtRecords))
                {
                    if (ip.TextData.Contains("v=spf1 "))
                    {
                        dnsRecord.spfRecord = ip.TextData;
                        if (!ip.TextData.Contains("+all") && !ip.TextData.Contains("~all") && !ip.TextData.Contains("-all") && !ip.TextData.Contains("?all"))
                        {
                            longSPF = true;
                        }
                    }
                    else if (longSPF)
                    {
                        if (ip.TextData.Contains("+all") || ip.TextData.Contains("~all") || ip.TextData.Contains("-all") || ip.TextData.Contains("?all"))
                        {
                            dnsRecord.spfRecord += ip.TextData;
                        }
                    }
                }
                try
                {
                    txtRecords = resolver.Resolve <TxtRecord>("_dmarc." + domainName, RecordType.Txt);
                    foreach (TxtRecord ip in txtRecords)
                    {
                        if (ip.TextData.Contains("v=DMARC1"))
                        {
                            dnsRecord.dmarcRecord = ip.TextData;
                        }
                    }
                    if (dnsRecord.dmarcRecord.IsNullOrWhiteSpace())
                    {
                        throw new Exception();
                    }
                }
                catch
                {
                    DomainParser domainParser = new DomainParser(new WebTldRuleProvider());
                    string       parentDomain = domainParser.Get(domainName).RegistrableDomain;

                    txtRecords = resolver.Resolve <TxtRecord>("_dmarc." + parentDomain, RecordType.Txt);
                    foreach (TxtRecord ip in txtRecords)
                    {
                        if (ip.TextData.Contains("v=DMARC1"))
                        {
                            dnsRecord.dmarcRecord = ip.TextData;
                        }
                    }
                }
            }
            catch
            {
                return(dnsRecord);
            }
            return(dnsRecord);
        }