分类 阿里云 下的文章

阿里云负载均衡访问控制(黑名单)自动添加IP的方法

前文写了一个添加ip的python脚本,https://www.willnet.net/index.php/archives/104/
现在做一个自动添加方案,以阿里云日志服务收集nginx日志为例,目的是自动屏蔽每15分钟请求超过2500次的IP地址
1,阿里云日志服务新建搜索

* | select remote_addr,count(*)  as count group by remote_addr order by count desc limit 1

保存上面的搜索为快速查询
2,配置nginx新站点,反代8088端口,配置日志输出为
nginx.conf

log_format log-alarm-access '$request_body '

example.com.conf

server {
listen 80;
server_name example.com;
index index.html index.htm index.php;
  if ($http_x_forwarded_proto = "http") {
    return 307 https://$host$request_uri;
  }


location /requestoverlimit {
  proxy_pass         http://localhost:8088;
  proxy_redirect     off;
  proxy_set_header   Host              $host;
  proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
  proxy_set_header   X-Forwarded-Proto $scheme;
  access_log /var/log/nginx/example.com.access.log log-alarm-access;
}
}

3,新建python脚本
server.py

#!/usr/bin/env python
"""
Very simple HTTP server in python.
Usage::
    ./dummy-web-server.py [<port>]
Send a GET request::
    curl http://localhost
Send a HEAD request::
    curl -I http://localhost
Send a POST request::
    curl -d "foo=bar&bin=baz" http://localhost
"""
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write("<html><body><h1>hi!</h1></body></html>")

    def do_HEAD(self):
        self._set_headers()
        
    def do_POST(self):
        # Doesn't do anything with posted data
        self._set_headers()
        self.wfile.write("OK")
        
def run(server_class=HTTPServer, handler_class=S, port=8088):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting httpd...'
    httpd.serve_forever()

if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

4,启动python server.py,并添加服务器启动命令到rc.local开机启动
5,阿里云日志服务把1里面保存的快速查询另存为告警,webhook地址填上面新建的网址,如图
另存为告警
6,新建定时任务,每五分钟执行

*/5 * * * *  tail -n 1 /var/log/nginx/example.com.access.log|awk -F ":" '{print $9}'|awk -F "]" '{print $1}'|xargs python /root/aliyun/scripts/addaclentry.py >> /var/log/autoaddblacklist/autoaddblacklist.log 2>&1 

7,查看访问控制黑名单列表

ps:一键脚本,对比上一次IP地址是否已经添加到黑名单

#! /bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

function sameip(){
        lastip=$(cat /root/aliyun/server/lastip.txt)
        currentip=$(tail -n 1 /var/log/nginx/example.com.access.log|awk -F ":" '{print $12}'|awk -F "]" '{print $1}')
        if [ "$currentip"x != "$lastip"x ];then
                echo $currentip >/root/aliyun/server/lastip.txt
                cat /root/aliyun/server/lastip.txt|xargs python /root/aliyun/scripts/addaclentry.py >> /var/log/autoaddblacklist/autoaddblacklist.log 2>&1
        else
                date "+%Y-%m-%d %H:%M:%S" >> /var/log/autoaddblacklist/autoaddblacklist.log && echo "same ip address" >> /var/log/autoaddblacklist/autoaddblacklist.log
        fi
}

sameip

crontab定时,每分钟执行一次

* * * * * /root/aliyun/scripts/sameip.sh

阿里云负载均衡访问控制(黑名单)添加IP的脚本

python写的阿里云负载均衡访问控制添加IP的脚本,配合日志或报警执行自动添加ip。
需要先安装阿里云sdk

pip install aliyun-python-sdk-core
pip install aliyun-python-sdk-slb

addaclentry.py

#!/usr/bin/env python
#coding=utf-8

import sys
import json
from aliyunsdkcore import client
from aliyunsdkslb.request.v20140515 import AddAccessControlListEntryRequest
from aliyunsdkslb.request.v20140515 import DescribeAccessControlListAttributeRequest

clt = client.AcsClient('AccessKeyId','secret','cn-beijing')


AclEntryIP = [{u'entry': u'', u'comment': u''}]

AclEntryIP[0]["entry"] = sys.argv[1]+'/32'

AclEntryIP = json.dumps(AclEntryIP)

request = AddAccessControlListEntryRequest.AddAccessControlListEntryRequest()
request.set_accept_format('json')

request.add_query_param('RegionId', 'cn-beijing')
request.add_query_param('AclEntrys', AclEntryIP)
request.add_query_param('AclId', 'acl-fdsafdsafdsafdsaf')


## 发起请求
response = clt.do_action_with_exception(request)


# 查询
## 设置参数
request = DescribeAccessControlListAttributeRequest.DescribeAccessControlListAttributeRequest()
request.set_accept_format('json')

request.add_query_param('RegionId', 'cn-beijing')
request.add_query_param('AclId', 'acl-fdsafdsafdsafdsaf')

## 发起请求
response = clt.do_action_with_exception(request)

