s

security

使用 chown 和 chmod 將資料夾及其內容的擁有者設為 nobody,並設定適當的讀寫執行權限。

0 0 0 1
1 # 將該資料夾及裡面的所有檔案/子目錄的 owner & group 改成 65534:65534
2 # 65534 就是「nobody」的代號,用來指定權限最低的帳號,降低風險。
3 sudo chown -R 65534:65534 /path/to/directory
4
5 # 把該資料夾及其所有內容的權限設成 775
6 # 表示 owner 與同群組成員可讀寫執行,其他人只能讀與執行
7 sudo chmod -R 775 /path/to/directory

用 bcrypt 進行密碼加密與驗證,支援 salt、自動安全雜湊,保護你的使用者資料不被爆破!適合登入驗證與帳號系統 🚀

0 0 0 1
1 import bcrypt
2
3
4 def encode_password(password: str) -> str:
5 salt = bcrypt.gensalt()
6 hashed = bcrypt.hashpw(password.encode(), salt)
7 return hashed.decode()
8
9
10 def check_password(password: str, hashed: str) -> bool:
Last active 5 hours ago api authentication fastapi header python security

FastAPI 可透過 Header 讀取請求標頭,並透過 Depends 進行依賴注入(Dependency Injection),適用於 API Token 驗證、身份驗證、請求處理 等場景。

0 0 0 3
1 from fastapi import FastAPI, Header, HTTPException
2
3 app = FastAPI()
4
5 @app.get("/secure-data")
6 async def secure_data(api_key: str = Header(None)):
7 if api_key != "my_secure_token":
8 raise HTTPException(status_code=401, detail="無效的 API 金鑰")
9 return {"message": "驗證成功,提供安全數據"}
Last active 5 hours ago audit logging monitoring python security

addaudithook 可用來監聽 Python 內部的安全性相關事件,例如模組導入、檔案存取或執行系統命令,可用於安全監控、日誌記錄或限制不安全的操作。

0 0 0 1
1 import sys
2
3 def audit_hook(event, args):
4 print(f"Audit event: {event}, Arguments: {args}")
5
6 # 註冊審計鉤子
7 sys.addaudithook(audit_hook)
8
9 # 觸發一些事件
10 open("test.txt", "w").write("Hello") # 檔案寫入事件

這段程式碼建立了一個 WebSocket 伺服器,允許遠端用戶端傳送指令,並在伺服器端執行該指令後回傳執行結果。適用於遠端系統管理、指令控制或測試環境中的即時互動,但因為直接執行來自用戶端的指令,需特別注意安全性風險,如權限控管與輸入驗證,以防止指令注入攻擊。

0 0 0 1
1 import asyncio
2 import websockets
3 import subprocess
4
5 async def handle_command(websocket, path):
6 try:
7 async for message in websocket:
8 print(f"Received command: {message}")
9
10 # 執行系統指令

這兩段 Bash 指令都利用 tcpdump 監控 eth0 網卡上的郵件流量,第一個同時捕捉 POP3 (port 110) 與 IMAP (port 143) 的封包並存成 imap_pop3.pcap,而第二個則專門捕捉 POP3 (port 110) 流量並存成 pop3_traffic.pcap,方便後續進行網路分析或除錯。

0 0 0 2
1 #!/bin/bash
2
3 tcpdump -i eth0 port 110 or port 143 -w imap_pop3.pcap

此 SSH 設定根據目標 IP 或域名,透過不同的跳板機 (ProxyCommand) 進行連線,確保內外部網路存取的靈活性與自動化。

0 0 0 1
1 Host *.internal.local
2 ProxyCommand bash -c 'timeout 3 nc -z %h %p || ssh -W %h:%p jump.internal.example.com'
3
4 Host *
5 ProxyCommand bash -c 'timeout 3 nc -z %h %p || ssh -W %h:%p jump.external.example.com'
6
7 Host 192.168.0.*
8 ProxyCommand bash -c 'timeout 3 nc -z %h %p || ssh -W %h:%p jump1.example.com'
9
10 Host 172.16.*.*