Tiếp nối bài viết trước đó là tạo port scanner [trình quét cổng] bằng python. Trong bài viết này, mình sẽ hướng dẫn các bạn làm quen với thư viện requests trong python, và cách ứng dụng thư viện đó trong an ninh mạng nhé.
Đối phó với các requests HTTP không phải là một nhiệm vụ dễ dàng trong bất kỳ ngôn ngữ lập trình nào. Nếu khi nói về Python, nó đi kèm với hai thư viện tích hợp sẵn là urllib
và urllib2
, để xử lý các hoạt
động liên quan đến HTTP. Cả hai thư viện đi kèm này đều có một tập hợp các hàm [chức năng] khác nhau và nhiều khi cần được sử dụng cùng nhau. Hạn chế chính của việc sử dụng urllib
là nó dễ gây nhầm lẫn [một số methods có sẵn trong cả urllib
, urllib2
], tài liệu không rõ ràng và chúng ta cần viết rất nhiều code để thực hiện một yêu cầu HTTP đơn giản.
Để làm cho công việc đơn giản hơn, một thư viện bên thứ ba dễ sử dụng đã ra đời, được gọi là
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]0, có sẵn và hầu hết các nhà phát triển đều thích sử dụng nó để thay thế urllib/urllib2. Nó là một thư viện HTTP của Apache2 và được cung cấp bởi urllib3 và httplib.
Cài đặt
Vì trong bài này sử dụng python3, nên mình sẽ sử dụng pip3 để cài đặt các thư viện của bên thứ ba.
Nhập lệnh sau vào Terminal:
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]1
Lệnh
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]2 đó sẽ cài đặt thư viện
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]3 trên hệ thống của bạn.
Các khái niệm cơ bản về requests
Để bắt đầu sử dụng thư viện
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]3 của python, trước tiên bạn cần phải import nó. Sau đây là các lệnh sẽ được sử dụng để tạo một chương trình thu thập dữ liệu từ một trang web hoặc API. Nhưng trước tiên, bạn cần đọc bài viết này nắm rõ về cơ chế hoạt động của HTTP đã.
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]
5: Lệnh này sẽ thực hiện request GET tới trang web.import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]
6: Lệnh này sẽ thực hiện request POST đến URL và dữ liệu của nội dung bài viết có thể được chuyển sang dạng dictionary.
Lưu ý: Các phương thức request khác sẽ được thực hiện theo cách tương tự như request.head, request.put,…
Để dễ hiểu, chúng ta hãy lấy một ví dụ về đối tượng request:
>>>import requests >>>r = requests.get["//google.com"]
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]
7: Lệnh này sẽ trả về mã phản hồi đã nhận được từ request như 200, 404, 301,…import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]
8: Lệnh này sẽ trả về dữ liệu bạn đã nhận được từ một trang web.import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]
9: Lệnh này sẽ lấy dữ liệu đã phản hồi từ web dưới dạng dictionary.
Đối số cho các phương thức request:
#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file
0: Lệnh này được sử dụng để đặt thời gian chờ cho một request.#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file
1: Lệnh này được sử dụng để chỉ định chuyển hướng có thể được phép hoặc không như#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file
2 sẽ cho phép các request chuyển hướng.#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file
3: Lệnh này sẽ hiển thị dạng mã hóa của dữ liệu nhận được.#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file
4: Lệnh này sẽ chuyển cookie đến session request.#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file
5: Lệnh này sẽ sử dụng để cung cấp header cho session request.
Bài tập 1: Tra cứu IP
Áp dụng những kiến thức trên, chúng ta sẽ thực hiện một request đơn giản tới API tra cứu IP để thu thập thông tin cho mục tiêu của chúng ta.
Lưu ý: Đây sẽ là một request rất cơ bản, nhưng dù sao nó cũng sẽ giúp bạn hiểu cách thu thập dữ liệu bằng Python. Mình đang sử dụng API này để nhận thông tin chung về địa chỉ IP.
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]
Cách hoạt động
Trên dòng đầu tiên và thứ hai, chúng ta import 2 thư viện là
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]0 và
#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file7. Sau đó, chúng ta tạo một hàm có tên
#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file8, chứa tham số
#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file9. Tiếp theo, chúng ta gửi request tới API và xem nó có thành công hay không thông qua
import requests import json # Thư viện dùng để định dạng dữ liệu nhận được def iplookup[public_ip]: r = requests.get["//ip-api.com/json/"+public_ip] if r.status_code == 200: # Nếu thành công data = json.loads[r.text] # Chuyển dữ liệu nhận được vào json for key, value in [data].items[]: # Định dạng dữ liệu json sang dictionary print["{}:{}".format[key, value]] else: # If error occurs print["Error Occured while making request"] if __name__ == "__main__": try: ip = input["Enter IP: "] iplookup[ip] except: print["Error Occured!"]7. Chuyển dữ liệu nhận được sang định dạng json và dictionary rồi in ra Terminal. Mình đã thêm
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]1 để xử lý bất kỳ lỗi nào có thể xảy ra.
Bài tập
2 : Chặn thư mục
Bây giờ, chúng ta hãy sử dụng một công cụ phức tạp hơn, nhưng rất hữu ích, một công cụ chặn thư mục. Nhưng trước khi tiếp tục, mình sẽ giải thích cho cac bạn cách đọc và ghi file bằng Python.
Xử lý file: Đọc và ghi
Chúng ta cần đọc các tệp để thực hiện việc chặn thư mục bằng cách sử dụng dictionary attack. Trong python, chúng ta sử dụng hàm
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]2 là một hàm tích hợp trả về một đối tượng tệp và có thể được sử dụng để mở tệp theo nhiều cách khác nhau như đọc, ghi và nối thêm.
Ví dụ:
#!/usr/bin/python3 f = open["new.txt", "r"] # Mở file ở chế độ đọc print[f.read[]] # Đọc nội dung file new = open["new1.txt","w"] # Mở file ở chế độ đọc ghi data = f.read[] new.write[data] # Ghi dữ liệu vào file new1.txt new.close[] # Đóng file
Chúng ta sử dụng hàm
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]2 có 2 tham số là đường dẫn của file và chế độ mở file. Trong ví dụ trên,
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]4 là đường dẫn tệp, còn
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]5 là chế độ đọc và sau đó mở tệp
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]6 để ghi dữ liệu.
Các chế độ tệp khác nhau:
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]
5: Chế độ đọc.import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]
8: Chế độ ghi.import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]
9: Chế độ nối [Khi mở file, vị trí con trỏ sẽ luôn ở cuối file].[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--
0: Chế độ đọc và ghi.
Lưu ý: Việc thêm
[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--1 vào một chế độ sẽ mở tệp ở chế độ hoạt động nhị phân, tức là tất cả nội dung của tệp sẽ được coi là đối tượng byte như[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--2 sẽ đọc tệp ở dạng nhị phân.
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]
Cách hoạt động
Chúng ta đã tạo một hàm có tên là
[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--3 với các tham số là
[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--4 và
[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--5, đây sẽ là tệp chứa danh sách thư mục để brute force trên trang web. Tiếp theo, mình cũng không quên sử dụng
import requests def dirb[url, dict]: try: wordlist = open[dict,"rb"] for path in wordlist.readlines[]: path = path.strip[].decode["utf-8"] urlpath = url+"/"+path r = requests.get[urlpath] if r.status_code != 404: print["{} -> {}".format[r.status_code, urlpath]] except: # Catching exceptions print["Error Occured!"] if __name__ == "__main__": dirb["//10.0.0.210", "all.txt"]1. Sau đó, mình mở tệp
[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--5 bằng cách sử dụng
[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--8 và đọc danh sách các từ có trong file, rồi tách chuỗi và giải mã, nối dữ liệ vào các url được chỉ định của mình, sau đó thêm các url và đường dẫn cùng với “/”. Cuối cùng, thực hiện request GET tới url đã tạo và in đầu ra của request miễn là mã phản hồi không bằng 404 [có nghĩa là “Not Found”].
Mình sẽ sử dụng tệp lệnh này để hack một máy chủ trên TryHackMe MrRobotCTF và đây là kết quả:
[email protected]:~$ python3 temp.py 200 -> //10.0.0.210/admin 403 -> //10.0.0.210/.htaccess 200 -> //10.0.0.210/readme.html 200 -> //10.0.0.210/image --snip--
Bạn cũng có thể triển khai máy chủ MrRobot và sử dụng tập lệnh này để lấy các thư mục của trang web.
Tổng kết
Bài viết này sẽ cung cấp cho bạn đủ ý tưởng và kiến thức để tạo các công cụ của riêng bạn bằng Python3. Nhưng trong dự án thứ hai, bạn có thể thấy rằng chương trình chạy hơi lâu. Để giải quyết vấn đề đó, chúng ta có thể sử dụng đa luồng. Mình chưa thêm tính năng đó vào vì nó sẽ yêu cầu thêm một số thư viện và kiến thức khác nhau. Ngoài ra, bạn cũng có thể xem thêm nhiều bài về python tại đây.