网站安全攻击和防御中的屏蔽代理服务器

简介: 网站安全攻击和防御中的屏蔽代理服务器 网站安全一直是个重要话题,本人写了网络攻防的屏蔽代理服务器相关代码,分享下:1. 写个网页request类:using System;using System.

网站安全攻击和防御中的屏蔽代理服务器

 

网站安全一直是个重要话题,本人写了网络攻防的屏蔽代理服务器相关代码,分享下:

1. 写个网页request类:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class WebRequestUtil
    {
        public static string responseBody = string.Empty; 
        public static bool GetWeb(string uri, string proxyAddress = "", int proxyPort = 0)
        {
            string serverUri = string.Format(uri);

            ////set limit for supporting 200 connection
            ServicePointManager.DefaultConnectionLimit = 1000;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUri);

            if (!string.IsNullOrEmpty(proxyAddress))
            {
                WebProxy myproxy = new WebProxy(proxyAddress, proxyPort);
                request.Proxy = myproxy;
            }

            ////extend timeout for decrease request timeout re-trying times
            request.Timeout = 60 * 1000;
            request.Method = @"GET";

            UTF8Encoding encoding = new UTF8Encoding();
            request.Headers.Set("Cache-Control", @"no-cache");
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                bool isSent = false;
                int retryCount = 0;
                string errorStr = string.Empty;
                while (!isSent && retryCount <= 2)
                {
                    retryCount++;
                    try
                    {
                        using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                        {
                            responseBody = stream.ReadToEnd();
                        }

                        isSent = true;
                    }
                    catch (Exception exc)
                    {
                        if (!errorStr.Contains(exc.ToString()))
                        {
                            errorStr += exc.ToString();
                        }

                        ////Re-try when operation timeout
                        if (!exc.ToString().Contains("The operation has timed out"))
                        {
                            LogError(exc.ToString());
                        }

                        Thread.Sleep(1000);
                    }
                }

                if (retryCount > 100)
                {
                    string err = string.Format("request.GetRequestStream try 100 times and timeout! detail error: {0}", errorStr);
                    LogError(err);
                    return false;
                }

                ////need to close or abort request for each call to fix timeout issue, otherwise it will fail when the 3rd call!
                if (request != null)
                {
                    request.Abort();
                }

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    string err = string.Format("Failed, error:{1}", response.ToString());
                    LogError(err);
                    return false;
                }

                if (response != null)
                {
                    response.Close();
                }
            }
            catch (Exception exc)
            {
                LogError(exc.ToString());
                return false;
            }

            return true;
        }

        public static void LogError(string content)
        {
            File.AppendAllText("log.log", "ERROR: " + content + Environment.NewLine);
        }
    }
}

2. 采集代理服务器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static int FailCount = 0;
        static int TotalCount = 0;
        const string IPRegex = @"(\d{1,3}\.){3}\d{1,3}</td><td>\d{1,4}";
        static void Main()
        {
            DateTime startTime = DateTime.Now;
            //int i = 0;
            //while (DateTime.Now < startTime.AddMinutes(5))
            {
                //WriteLog("Try " + i++ + "th round! Begin" + DateTime.Now.ToString());

                //WebRequestUtil.GetWeb(@"http://edu.laliyun.com/test.php", "147.47.106.36", 1920);
                //File.AppendAllText(@"test.txt", WebRequestUtil.responseBody, Encoding.UTF8);

                string url = @"http://proxy.com.ru/gaoni/list_{0}.html";
                for (int i = 1; i <= 63; i++)
                {
                    WebRequestUtil.GetWeb(string.Format(url, i));

                    string sourceString = WebRequestUtil.responseBody;
                    string IPs = string.Empty;
                    var matches = Regex.Matches(sourceString, IPRegex);
                    if (matches.Count > 0)
                    {
                        foreach (var m in matches)
                        {
                            string ip = m.ToString().Replace("</td><td>", "#").Split('#')[0];
                            IPs += ip + Environment.NewLine;
                        }
                    }

                    File.AppendAllText(@"blacklist.txt", IPs, Encoding.UTF8);
                    Console.WriteLine("Done " + i.ToString() + " page.");
                }

                //Test2(1);
                //WriteLog("Total:" + TotalCount);
                //WriteLog("Fail:" + FailCount);
                //WriteLog("Try " + i++ + "th round! End" + DateTime.Now.ToString());
            }
            Console.WriteLine("Please press any key to end of this program!\r\n");
            Console.ReadKey();
        }

        static void WriteTotalLog(string message)
        {
            //WriteLog(message, @"C:\TotalLog.txt");
        }

        static void WriteLog(string message, string path = @"C:\Test\Test#log.txt")
        {
            message = "ThreadId:" + Thread.CurrentThread.ManagedThreadId + "," + message + Environment.NewLine;
            File.AppendAllText(path.Replace("#", Thread.CurrentThread.ManagedThreadId.ToString()), message);
        }

        static void WriteErrorLog(string message)
        {
            WriteLog(message, @"C:\TestError" + Thread.CurrentThread.ManagedThreadId + "log.txt");
        }


