diff --git a/chaos-rop/README.md b/chaos-rop/README.md new file mode 100644 index 0000000..8a7ba6e --- /dev/null +++ b/chaos-rop/README.md @@ -0,0 +1,11 @@ +# ROP +### 描述: +* GeruzoniAnsasu给他的学弟讲解了一下rop是什么之后,学弟问到,程序代码全都写成rop的形式会是什么样?答:混沌邪恶。 +* 基本上主要操作都是push push push ret 完成的……输入正确的key之后会依次跳到几个加解密的代码段,跳的地址跟上一段加解密结果有关,最后跳到正确的地址后会将flagiswhatthefuck?改为flagiswhatyouwant + + +* 这里的代码是批量出的某个版本。。而且源码部分已经部分打乱了,最初的顺序写的代码不知道被我改了什么东西编译不了了orz将就吧,反正哪个版本都看不懂的 + +* sample10是我自己尝试逆的另一个版本,到第二个跳rbx的地方发现不给提示没法猜原数据……orz好吧我承认这个东西确实就是写来让人做不了的,不过本意并不是逻辑意义上的做不了 + * `[*][c][t][f][_][f][+][+][+][+]`打*号的位是不固定的(不过也没人发现)打+号的位置不影响跳转地址,但会因aesenc加密后不符导致最后不会显示flag正确的提示,如果真要逆这几位的话……别想了不可能逆得了的 +* 程序总共有5段aesenc顺序和数据全对才能提示正确。。gg,没法做 diff --git a/chaos-rop/callee.c b/chaos-rop/callee.c new file mode 100644 index 0000000..8e10730 --- /dev/null +++ b/chaos-rop/callee.c @@ -0,0 +1,135 @@ +//callee.c +#include +#include +#include +#include +#include +#include +#include + +ssize_t read(int fd, void *buf, size_t count); +ssize_t write(int fd, const void *buf, size_t count); +extern char * _extern; +extern char* _extern_end; +char flgsz[128] = {"\nflag:hctf{Ye4h_u_g0"}; +char fakesz[128] = {"什么的……当然是假的啦!"}; + +//tmp +extern char * FAKE_J1; +extern char * FAKE_J2; +extern char * FAKE_J3; +extern char * FAKE_J4; +extern char * FAKE_J5; +extern char * FAKE_J6; +extern char * FAKE_J7; +extern char * FAKE_J8; +extern char * FAKE_J9; +extern char * FAKE_J10; +extern char * FAKE_J11; +extern char * FAKE_J12; + +void XOR(char *s1,char *s2,unsigned int len) +{ + unsigned int i=0; + for(i=0;iselect jmp pos + +_ss: + s1 db "Hello :)",0xa,0x0 + s2 db "菊苣们好·-·",0xa,0x0 + s3 db "皆さんごきげんようovo",0xa,0x0 + s4 db "안녕하세요:)",0x0a,0x0 + len equ $ - s1 +_realstart: + xor rdi,rdi + inc rdi + dec r14;clear jmp table flag + push rdi + push s4+3 + push len + push POP_RDX + push s1 + push POP_RSI + ret + db 0xeb +_c1:; first time to call write + ;sub rsp 8 + call [ext_write] + push s4+3 + push 1 + push POP_R15 + ret + db 0xeb +_out3: + push _out4 + push vMagicStr + push POP_RCX + push ADD_RAX_RCX + push MOV_SELF_RAX + push vMagicStr + push POP_RAX + push rax + push POP_RCX + ret + db 0xeb +_EXIT: + pop rax + xor rbx,rbx + int 0x80 +_read_input: + cmp r14,1 + jz l1;from jmp table r14 should be 1 +buff_all: + times 1023 db 0x0;can be anything,but size is 256 + db 0 +l1:;read input to buffall + dec r14 + push l2;continue to l2 + push qword[ext_read] + push 0 + push POP_RDI + push buff_all + push POP_RSI + push 1024 + push POP_RDX + ret + FAKE_J2: + db 0xeb +JMP_RAX: + jmp rax + ret +FAKE_J3: + db 0xeb +SUB_RAX_16: + sub rax,16 + ret +l2: + ;rsi --> buff + push MOV_SELF_RAX + push rsi + inc rsi + push POP_RAX + push 3 + push CALL_HELPER9 + call [rsp] +entry1: + add r15,1;read_input / entry1_c + jmp s4+3 +;call return to here +hhh: + mov rbx,entry1 + mov rcx,0x3732363034393931;19940627 + mov rdx,0x62d762d762d762d7 + xor rax,rcx + shr rax,5 + xor rax,rdx + movzx r12,al ; r12 --> times of sections --> 5 + shr rax,8 +l4:;main loop + inc rsi; point to secion data start + cmp r12,0 + jg l3 +;here out +_out: + push _out1 + push MOV_SELF_RAX + push buff1 + push POP_RAX + ret + db 0xeb +l3: + dec r12 + movzx r13,al; r13 --> len of section -->8 for first + test r14,r14 + jz l5 + align 128 +buff1: + times 0xff db 0xcc +FAKE_J5: + db 0xeb +POP_RDI: + pop rdi + ret +_out1: + push _out2 + push rax + push POP_RCX + ret +FAKE_J6: + db 0xeb +POP_RSI: + pop rsi + ret +l6: + inc r15 + call rbx + push l4; jmp l4 + push MOV_SELF_RAX + push rsi; this rsi must be original + push POP_RAX + ret + FAKE_J7: + db 0xeb +POP_RDX: + pop rdx + ret +FAKE_J8: + db 0xeb +POP_RCX: + pop rcx + ret +l8: + mov ebx,eax + ;call rcx ;go out --> entry2 + pop rsi + push _sub + push rsi; rsi --> beg of buff_all + push POP_RAX + push (l1-1);rdi --> endof buff_all + push POP_RDI + ret + showstr db "fl" + db "agiswhat" + vMagicStr db "thefuck?",0 ; thefuck? --> youinput +FAKE_J9: + db 0xeb +POP_R15: + pop r15 + ret +FAKE_J10: + db 0xeb +ADD_RSI_R13: + add rsi,r13 + ret +l5: +;copy data to buff1 + push l6 + push ADD_RSI_R13 + push qword[ext_memcpy];memcpy(buff1,rsi,r13_len) + push r13 + push POP_RDX + push buff1 + push POP_RDI + ret + FAKE_J4: + db 0xeb +POP_RAX: + pop rax + ret +;entry1: +; add r15,1;read_input / entry1_c +; jmp s4+3 +entry1_c: + dec r14 + push rsi ;save rsi + push l7 + push qword[ext_XOR] + push buff1 + push POP_RDI + push $-3;self locating || may be entry2? + push POP_RSI + push r13 + push POP_RDX + ret +FAKE_J11: + db 0xeb +ADD_RAX_RCX: + add rax,rcx + ret +FAKE_J12: + db 0xeb +XOR_RAX_RCX: + xor rax,rcx + ret +entry2_c: + dec r14 + movaps xmm2,[rdi];save part1 + ;AESENC xmm1,xmm2;buff1 + movzx rcx, byte[buff1] + lea rcx, [rcx*8] ; must be 4*8 + push l9 + push MOV_SELF_RAX + push ADD_RAX_RCX + ret + db 0xeb +sj5: + xor r15, r15 + jmp entry3 +POP_RBX: + pop rbx + ret +l7: + movaps xmm1,[buff1] ;AES KEY 0x3f6709877f3f661c + ;AESENC xmm1,xmm2 + ;inc r15;r15=1+2 --> entry2 --> entry2_c + push l8 + push XOR_RAX_RCX + push MOV_SELF_RAX + push buff1 + push POP_RAX + ;magic equ (0x3f6709877f3f661c)^(entry2-$$) + ;%assign magic $^FAKE_J1 + push vMagic1 ; entry2 --> entry2_c = entry2 ^ 0x7f3f661c + ;push $$ + push POP_RCX + ret + db 0xeb +_out2: + mov rax,vFinalL + xor rax,rcx + test rax,rax + jnz _EXIT;wrong,can't see any change + mov rcx,vFinalH + push _out3 + push XOR_RAX_RCX + push MOV_SELF_RAX + push buff1+8 + push POP_RAX + ret + db 0xeb +entry2: + add r15,2 + jmp s4+3 +_sub: + sub byte[rax], 0x30 + inc rax + cmp rdi,rax + jne _sub + ret + db 0xeb +sj4: + xor r15, r15 + jmp entry2_c +l10: + mov ebx,eax + ret + db 0xe8 +entry4: + movaps xmm3,[rdi];save part3 + AESENC xmm1,xmm0 + ;AESENC xmm1,xmm3 + pxor xmm0,xmm2 + pxor xmm0,xmm3 + pxor xmm0,[rdi+128] + movaps [rdi],xmm0 + push l10 + push XOR_RAX_RCX + push vMagic2;magic2 --> entry5 + push POP_RCX + push MOV_SELF_RAX + push rdi + push POP_RAX + ret + db 0xeb +sj3: + xor r15, r15 + jmp entry1_c +sj1: + xor r15, r15 + jmp _c1 +JMPTABLE: + dq sj1 + dq sj2 + dq sj3 + dq sj4 + dq sj5 +entry5: + AESENC xmm1,xmm3 + AESENC xmm1,[rdi] + movaps [rdi],xmm1 + ret +l9: + push buff1 + push POP_RDI + push rax + push POP_RBX + ret + db 0xeb +sj2: + xor r15, r15 + jmp _read_input + db 0xeb +_out4: + mov [rcx],rax + push _EXIT + push qword[ext_puts] + push showstr + push POP_RDI + ret diff --git a/chaos-rop/rop.o b/chaos-rop/rop.o new file mode 100644 index 0000000..33366ff Binary files /dev/null and b/chaos-rop/rop.o differ diff --git a/chaos-rop/sample10 b/chaos-rop/sample10 new file mode 100755 index 0000000..50e1c81 Binary files /dev/null and b/chaos-rop/sample10 differ diff --git a/chaos-rop/sample10.i64 b/chaos-rop/sample10.i64 new file mode 100755 index 0000000..6d39610 Binary files /dev/null and b/chaos-rop/sample10.i64 differ diff --git a/chaos-rop/test b/chaos-rop/test new file mode 100755 index 0000000..68954e2 Binary files /dev/null and b/chaos-rop/test differ diff --git a/misc-shortbin/README.md b/misc-shortbin/README.md new file mode 100644 index 0000000..0d15939 --- /dev/null +++ b/misc-shortbin/README.md @@ -0,0 +1,6 @@ +# misc-shortbin(shortcode) +### 描述: + * GeruzoniAnsasu这么长id的人实际上是个非常懒的programer... + +读入发过来的消息,存成文件然后尝试执行,根据回答决定下一步 +> http://drops.hduisa.cn/archives/161/ diff --git a/misc-shortbin/misc-shortbin.py b/misc-shortbin/misc-shortbin.py new file mode 100644 index 0000000..7a78f4c --- /dev/null +++ b/misc-shortbin/misc-shortbin.py @@ -0,0 +1,108 @@ +#!/usr/bin/python +#coding:utf-8 + +import SocketServer +#from zio import * +import string +import os +from hashlib import md5 +import subprocess + +class MyServer(SocketServer.ThreadingTCPServer,object): + allow_reuse_address = True + +class MyHandler(SocketServer.StreamRequestHandler): + def handle(self): + print 'get connection from',self.client_address + self.request.settimeout(10) + self.wfile.write('TOKEN=') + self.token = self.rfile.readline().strip() + print 'TOKEN='+self.token + if '' == self.token: + self.wfile.write('\n\nwrong token\n') + return + print 'serving team {'+self.token+'} from ',self.client_address + + self.wfile.write('\nProgrammers are alwas trying to write shorter code, \ +so that they can finish their work earlier and enjoy a cup of java.\n') + self.rfile.readline() + self.wfile.write('Since I am a very lazy programmer, a typical "Hello world" program wrote by me usually has only 56 bytes.\n') + self.rfile.readline() + self.wfile.write("But I think that's enough. There has been a lot of things can be done, within 60 bytes.\n") + self.rfile.readline() + self.wfile.write('We are all programmers. Do you agree with me?\n') + rpl = self.rfile.readline().strip() + if rpl.lower().find('no') >= 0: + self.wfile.write('Ah... what a pitty:(\n') + return + elif rpl.lower().find('yes') >= 0: + self.wfile.write("Hmm.. I'm happy to hear that:) But I must test your honesty.\n") + self.rfile.readline() + self.wfile.write("I will ask you some questions, please answer them in our PROGRAMmer WAY:)\n") + self.wfile.write('Remember that famous word? Talk is cheap, show me the CODE :)\n\n') + self.wfile.write('***Hey your codes never compiled? <<<-I AM THE LAST HINT.\n\n') + + QnA = (('Q1:Do you enjoy tea or coffee?','coffee'),('Q2:Do you like hacking things?','yes'),('Q3:Will you hack me?','no')) + rply = {\ + 'coffee':\ + ("Haha nice:)\n",\ + "Hey don't you like java? There is nothing worth talking with you:( BYE\n"),\ + 'yes':\ + ('Great! We are the same:)\n',\ + "Are you really a hacker? Why do you come here?\n"),\ + 'no':\ + (':) Alright, give you the flag:', + 'FxxK YOU!\n')} + LEN_LIMIT = 60 + for i,t in enumerate(QnA): + q,a = t + self.wfile.write(q+'\n') + d = self.request.recv(200) + print '-'*30+'\n{}\n'.format(repr(d))+'-'*30+'\n'*2 + if len(d) > LEN_LIMIT: + self.wfile.write('Wow too long!\n') + return + if d.find('ELF')<0 or d.find('main')>=0 : + self.wfile.write('Huh..?Are your sure you understood me?\n') + return + h = md5(d).hexdigest(); + print h + with open('/tmp/'+h,'wb') as f: + f.write(d) + os.system('chmod 777 /tmp/'+h) + #io = zio('/tmp/'+h,timeout = 0.1) + pp = subprocess.Popen('/tmp/'+h,stdout=subprocess.PIPE) + pp.wait() + ans = pp.stdout.read().strip('\x00 \n') + pp.stdout.close() + #ans = '' + #try: + # ans = io.read(100).strip('\0 \n\t')[:len(a)] + #except EOF: + # pass + #except TIMEOUT: + # pass + os.system('pkill -9 '+h) + os.system('rm -f /tmp/'+h) + print '**{}----------{}**'.format(str(list(a)),str(list(ans))) + print cmp(ans ,a.strip()) + if ans != a.strip(): + self.wfile.write(rply[a][1]) + break + else: + if i < 2: + self.wfile.write(rply[a][0]+"\n...Oh lazy me... This time can you give me shorter answer?\n\n") + LEN_LIMIT -= 4 + else: + self.wfile.write('here you got the flag, but i removed some code from original file.\n') + print 'team {%s} got the flag.' % self.token + else: + self.wfile.write(':( You are not listening.\n') + + + +if __name__ == "__main__": + host = '0.0.0.0' + port = 9999 + s = MyServer((host, port), MyHandler) + s.serve_forever() diff --git a/misc-shortbin/test0 b/misc-shortbin/test0 new file mode 100755 index 0000000..c9cfa92 Binary files /dev/null and b/misc-shortbin/test0 differ diff --git a/misc-shortbin/test1 b/misc-shortbin/test1 new file mode 100755 index 0000000..83f37e2 Binary files /dev/null and b/misc-shortbin/test1 differ diff --git a/picmatching/CMakeLists.txt b/picmatching/CMakeLists.txt new file mode 100644 index 0000000..3dcae69 --- /dev/null +++ b/picmatching/CMakeLists.txt @@ -0,0 +1,21 @@ +cmake_minimum_required(VERSION 2.8) + +SET(CMAKE_BUILD_TYPE Release CACHE STRING "set build type to release") +SET(CMAKE_INSTALL_PREFIX /tmp CACHE STRING "install prefix") +add_definitions(-std=c++11) +remove_definitions(-g) +project( picmatch ) + +SET(Boost_USE_STATIC_LIBS TRUE) +SET(Boost_USE_MULTITHREADED TRUE) +SET(Boost_USE_STATIC_RUNTIME TRUE) + +SET(OpenCV_DIR /opt/opencv/share/OpenCV) +find_package(Boost REQUIRED serialization iostreams ) +find_package(OpenCV REQUIRED ) + +include_directories(${Boost_INCLUDE_DIR} ${OpenCV_INCLUDE_DIRS} ) +add_executable(picmatch archiverhelper.cpp picmatch.cpp) +target_link_libraries( picmatch ${Boost_LIBRARIES} ${OpenCV_LIBS} ) + +add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND objcopy -N -S -R .comment -R .jcr ${PROJECT_NAME}) diff --git a/picmatching/README.md b/picmatching/README.md new file mode 100644 index 0000000..83c47c2 --- /dev/null +++ b/picmatching/README.md @@ -0,0 +1,16 @@ +## Picture Matching + +拿到源码你们也编译不了=。= + +opencv的demo,拿来玩玩就好,想逆……别太当真了,好几m呢光opencv和boost的封装就看吐你,而且源码里在干嘛你看懂了吗,那不就是了…… + +程序其实有3个选项,见源码,你可以试试找张图片detect下来keypoints然后把这图旋转缩放一下再match,图像最好大一点复杂一点 + +根据特征点来分析图像特征什么的……哈哈哈哈哈 + +题目给了本体和detect出来的特征点,这题我觉得找到test选项,把test那个drawimage的参数改成default然后对照着特征点的位置试试是什么字母,手动画出图后再用match选项比对一下画的图可能还比rop容易,毕竟这两个matching算法就是用来匹配图像在变换/扭曲/模糊之后的结果的 不过这样的话……算是什么类型的题呢 + +------- + + + diff --git a/picmatching/archiverhelper.cpp b/picmatching/archiverhelper.cpp new file mode 100644 index 0000000..9e20320 --- /dev/null +++ b/picmatching/archiverhelper.cpp @@ -0,0 +1,2 @@ +#include "archiverhelper.h" + diff --git a/picmatching/archiverhelper.h b/picmatching/archiverhelper.h new file mode 100644 index 0000000..9f044b5 --- /dev/null +++ b/picmatching/archiverhelper.h @@ -0,0 +1,89 @@ +#ifndef ARCHIVERHELPER_H +#define ARCHIVERHELPER_H + +#include +#include "opencv2/core.hpp" +using std::vector; + +template +class ArchiveHelper +{ + +public: + ArchiveHelper(T & any):mVector(any) + { + + } + + operator T &() + { + return mVector; + } +private: + T & mVector; + friend class boost::serialization::access; + template + void serialize(Archive & ar, const unsigned int version) + { + ar & mVector; + } + +}; +BOOST_SERIALIZATION_SPLIT_FREE(cv::Mat) +namespace boost { +namespace serialization { + +template +void serialize(Archive & ar, cv::KeyPoint & keypoint, const unsigned int version) +{ + ar & keypoint.class_id; + ar & keypoint.angle; + ar & keypoint.octave; + ar & keypoint.pt; + ar & keypoint.response; + ar & keypoint.size; +} +template +void serialize(Archive & ar, cv::Point_<_Tp> & p, const unsigned int version) +{ + ar & p.x; + ar & p.y; +} +/** Serialization support for cv::Mat */ +template +void save(Archive & ar, const cv::Mat & m, const unsigned int version) +{ + size_t elem_size = m.elemSize(); + size_t elem_type = m.type(); + + ar & m.cols; + ar & m.rows; + ar & elem_size; + ar & elem_type; + + const size_t data_size = m.cols * m.rows * elem_size; + ar & boost::serialization::make_array(m.ptr(), data_size); +} + +/** Serialization support for cv::Mat */ +template +void load(Archive & ar, cv::Mat & m, const unsigned int version) +{ + int cols, rows; + size_t elem_size, elem_type; + + ar & cols; + ar & rows; + ar & elem_size; + ar & elem_type; + + m.create(rows, cols, elem_type); + + size_t data_size = m.cols * m.rows * elem_size; + ar & boost::serialization::make_array(m.ptr(), data_size); +} + +} // namespace serialization +} // namespace boost + +#endif // ARCHIVERHELPER_H diff --git a/picmatching/generate.py b/picmatching/generate.py new file mode 100644 index 0000000..92df629 --- /dev/null +++ b/picmatching/generate.py @@ -0,0 +1,32 @@ +#!/usr/bin/python +#encoding:utf-8 +import Image as IM +import ImageDraw as IMDW +import ImageFont as IMF +from time import time,sleep +from random import random,seed +import sys +import json +ss = 'ABEFGHJKMNRSTVWXYZabdefghjmnpqrstu23456789' +w = 430 +h = 130 +seed(time()) +for j in xrange(int(sys.argv[1])): + rs = '' + r = int(random()*100)%14-7 + for i in range(5): + rs += ss[int(random()*100)%len(ss)] + seed(time()*random()) + img = IM.new('RGB',(w,h)) + ft = IMF.truetype('msyh.ttc',80+r) + dw = IMDW.Draw(img) + dw.text((5,0),rs,font=ft,fill=(255,255,255)) + seed(random()*time()) + rr = int(random()*1000)%160/10.0 - 8 #+ (int(random()*10)%2)*180 + rx = int(random()*100)%30 + ry = int(random()*100)%20 + fn = ''.join(rs.split(' ')) + print fn + img.offset(rx,ry+8).rotate(rr,IM.BICUBIC).point(lambda p:(255-p)).save('/tmp/pic/{}.png'.format(fn)) + import os + os.system('./picmatch detect /tmp/pic/{0}.png /tmp/pic/kp/kpsample{1}'.format(fn,str(j))) diff --git a/picmatching/picmatch b/picmatching/picmatch new file mode 100755 index 0000000..cfde501 Binary files /dev/null and b/picmatching/picmatch differ diff --git a/picmatching/picmatch.cpp b/picmatching/picmatch.cpp new file mode 100644 index 0000000..efd1ec2 --- /dev/null +++ b/picmatching/picmatch.cpp @@ -0,0 +1,218 @@ +#include +#include +#include + +#include +#include +#include +#include + +#include "opencv2/core.hpp" +#include "opencv2/xfeatures2d.hpp" +#include "opencv2/highgui.hpp" +#include "archiverhelper.h" + +#define minHessian 400 +#define siftPoints 0 + +using namespace std; +using namespace cv; +using namespace cv::xfeatures2d; + +using namespace boost; +using namespace boost::archive; + + +void readme(); +/* @function main */ + +int main( int argc, char** argv ) +{ + if( argc != 4 ) + { readme(); return -1; } + namespace io = boost::iostreams; + if(strncmp(argv[1],"detect",6)==0) + { + const char* fname_pic = argv[2]; + const char* fname_kps = argv[3]; + Mat img = imread(fname_pic,IMREAD_GRAYSCALE); + if(!img.data) + { + cout<< "Error reading images!" << std::endl; + return -1; + } + Ptr sift_detector = SIFT::create(siftPoints); + Ptr surf_detector = SURF::create(minHessian); + vector surf_keypoints,sift_keypoints; + Mat sift_descriptors,surf_descriptors; + sift_detector->detectAndCompute(img, Mat(),sift_keypoints, sift_descriptors); + surf_detector->detectAndCompute(img, Mat(),surf_keypoints, surf_descriptors); + + ofstream ofs(fname_kps,ios_base::binary); + { + io::filtering_streambuf out; + out.push(io::zlib_compressor(io::zlib::best_compression)); + out.push(ofs); + binary_oarchive oa(out); + ArchiveHelper > sift_archiver(sift_keypoints); + ArchiveHelper > surf_archiver(surf_keypoints); + ArchiveHelper ar1(sift_descriptors); + ArchiveHelper ar2(surf_descriptors); + oa << sift_archiver; + oa << surf_archiver; + oa << ar1; + oa< isift_keypoints,isurf_keypoints,psift_keypoints,psurf_keypoints; + Mat isift_descriptors,isurf_descriptors; + + ifstream ifs(fname_kps,ios_base::binary); + { + io::filtering_streambuf in; + in.push(iostreams::zlib_decompressor()); + in.push(ifs); + binary_iarchive ia(in); + ArchiveHelper > sift_archiver(isift_keypoints),surf_archiver(isurf_keypoints); + ArchiveHelper ar1(isift_descriptors),ar2(isurf_descriptors); + + ia>>sift_archiver; + ia>>surf_archiver; + ia>>ar1; + ia>>ar2; + } + ifs.close(); + Mat img = imread(fname_pic,IMREAD_GRAYSCALE); + Ptr sift_detector = SIFT::create(siftPoints); + Ptr surf_detector = SURF::create(minHessian); + Mat psift_descriptors, psurf_descriptors; + + sift_detector->detectAndCompute(img, Mat(),psift_keypoints, psift_descriptors); + surf_detector->detectAndCompute(img, Mat(),psurf_keypoints, psurf_descriptors); + + BFMatcher matcher; + vector< DMatch > sift_matches,surf_matches; + vector > sift_knnMatches,surf_knnMatches; + matcher.knnMatch(psift_descriptors,isift_descriptors,sift_knnMatches,2); + matcher.knnMatch(psurf_descriptors,isurf_descriptors,surf_knnMatches,2); + + for( size_t i = 0; i < sift_knnMatches.size(); i++ ) + { + const DMatch& bestMatch = sift_knnMatches[i][0]; + const DMatch& betterMatch1 = sift_knnMatches[i][1]; + float distanceRatio = bestMatch.distance / betterMatch1.distance; + if(distanceRatio<0.61) + { + sift_matches.push_back(bestMatch); + } + } + for( size_t i = 0; i < surf_knnMatches.size(); i++ ) + { + const DMatch& bestMatch = surf_knnMatches[i][0]; + const DMatch& betterMatch1 = surf_knnMatches[i][1]; + float distanceRatio = bestMatch.distance/betterMatch1.distance; + if(distanceRatio<0.65) + { + surf_matches.push_back(bestMatch); + } + } + printf("-- SIFT KNN Matching rate:%f\n",sift_matches.size()/(0.0+psift_keypoints.size())); + printf("-- SURF KNN Matching rate:%f\n\n",surf_matches.size()/(0.0+psurf_keypoints.size())); + //-- Quick calculation of max and min distances between keypoints + double mx_sift_dist = 0; double mn_sift_dist = 999; + double mx_surf_dist = 0; double mn_surf_dist = 999; + for( size_t i = 0; i < sift_matches.size(); i++ ) + { + double dist = sift_matches[i].distance; + if( dist < mn_sift_dist ) mn_sift_dist = dist; + if( dist > mx_sift_dist ) mx_sift_dist = dist; + } + for( size_t i = 0; i < surf_matches.size(); i++ ) + { + double dist = surf_matches[i].distance; + if( dist < mn_surf_dist ) mn_surf_dist = dist; + if( dist > mx_surf_dist ) mx_surf_dist = dist; + } + + std::vector< DMatch > final_sift_matches,final_surf_matches; + + for( size_t i = 0; i < sift_matches.size(); i++ ) + { + if( sift_matches[i].distance <= max(1.8*mn_sift_dist+1,90.0)) + { + final_sift_matches.push_back(sift_matches[i]); + } + } + for( size_t i = 0; i < surf_matches.size(); i++ ) + { + if( surf_matches[i].distance <= max(1.8*mn_surf_dist+0.0016,0.16)) + { + final_surf_matches.push_back(surf_matches[i]); + } + } + + printf("-- SIFT Max dist: %f \n", mx_sift_dist); + printf("-- SIFT Min dist: %f \n", mn_sift_dist); + printf("-- SIFT Total matches: %d, good matches: %d\n",sift_matches.size(),final_sift_matches.size()); + printf("-- SIFT Matching rate: %f\n\n",(final_sift_matches.size()+0.0) / sift_matches.size()); + + printf("-- SURF Max dist: %f \n", mx_surf_dist); + printf("-- SURF Min dist: %f \n", mn_surf_dist); + printf("-- SURF Total matches: %d, good matches: %d\n",surf_matches.size(),final_surf_matches.size()); + printf("-- SURF Matching rate: %f\n\n",(final_surf_matches.size()+0.0) / surf_matches.size()); + + Mat img_white(img.rows,img.cols,CV_8UC3,cv::Scalar(255,255,255)); + Mat img_matches1,img_matches2; + drawMatches(img,psift_keypoints,img_white,isift_keypoints,final_sift_matches,img_matches1); + //-- Show detected matches + namedWindow("SIFT Matches",WINDOW_FREERATIO|WINDOW_NORMAL); + imshow( "SIFT Matches", img_matches1 ); + + drawMatches(img,psurf_keypoints,img_white,isurf_keypoints,final_surf_matches,img_matches2); + //-- Show detected matches + namedWindow("SURF Matches",WINDOW_FREERATIO|WINDOW_NORMAL); + imshow( "SURF Matches", img_matches2 ); + } + else if(strncmp(argv[1],"test",4)==0) + { + vector sift_keypoints,surf_keypoints; + ifstream ifs(argv[3],ios_base::binary); + { + io::filtering_streambuf in; + in.push(iostreams::zlib_decompressor()); + in.push(ifs); + binary_iarchive ia(in); + ArchiveHelper > sift_archiver(sift_keypoints),surf_archiver(surf_keypoints); + ia>>sift_archiver; + ia>>surf_archiver; + } + ifs.close(); + printf("-- SIFT key points:%d\n",sift_keypoints.size()); + printf("-- SURF key points:%d\n",surf_keypoints.size()); + + Mat img = imread(argv[2],IMREAD_GRAYSCALE); + Mat img_kp_sift; Mat img_kp_surf; + + drawKeypoints( img, sift_keypoints, img_kp_sift, Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS); + drawKeypoints( img, surf_keypoints, img_kp_surf, Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS); + namedWindow("SIFT Keypoints",WINDOW_NORMAL); + imshow("SIFT Keypoints", img_kp_sift ); + namedWindow("SURF Keypoints",WINDOW_NORMAL); + imshow("SURF Keypoints", img_kp_surf ); + } + else + { + readme(); + return -1; + } + waitKey(0); + return 0; +} +/* @function readme */ +void readme() +{ std::cout << " Usage: ./picmatch " << std::endl; } diff --git a/ppc-redef-calc/README.md b/ppc-redef-calc/README.md new file mode 100644 index 0000000..2b3fe20 --- /dev/null +++ b/ppc-redef-calc/README.md @@ -0,0 +1,60 @@ +## Description: + +* GeruzoniAnsasu的舍友M大大最近去旁听了编译原理,回来问了一个问题把大家都难住了:为啥处理语法树的时候要有人为规定的优先级?如果优先级重新定义的话…… + +### 原题文档: +``` +Lzy有n个数字a1,a2....an,n-1个符号(+,-,*) +他问***假如运算没了优先级,各种运算顺序下的结果总和对1e9+7取模的结果是多少? +***笑了笑。 +ex:1*2+3 +(1*2)+3 = 5 + 1*(2+3)= 5 +结果是10. + +输入数据:第一行n表示共有n个数字,随后n个数字,最后符号串。数据范围2<=n<=100,(0≤ai≤109) +输出数据: 结果 + +sample input: +3 +1 1 1 +++ + +sample output: +6 + +``` +-------------- +加多点数据:) +问过能不能加入其它的运算符,答:没法加 + +## 原出题acmer的writeup +``` +这是一道简单区间DP问题。 +先来分析复杂度O(n^3),第一层处理数字的个数i,第二层从第几个开始t,第三层以哪个符号为最后结束。 +再分类讨论,+,-为一类,*为一类。 +第一类:左边的结果*右边符号数的阶乘 + 右边的结果*左边符号数的阶乘 +第二类:左边结果*右边结果即可 +注意还要乘以组合数,即为答案。 +讲得好抽象,不过很多队伍做出来,这里就简要描述。 +主要代码部分,c为组合数,f为阶乘数,注意取模 +for(int i = 2; i <= n; i++) +{ + for(int t = 1; t + i -1 <= n; t++) + { + for(int d = 1; d <=i-1; d++) + { + int w = t+d-1; + char ch = s[w]; + if(ch=='+') + dp[i][t] = (dp[i][t] + (c[i-2][d-1]*(dp[d][t]*f[i-1-d]%mod + dp[i-d][t+d]*f[d-1]%mod)%mod)%mod)%mod; + else if(ch=='-') + dp[i][t] = (dp[i][t] + (c[i-2][d-1]*(dp[d][t]*f[i-1-d]%mod - dp[i-d][t+d]*f[d-1]%mod)%mod)%mod)%mod; + else + dp[i][t] = (dp[i][t] + (c[i-2][d-1]*(dp[d][t]*dp[i-d][t+d]%mod)%mod)%mod)%mod; + } + } +} + + By ——Lzy +``` diff --git a/ppc-redef-calc/calc b/ppc-redef-calc/calc new file mode 100755 index 0000000..a109776 Binary files /dev/null and b/ppc-redef-calc/calc differ diff --git a/ppc-redef-calc/sample-code.cpp b/ppc-redef-calc/sample-code.cpp new file mode 100644 index 0000000..f1ad5d3 --- /dev/null +++ b/ppc-redef-calc/sample-code.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define inf 0x3f3f3f3f +#define LL long long +#define clr(a,b) memset(a,b,sizeof(a)) + +using namespace std; + +int a[1055]; +char s[1055]; +LL c[1055][1055]; +LL dp[1055][1055]; +LL f[1055]; +const int mod = 1e9 + 7; + +void init() +{ + c[0][0] = 1; + for(int i =1; i <= 1050; i++) + { + c[i][0] = c[i][i] = 1; + for(int j = 1; j < i; j++) + c[i][j] = (c[i-1][j] + c[i-1][j-1])%mod; + } + f[0] = f[1] = 1; + for(int i =2; i <= 1050; i++) + f[i] = i*f[i-1]%mod; +} + +int main(int argc,char *argv[]) +{ + int n; + init(); + if(scanf("%d",&n) || 1 )// patched from while + { + for(int i =1; i <= n; i++) + scanf("%d",a+i); + scanf("%s",s+1); + clr(dp,0); + for(int i = 1; i <= n; i++) + dp[1][i] = a[i]; + for(int i = 2; i <= n; i++) + { + for(int t = 1; t + i -1 <= n; t++) + { + for(int d = 1; d <=i-1; d++) + { + int w = t+d-1; + char ch = s[w]; + if(ch=='+') + dp[i][t] = (dp[i][t] + (c[i-2][d-1]*(dp[d][t]*f[i-1-d]%mod + dp[i-d][t+d]*f[d-1]%mod)%mod)%mod)%mod; + else if(ch=='-') + dp[i][t] = (dp[i][t] + (c[i-2][d-1]*(dp[d][t]*f[i-1-d]%mod - dp[i-d][t+d]*f[d-1]%mod)%mod)%mod)%mod; + else + dp[i][t] = (dp[i][t] + (c[i-2][d-1]*(dp[d][t]*dp[i-d][t+d]%mod)%mod)%mod)%mod; + } + } + } + LL ans = dp[n][1]; + if(ans < 0 ) ans += mod; + printf("%lld\n",ans); + } +} diff --git a/ppc-redef-calc/server.py b/ppc-redef-calc/server.py new file mode 100644 index 0000000..84a76d8 --- /dev/null +++ b/ppc-redef-calc/server.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python2.7 +#encoding:utf-8 +import SocketServer + +from random import random,seed,randrange +from time import time,sleep +import zio +from hashlib import md5 + +ops = '+-*' + +class MyServer(SocketServer.ThreadingTCPServer,object): + allow_reuse_address = True + def handle_timeout(self): + print '->>>>>>>>>>>>>>>>>>' + + +class MyHandler(SocketServer.StreamRequestHandler): + TO_LV1 = 10 + TO_LV2 = 6 + TO_LV3 = 1.2 + TO_LV4 = 4 + def handle(self): + print 'get connection from',self.client_address + self.request.settimeout(10) + self.wfile.write('TOKEN=') + self.token = self.rfile.readline().strip() + print 'TOKEN='+self.token + if '' == self.token: + self.wfile.write('\n\nwrong token\n') + return + print 'serving team {'+self.token+'} from ',self.client_address + self.request.settimeout(50) + self.wfile.write('GeruzoniAnsasu的舍友M大大最近去旁听了编译原理,回来问了一个问题把大家都难住了:\n') + #sleep(0.6) + self.wfile.write('为啥处理语法树的时候要有人为规定的优先级?\n') + #sleep(0.6) + self.wfile.write('如果优先级重新定义的话……\n\n') + self.rfile.readline() + self.wfile.write('example: 2*4+5\n') + self.wfile.write(' (2*4)+5 = 13\n') + self.wfile.write(' 2*(4+5) = 18\n\n') + #sleep(0.6) + self.wfile.write('那么所有这些情况的结果和是多少呢?(31)\n') + if self.rfile.readline().strip() != '31': + return + self.wfile.write('\n\n先来熟悉熟悉吧:\n') + #sleep(0.8) + smps = (('1*2+3',10),('4-3+7',2),('9*3-5',4),('6+7*8',166),('15+3*8-7',255),('3*8+11+4',316)) + for i in range(3): + t1 = time() + s,v = smps[randrange(6)] + self.wfile.write(s+' sum = ?\n') + ans = int(self.rfile.readline().strip()) + t2 = time() + if ans != v or t2-t1 > 50: + self.wfile.write('噫……\n') + return + + #sleep(0.5) + self.wfile.write('\n\n还可以,我感觉你已经理解意思了。\n') + #sleep(0.8) + self.wfile.write('现在让我们换一种表达方式,如下:\n\n') + self.wfile.write('6[2,5,10,9,3,34]++*-*\n') + self.wfile.write('答案159001\n\n') + #sleep(0.3) + self.wfile.write('以防数字太大,所有答案mod 1e9+7.\n') + self.rfile.readline() + #sleep(0.1) + self.wfile.write('那么,lv1,计时开始:)\n\n') + self.request.settimeout(self.TO_LV1) + #sleep(0.3) + self.wfile.write('2[0,10]- \n') + ans = int(self.rfile.readline().strip()) + if ans != 999999997: + self.wfile.write('再想想\n') + return + seed(time()) + sz_calc = '' + sz_send = '' + print '--LV1--' + for i in xrange(randrange(5,8)):#5到8组 LV1 + break + n = randrange(8,18)#8到18个数 + sz_calc = str(n)+'\n' + sz_send = str(n) + l = [] + for j in xrange(n): + num = randrange(1e9+7) + sz_calc += str(num)+' ' + l.append(num) + sz_calc += '\n' + sz_send += repr(l) + for j in xrange(n-1): + sign = ops[randrange(3)] + sz_calc += sign + sz_send += sign + io = zio.zio('./calc',print_read = lambda x:'',print_write = lambda x:'') + io.writeline(sz_calc) + right_ans = int(io.readline().strip()) + print 'R->',right_ans + self.wfile.write(sz_send+'\n') + #continue + ans = int(self.rfile.readline().strip()) + print '<-A',ans + if ans != right_ans: + return + io.close() + + print '--LV2--' + self.wfile.write('可喜可贺!\nlv2,时限更严:)\n\n')#LV2 + self.request.settimeout(self.TO_LV2) + for i in xrange(randrange(10,20)):#10到20组 + n = randrange(12,30)#12到30个数 + sz_calc = str(n)+'\n' + sz_send = str(n) + l = [] + for j in xrange(n): + num = randrange(1e9+7) + sz_calc += str(num)+' ' + l.append(num) + sz_calc += '\n' + sz_send += repr(l) + for j in xrange(n-1): + sign = ops[randrange(3)] + sz_calc += sign + sz_send += sign + io = zio.zio('./calc',print_read = lambda x:'',print_write = lambda x:'') + io.writeline(sz_calc) + right_ans = int(io.readline().strip()) + print 'R->',right_ans + self.wfile.write(sz_send+'\n') + #continue + ans = int(self.rfile.readline().strip()) + print '<-A',ans + if ans != right_ans: + print ':(' + return + io.close() + + print '--LV3--' + self.wfile.write('有希望看到flag了!\nlv3,证明你是精英的时候:)\n\n')#LV3 + self.request.settimeout(self.TO_LV3) + for i in xrange(10):#30组 + n = randrange(90,150)#90到150个数 + sz_calc = str(n)+'\n' + sz_send = str(n) + l = [] + for j in xrange(n): + num = randrange(1e9+7) + sz_calc += str(num)+' ' + l.append(num) + sz_calc += '\n' + sz_send += repr(l) + for j in xrange(n-1): + sign = ops[randrange(3)] + sz_calc += sign + sz_send += sign + io = zio.zio('./calc',print_read = lambda x:'',print_write = lambda x:'') + io.writeline(sz_calc) + right_ans = int(io.readline().strip()) + print 'R->',right_ans + self.wfile.write(sz_send+'\n') + #continue + ans = int(self.rfile.readline().strip()) + print '<-A',ans + if ans != right_ans: + return + io.close() + + print '--LV4--' + self.wfile.write('\nINSANE!!\n\n')#LV4 + self.request.settimeout(self.TO_LV4) + for i in xrange(2): + n = randrange(700,900)#700到900个数 + sz_calc = str(n)+'\n' + sz_send = str(n) + l = [] + for j in xrange(n): + num = randrange(1e9+7) + sz_calc += str(num)+' ' + l.append(num) + sz_calc += '\n' + sz_send += repr(l) + for j in xrange(n-1): + sign = ops[randrange(3)] + sz_calc += sign + sz_send += sign + io = zio.zio('./calc',print_read = lambda x:'',print_write = lambda x:'') + io.writeline(sz_calc) + right_ans = int(io.readline().strip()) + print 'R->',right_ans + self.wfile.write(sz_send+'\n') + #continue + ans = int(self.rfile.readline().strip()) + print '<-A',ans + if ans != right_ans: + return + io.close() + + self.wfile.write('here you got the flag, but i removed some code from original file.\n') + print 'team {%s} got the flag.' % self.token + +if __name__ == "__main__": + host = '0.0.0.0' + port = 4799 + print 'started.' + s = MyServer((host,port),MyHandler) + s.serve_forever() diff --git a/ppc-redef-calc/test.py b/ppc-redef-calc/test.py new file mode 100644 index 0000000..0efd3aa --- /dev/null +++ b/ppc-redef-calc/test.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python2.7 +#encoding:utf-8 + +from zio import * +import time +target = ('127.0.0.1',9979) +target = ('120.55.113.21',4799) +io = zio(target,timeout=5,print_read=COLORED(REPR,'cyan'),print_write=COLORED(REPR,'red')) +io.writeline('thatsme') +io.writeline() +time.sleep(0.5) +io.writeline('31') +io.read_until('吧') +io.readline() +q = io.readline() +q = q[:q.find('sum')-1].strip() +smps = {'1*2+3':10,'4-3+7':2,'9*3-5':4,'6+7*8':166,'15+3*8-7':255,'3*8+11+4':316} +io.writeline(str(smps[q])) +q = io.readline() +q = q[:q.find('sum')-1].strip() +io.writeline(str(smps[q])) +q = io.readline() +q = q[:q.find('sum')-1].strip() +io.writeline(str(smps[q])) +io.writeline() +time.sleep(0.5) +io.read_until(':)') + +io.readline() +io.readline() + +while True: + try: + q = io.readline().strip() + if q.find('[') < 0: + raise 'E' + n = q[:q.find('[')] + nums = eval(q[q.find('['):q.find(']')+1]) + signs = q[q.find(']')+1:] + #print n,nums,signs + s = '{0}\n{1}\n{2}'.format(str(n),' '.join(map(str,nums)),signs) + #print s + calcio = zio('./calc',print_write=lambda x:'',print_read=lambda x:'') + calcio.writeline(s) + ans = calcio.readline().strip() + #print 'ans:',ans + io.writeline(ans) + print '_______' + except KeyboardInterrupt: + break + except: + print '>>' + if q.find('hctf') >= 0: + print q + break + time.sleep(0.3) + continue