## 输出结果
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print "黑名单列表:", response, '\n'

使用方法

python addaclentry.py 8.8.8.8

阿里云国际新加坡试用

去年阿里云国际香港促销,一直偷懒没有测试,注册了没绑定paypal。。。
前几天看别人买了据说还不错,周末也花10刀买了测试一下。<br/>

阿里云国际比国内多一种销售方式,打包出售,把最低配ecs和流量包一起打包,但是ecs网络带宽会限制在30m,流量包2t,流量包是地域共享的,就是同一个地方开多台机器公用流量包,所以再开一个按流量计费的200m带宽的ecs就可以使用这2t的流量,就是多花一个月esc的钱,比如新加坡的是套餐10刀,按流量计费esc12.61刀,总计22.61刀,约人民币150使用200m带宽的2t流量和两台ecs,如果能跑满还是挺划算的,相比之下香港就是19+12.61刀,约人民币220元。<br/>

联通连接阿里云新加坡走的是sigtel新加坡电信,电信走的是cn2,我测试联通是能跑满的,但是突发流量有点慢,youtube4k缓冲几秒可以看,比google cloud没改路由的时候慢一点。<br/>

阿里云异常登录问题排查记录

阿里云ecs使用的是ubuntu14.04系统,收到阿里云短信提醒,有异地ip登录可能被黑客攻击。登录阿里云云盾查看登录ip登录时间和登录名为git,基本确定如果出问题的话应该是gitlab的锅
首先,用自己的账号登录服务器,可以登录说明没有被大范围破坏。
然后查看/var/log/auth.log,发现登录ip和登录时间与阿里云提醒短信相符,而且log并没有被删除或修改。
在auth.log文件中
Apr 15 22:42:57 servername sshd[14983]: Accepted publickey for git from 60.10.71.xx port 7207 ssh2: RSA 15:07:f5:20:8e:40:ba:d5:60:92:6b:b7:b2:xx:xx:xx
Apr 15 22:42:57 servername sshd[14983]: pam_unix(sshd:session): session opened for user git by (uid=0)
Apr 15 22:42:57 servername sshd[15002]: Received disconnect from 60.10.71.xx: 11: disconnected by user
Apr 15 22:42:57 servername sshd[14983]: pam_unix(sshd:session): session closed for user git
通过搜索rsa指纹发现在工作时间有此指纹的机器通过办公网络ip登录,由此基本可以确定“黑手”来自内部。
然后就是通过rsa指纹找到这只“黑手”,通过在每台工作电脑上执行ssh-keygen -l -E md5 -f ~/.ssh/id_rsa.pub,查看pubkey的指纹是不现实的的
想到gitlab保存了所有用户的公钥,通过搜索找到gitlab公钥存放位置,默认/var/opt/gitlab/.ssh/authorized_keys
打开文件将每个人的公钥复制出来保存为文件,执行ssh-keygen -l -E md5 -f [filepath]生成每个文件的指纹,对比日志中异常登录的指纹
最终确定“黑手”是谁,通过询问“黑手”得知相同时间通过自家宽带通网络push过代码,警报解除。

ps:由于像宽带通、鹏博士这些二级运营商的宽带对出口ip做了nat,使用周边省市的出口ip以减少成本,所以远程主机记录的登录ip会不准确,可以通过ip查询网站查询此ip属于哪个运营商,或者百度ip应该也有些收获
pps:阿里云的云盾防攻击保护确实有些作用,但是有些时候也有些夸大威胁,来推销自己安全防护服务的目的

阿里云坑啊!记dnsmasq安装配置

需要在阿里云vpc里配置一台dns服务器,使用dnsmasq,安装一切妥当,按照文章配置内网服务器域名,一切看起来都挺顺。
就在dig baidu.com的时候出了问题。居然没有answer section,而内网服务器一切正常。
谷歌,百度各种文章,发工单问是不是阿里云做了什么限制,均无果。
最后在某篇文章启发下去找日志,默认是不开日志的,日志的位置也很诡异,在syslog里。
通过日志发现,dnsmasq没有使用我配置的源dns服务器,通过ps -ef | grep dns看到dnsmasq默认使用文件/var/run/dnsmasq/resolv.conf作为上游名字服务列表文件,然而这个文件是空的,dnsmasq在没有源dns时返回refuse
即dig里没有answer section。
其实也是我没自习看dig的返回信息,看到status:refuse解决这个问题就会少走很多弯路。
知道问题所在就好办了,直接修改这个/var/run/dnsmasq/resolv.conf可以,修改默认环境变量屏蔽这个文件也可以。
在这说说我猜这个坑的由来,其实我在其他vps上试是没有问题的,同样的ubuntu14.04,同样的版本,同样的大小,效果就不同
/var/run/dnsmasq/resolv.conf这个文件其实是桌面版ubuntu的network-manager使用的,可是阿里云都应该是服务器版啊
是阿里云镜像有问题,还是偷懒把桌面源给了服务器,不得而知,可以预计同样的坑还会有不少,以后多加小心。