3. 多线程攻击服务器代码:

static void Test2(int numThreads)
        {
            ManualResetEvent resetEvent = new ManualResetEvent(false);
            int toProcess = numThreads;

            // Start workers.
            for (int i = 0; i < numThreads; i++)
            {
                new Thread(delegate()
                {
                    test();
                    //Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
                    // If we're the last thread, signal
                    if (Interlocked.Decrement(ref toProcess) == 0)
                        resetEvent.Set();
                }).Start();
            }

            // Wait for workers.
            resetEvent.WaitOne();
            WriteTotalLog("Done all!");
        }

        static void test()
        {
            TotalCount++;

            try
            {
                WebRequestUtil.GetWeb(@"http://1111.ip138.com/ic.asp", "219.239.236.49", 8888);
                File.AppendAllText(@"response.html", WebRequestUtil.responseBody, Encoding.UTF8);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "pass");
            }
            catch (Exception exc2)
            {
                FailCount++;
                WriteErrorLog("Error:" + exc2.ToString());
            }
        }
    }
}


4. Php网页屏蔽代理服务器代码:

<?php

$page= file_get_contents("blacklist.txt");

	if(!empty($_SERVER['HTTP_CLIENT_IP']))
	{
        	//check ip from share internet
        	$ip = $_SERVER['HTTP_CLIENT_IP'];
    	}
	else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	{
        	//to check ip is pass from proxy
        	$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    	}
	else{
        	$ip = $_SERVER['REMOTE_ADDR'];
    	}

	echo  $ip;
if(strpos($page,$ip)!== false)
echo "您使用代理浏览我们的网站,很抱歉本站出于安全考虑屏蔽了代理,请使用非代理浏览,谢谢!";
else
echo "执行程序的正常逻辑";
?>


演示代码:http://edu.laliyun.com/test.php

目录
相关文章
|
6月前
|
SQL 监控 安全
服务器安全性漏洞和常见攻击方式解析
服务器安全性漏洞和常见攻击方式解析
|
3月前
|
存储 安全 数据可视化
如何规避DDoS攻击带来的风险?服务器DDoS防御软件科普
如何规避DDoS攻击带来的风险?服务器DDoS防御软件科普
101 0
|
28天前
|
存储 安全 数据可视化
提升网络安全防御有效性,服务器DDoS防御软件解读
提升网络安全防御有效性,服务器DDoS防御软件解读
40 1
提升网络安全防御有效性,服务器DDoS防御软件解读
|
5月前
|
负载均衡 监控 网络协议
高防服务器如何处理DDoS攻击?关于高防服务器的一些技术细节
DDoS攻击是网络威胁,通过大量请求淹没服务器。防御措施包括:备份网站以备切换,拦截异常HTTP请求,增加带宽抵御流量攻击,使用CDN分发内容并隐藏源IP。防御策略涉及流量清洗、黑洞路由、负载均衡等。硬件如防火墙、IDS/IPS也重要,云服务提供自动防护和弹性扩容。
117 3
|
6月前
|
安全 NoSQL Redis
服务器又被攻击了,我这样做...
近期遭遇阿里云服务器频繁报警,经分析发现是由于测试服务器所有端口对公网开放,导致自动化程序对其扫描。黑客可能利用类似Redis的未授权访问漏洞进行攻击。为避免此类问题,建议:1. 不开放不必要的端口;2. 避免以root权限运行服务;3. 设置服务器IP白名单;4. 定期更换密码。保持良好安全习惯可保障服务器安全。
1199 3
服务器又被攻击了,我这样做...
|
5月前
|
监控 安全 网络安全
蓝易云 - 服务器遭受攻击,CPU升高,流量升高,你一般如何处理
以上步骤可以帮助你处理服务器遭受攻击的情况,但具体的方法可能会根据你的网络环境和攻击类型有所不同。
73 2
|
6月前
|
监控 安全 网络安全
|
5月前
|
负载均衡 网络协议 安全
|
6月前
|
SQL 安全 网络安全
美国高防云服务器能防御哪些攻击? - 蓝易云
高防云服务器通常具有一定的防御能力,可以帮助抵御这些攻击。然而,防御的效果也取决于服务器的配置和管理,以及应用程序的安全性。
96 0
|
6月前
|
Linux 网络安全 Windows
如何通过隐藏服务器真实IP来防御DDOS攻击
如何通过隐藏服务器真实IP来防御DDOS攻击