본문 바로가기

[Wargame Write-up]/NewbieContest

[NewbieContest] [Programmation] Second degré

Second degree라는 뜻의 문제이다.




불어로 뭐라고 써 있는데, 대충 보면 소수점 둘째 자리까지 나타낸 값을 전송하라는 것 같다.




주어진 이차방정식의 해 중 하나를 반올림하여 소수점 둘째 자리까지 구하고, 그 값을 보내면 된다.




아래처럼 특정 항이 없는 경우도 있으니, 주의해서 코딩하도록 하자.




아래는 solution 값을 주지 않았을 때의 Error Page이고,




아래는 답이 틀렸을 때의 Error Page이다. 참고하여 코딩하자.




이차방정식의 해를 구하는 부분에서 나올 수 있는 형태는 모두 고려하였고, 


제한시간 1초 때문에 전송 후 결과값을 출력하게 했다.


정규식을 사용해서 그런지 Time out 되는 경우가 있으니, 여러 차례 실행해야 한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#-*- coding: utf-8 -*-
import requests
import getpass
import sys
import os
import math
import re
 
def clear_screen():
    if sys.platform == 'win32':
        os.system("cls")
 
    else:
        os.system("clear")
 
def get_session(login_url, username, password):
    data = {"cookielength""-1"}
 
    try:
        data["user"= username
        data["passwrd"= password
 
        print("\n  [*] Connecting to " + login_url)
        session = requests.Session()
        session.post(login_url, data=data)
        print("  [*] Connection Success\n")
 
    except requests.exceptions.ConnectionError:
        print("  [*] Connection Failed\n")
        sys.exit()
 
    return session
 
def extract_necessary_string(session, target_url, find_text):
    response = session.get(target_url).text.encode('utf-8')
    result = response[response.find(find_text[0]) + len(find_text[0]):].replace("\xc3\x82\xc2\xb2""^2")
 
    print("  [*] Extracted Strings: %s (replaced \"\xc3\x82\xc2\xb2\" to ^2)" % result)
    
    return result
 
def get_answer(string):
    # get operand from extracted Strings
    operands = filter(None, re.split(" |= 0", string))
    
    a = (operands[0== "x^2"and 1 or int(operands[0].replace("x^2"""))
 
    if len(operands) == 5# when the equation form is ax^2 + bx + c = 0
        b = (operands[2== "x"and int(operands[1+ "1"or int(operands[1+ operands[2].replace("x"""))
        c = int(operands[3+ operands[4])
    
    elif len(operands) == 3:
        if "x" in operands[2]: # when the equation form is ax^2 + bx = 0
            b = (operands[2== "x"and int(operands[1+ "1"or int(operands[1+ operands[2].replace("x"""))
            c = 0
        
        else# when the equation form is ax^2 + c = 0
            b = 0
            c = int(operands[1+ operands[2])
 
    else# when the equation form is ax^2 = 0 (won't be happened)
        b = 0
        c = 0
 
    print("  [*] Operands: a = %d, b = %d, c = %d" % (a, b, c))
 
    return [round((-+ math.sqrt(b**2 - 4*a*c)) / (2*a), 2), round((-- math.sqrt(b**2 - 4*a*c)) / (2*a), 2)]
 
def submit_answer(session, submit_url, answer):
    # send answer first because of time limit: 1 second
    response = session.get(submit_url + str(answer[0])).text.encode('utf-8')
 
    print("  [*] Answer to submit (rounded off to the second digit after the decimal point):"),
    print(answer)
    print("")
 
    if "Bravo" in response:
        print("  [*] Submit Success :)")
        print("\n  [*] " + response[response.rfind(', '+ len(', '):response.rfind('</p>')])
 
    else:
        print("  [*] Submit Failed or Timed out :(")
  
def main():
    target_domain = "https://www.newbiecontest.org/"
    target_url = target_domain + "epreuves/prog/prog6.php"
    submit_url = target_domain + "epreuves/prog/verifpr6.php?solution="
    login_url = target_domain + "forums/index.php?action=login2"
    find_text = ["est :<br />"]
 
    clear_screen()
 
    session = get_session(login_url, raw_input("\nUsername: "), getpass.getpass())
    submit_answer(session, submit_url, get_answer(extract_necessary_string(session, target_url, find_text)))
 
if __name__ == '__main__':
    main()
 
cs



성공 시 결과 화면이다.




받은 인증키를 입력하면,




Clear~