顯示具有 資安 標籤的文章。 顯示所有文章
顯示具有 資安 標籤的文章。 顯示所有文章

2024年4月14日 星期日

Python 學習筆記 : 用 AES-Encryption 為帳號密碼加密與解密

周末將兩年半前買的 "Python 金融市場大賺錢投資聖經" 這本書帶回鄉下看, 我記得裡面有寫一些網路爬蟲的密技, 在其中第三章看到作者描述如何用 AES 為帳號密碼等機敏資料加密, 覺得還蠻有用的, 今天就來測試看看唄.


1. 下載 AES-Encryption : 

到下面這個 GitHub 下載 AES-Encryption 的模組 : 

按右上角的 Code 鈕選擇 Download ZIP 下載壓縮檔 : 




將此壓縮檔 AES-Encryption-main.zip 解開, 如果產生兩層 AES-Encryption 資料夾, 就複製最下層的 AES-Encryption 資料夾到工作目錄下, 例如我的工作目錄是 D:\python\test\ 則子目錄 AES_Encryption 底下就是解開的兩個 .py 檔 : 




第一個模組 en_decrype.py 利用一個第三方模組 Crypto 來做 AES 加密解密作; 第二個模組 encrype_process.py 則是利用 en_decrype.py 編寫了加密函式 input_new_encrype() 與解密函式 check_encrype(), 不過實際上使用時只需要呼叫 check_encrype() 即可, 若未找到密鑰名稱, 它會自動呼叫 input_new_encrype() 讓你輸入帳號密碼與名稱來建立密鑰. 這三個模組關係如下 :

Crypto 
     |__ encrype_process
                |__ encrype_process

所以要讓 check_encrype() 能用必須先有 Crypto 模組才行. Crypto 模組在 Python 中正式名稱是 pycrypto, 不過此套件已經停止更新很久了, 必須改安裝它的延伸套件 pycryptodome, 它裡面就有 Crypto 模組, 參考 :



2. 安裝 pycryptodome 套件 : 

可以使用 pip install 指令直接安裝 :

pip install pycryptodome 

D:\python\test>pip install pycryptodome   
Collecting pycryptodome
  Using cached pycryptodome-3.20.0-cp35-abi3-win_amd64.whl.metadata (3.4 kB)
Using cached pycryptodome-3.20.0-cp35-abi3-win_amd64.whl (1.8 MB)
Installing collected packages: pycryptodome
Successfully installed pycryptodome-3.20.0

我在 Thonny 套件管理安裝了最新版的 v3.20.0 :




安裝完就可匯入 Crypto 模組了 :

>>> import Crypto  
>>> dir(Crypto)   
['Cipher', 'Hash', 'Protocol', 'Random', 'Util', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'version_info']

上面 en_decrypt.py 裡面第一行就是從 Crypto.Cipher 匯入 AES 類別來進行加密與解密 : 

from Crypto.Cipher import AES 

但我們只要直接使用上面 AES-Encryption 套件中第二個模 encrype_process.py 的 check_encrype() 函式就可以進行加密解密了. 


3. 使用 AES_encryption 套件 : 

使用 AES_Encryption 套件進行加密解密只要從它的 encrype_process 模組中匯入全部函式即可 :

from AES_Encryption.encrype_process import *

>>> from AES_Encryption.encrype_process import *     # 注意是 encrype 不是 encrypt

不過 encrype_process 模組中的 input_new_encrype() 函式是作者為了 Gmail 登入帳密而特製, 我將其改為較一般化的設定指引, 將其中 print() 與 input() 中的英文提示修改如下 :

def input_new_encrype(fuc_name,key_path,result_path):
    print(f'名稱:{fuc_name}')
    user_id = input('帳號:')
    password = input('密碼:')
    print(result_path)
    result_file_path = (result_path+'encrype.config').replace('\n','')
    key = get_key(key_path,result_path)
    user_encrype = aes_encrypt(user_id, key)
    password_encrype = aes_encrypt(password, key)
    store_encrype = dict()
    store_encrype['name'] = fuc_name
    store_encrype['user_id'] = user_encrype
    store_encrype['password'] = password_encrype
    with open(result_file_path, 'a') as outfile:
        json.dump(store_encrype, outfile)
        outfile.write('\n')
    outfile.close()
    print('加密完成!')
    return user_id,password

參考 :


然後設定儲存金鑰檔與設定檔的資料夾路徑變數, 注意, 最好不要放在工作目錄下, 否則打包時很容易把金鑰都打包進去分享給他人, 其次是路徑結尾必須有斜線 "/", 例如 : 

>>> key_path="D:/key/"             # 金鑰路徑
>>> config_path="D:/config/"    # config 檔路徑

然後呼叫 check_encrype() 函式並傳入金鑰名稱, 金鑰路徑, 與設定檔路徑, 如果金鑰名稱存在會傳回解碼後的帳號與密碼組成之 tuple, 否則會出現輸入框要求設定金鑰名稱與鑰加密之帳密 : 

user_id, password=check_encrype(name, key_path, config_path)     

例如要加密我的網站 tony1966.cc 的登入帳密 : 

>>> user, pwd=check_encrype('tony1966.cc', key_path, config_path)    
名稱:tony1966.cc  
帳號:admin  
密碼:123456  
D:/config/  
加密完成!  

這時檢視 D 碟會發現已建立 key 與 config 這兩個資料夾, 裡面分別有 key.key 與 encrype.config 這兩個檔案 :





用 utf-8 編碼格式開啟 key.key 會發現是不可讀之亂碼 : 

�����\=�NA��6w�|���Y���7�

開啟 encrype.config 則是加密過的明碼 : 

{"name": "tony1966.cc", "user_id": "SgALjY8Tq7EnCo2uM45Z/MyIXtUU65qJDgDEDQv5jKE=\n", "password": "RlqD34SyRjK/Q3tGB9jx3dycB0PB9HiW1wrCtYfdYsU=\n"}

再次執行 check_encrype() 時因為有找到金鑰名稱 tony1966.cc 所以就傳回解碼後的帳密 : 

>>> user, pwd=check_encrype('tony1966.cc', key_path, config_path)    
>>> user   
'admin'  
>>> pwd    
'123456'   

這樣就能增強帳號密碼的安全性了. 如果要重設帳密, 只要將 key 與 config 這兩個資料夾刪除, 重新呼叫 check_encrype() 就可以再次設定了. 當然也可以用來儲存 OpenAI API 的 key, 例如 name 名稱可以取名為 tony1966_openai_key, 前面是註冊的 email 帳號 (我有多個帳號), 帳號就用 email, 而密碼就輸入 API Key, 解密回來時就用 password 當 API Key 用. 


2024-04-15 補充 :

我把修改後的 AES_Encryption 資料夾壓縮後放在 GitHub : 


2024年2月20日 星期二

Mapleboard MP510-50 測試 (十八) : 註冊 Let's Encrypt 的 SSL/TLS 憑證

申請好網域名稱後, 網站其實只有 HTTP 協定功能, 接下來必須安裝 SSL/TLS 憑證, 這樣網站才會有 HTTPS 加密傳輸功能, 否則瀏覽器連線網站時都會先顯示這是不安全的網站, 雖然按繼續瀏覽還是可以進入網站首頁, 但這樣的存取並不安全. 

以前憑證須要花錢買 (一年大約要 2~3 千元), 且年年要續約, 現在有免費的 Let's Encrypt 可用, 但先決條件是你的網站必須要有一個域名 (domain name), 我過年前便已向 Namecheap 購買了 tony1966.cc 的域名 (10 年 59.8 美元, 每年約 191 元台幣, 如其名真的很便宜), 參考 :


我原先是在下面這本書的 16.3 節看到 Let's Encrypt 的介紹 :

# 活用 django4 建構動態網站的 16 堂課 (博碩, 2023, 何敏煌, 林亮昀) 

不過此書是以 Apache 伺服器為例說明設定方式, 但我用的是 Nginx 伺服器, 所以主要是參考下面兩篇教學文章進行設定 : 



一. 關於 SSL 與 HTTPS 加密傳輸 : 

先摘要整理 SSL 加密憑證的相關知識如下 : 
  1. 傳統的 HTTP 協定是以明碼方式傳遞, 並未將內容加密, 只要用封包探測軟體就能輕易擷取用 HTTP 傳送的機敏內容, 例如帳號密碼, API 的存取密鑰 (access key) 或權杖 (csrf_token) 等, 駭客就能利用這些資訊送出假造的請求來進行網路攻擊或滲透. 
  2. SSL (Secure Soket Layer) 使用非對稱金鑰在後端網站與前端瀏覽器之間建立可信任的 HTTPS 加密傳輸, 當以 HTTPS 連線網站伺服器時, 伺服器主機會提供一把公鑰 (public key) 給瀏覽器, 讓它用來將欲傳送的內容加密, 當伺服器收到這加密過的資料, 就會用與那把公鑰對應的私鑰 (private key) 進行解密來取得原始的資料. 不過, SSL 只是安全性憑證的通稱, 事實上現在使用的是比 SSL 更安全的進階版 : TLS (Tranport Layer Security) .
  3. 但是當瀏覽器連線 HTTPS 網站時收到對方發送的公鑰時, 要如何辨別這把公鑰是真是假? 這時候就需要一個第三方的公正單位來提供信任查詢服務, 這個公正單位稱為憑證中心. 網站管理者如果要提供 HTTPS 安全連線功能, 必須提供網域名稱等資料向憑證中心提出申請, 當驗證通過後會得到一對金鑰並安裝在伺服器主機中並做好設定, 當客戶端提出 HTTPS 請求時伺服器會向其傳送公鑰, 瀏覽器收到後自動向憑證中心查詢此公鑰持有者是否可信任, 若驗證通過才會進行 SSL 加密傳輸. 
  4. 大部分的商用憑證必須付費購買且定期重新驗證, Let's Encrypt 是由 Google, IBM, Cisco 等大企業捐資成立的免費憑證頒發機構 ( CA, Certificate Authority, 憑證中心), 任何擁有網域名稱的主機管理人均可從 Let's Encrypt 獲得可信任的憑證, 替網站啟用 HTTPS (SSL/TLS) 功能. 其頒發的憑證效期為三個月, 亦即每三個月須重新驗證 (可透過程式自動更新憑證). Let's Encrypt 的驗證方式較初階, 憑證申請者 (也就是網站管理者) 必須在伺服器的特定資料夾下放置憑證中心指定之檔案, 以證明申請者擁有網站的管理權限. 參考 :

    # https://letsencrypt.org/zh-tw/

二. 使用 Certbot 套件註冊 Let's Encrypt 憑證 : 

Certbot 套件是一個軟體工具, 用來向 Let's Encrypt 註冊憑證並於到期前自動更新, 此軟體由位於美國舊金山的非營利機構電子前沿基金會 (Electronic Frontier Foundation) 設計與維護, 參考


Certbot 同時支援 Apache 與 Nginx 伺服器. 以下是安裝程序 :


1. 更新本機套件索引 : 

用下列指令更新套件索引 :

sudo apt update   

tony1966@LX2438:~$ sudo apt update     
[sudo] tony1966 的密碼: 
下載:1 http://packages.microsoft.com/repos/code stable InRelease [3,589 B]
已有:2 http://deb.mapleboard.org/mp510 jammy InRelease                 
下載:3 http://packages.microsoft.com/repos/code stable/main amd64 Packages [16.2 kB]
下載:4 https://linux.teamviewer.com/deb stable InRelease [11.9 kB]             
已有:5 http://ports.ubuntu.com jammy InRelease                                 
下載:6 http://packages.microsoft.com/repos/code stable/main arm64 Packages [16.4 kB]
下載:7 http://packages.microsoft.com/repos/code stable/main armhf Packages [16.3 kB]
下載:8 http://ports.ubuntu.com jammy-security InRelease [110 kB]
下載:9 http://ports.ubuntu.com jammy-updates InRelease [119 kB]
已有:10 http://ports.ubuntu.com jammy-backports InRelease
下載:11 http://ports.ubuntu.com jammy-updates/main arm64 Packages [1,193 kB]
下載:12 http://ports.ubuntu.com jammy-updates/main armhf Packages [768 kB]
取得 2,254 kB 用了 4s (504 kB/s)                           
正在讀取套件清單... 完成
正在重建相依關係... 完成
正在讀取狀態資料... 完成  
可升級 37 個套件。執行 apt list --upgradable 檢視


2. 安裝 Certbot 套件 : 

指令如下 :

sudo apt install certbot python3-certbot-nginx -y   

tony1966@LX2438:~$ sudo apt install certbot python3-certbot-nginx -y    
正在讀取套件清單... 完成
正在重建相依關係... 完成  
正在讀取狀態資料... 完成  
下列的額外套件將被安裝:
  python3-acme python3-certbot python3-certifi python3-configargparse python3-configobj python3-icu python3-idna
  python3-josepy python3-openssl python3-parsedatetime python3-requests python3-requests-toolbelt python3-rfc3339
  python3-tz python3-zope.component python3-zope.event python3-zope.hookable python3-zope.interface
建議套件:
  python-certbot-doc python3-certbot-apache python-acme-doc python-certbot-nginx-doc python-configobj-doc
  python-openssl-doc python3-openssl-dbg python3-socks python-requests-doc
下列【新】套件將會被安裝:
  certbot python3-acme python3-certbot python3-certbot-nginx python3-certifi python3-configargparse python3-configobj
  python3-icu python3-idna python3-josepy python3-openssl python3-parsedatetime python3-requests
  python3-requests-toolbelt python3-rfc3339 python3-tz python3-zope.component python3-zope.event
  python3-zope.hookable python3-zope.interface
升級 0 個,新安裝 20 個,移除 0 個,有 37 個未被升級。
需要下載 1,440 kB 的套件檔。
此操作完成之後,會多佔用 7,316 kB 的磁碟空間。
下載:1 http://ports.ubuntu.com jammy/main arm64 python3-openssl all 21.0.0-1 [45.2 kB]
下載:2 http://ports.ubuntu.com jammy/universe arm64 python3-josepy all 1.10.0-1 [22.0 kB]
下載:3 http://ports.ubuntu.com jammy/main arm64 python3-certifi all 2020.6.20-1 [150 kB]
下載:4 http://ports.ubuntu.com jammy/main arm64 python3-idna all 3.3-1 [49.3 kB]
下載:5 http://ports.ubuntu.com jammy-security/main arm64 python3-requests all 2.25.1+dfsg-2ubuntu0.1 [48.8 kB]
下載:6 http://ports.ubuntu.com jammy/main arm64 python3-requests-toolbelt all 0.9.1-1 [38.0 kB]
下載:7 http://ports.ubuntu.com jammy-updates/main arm64 python3-tz all 2022.1-1ubuntu0.22.04.1 [30.7 kB]
下載:8 http://ports.ubuntu.com jammy/main arm64 python3-rfc3339 all 1.1-3 [7,110 B]
下載:9 http://ports.ubuntu.com jammy-updates/universe arm64 python3-acme all 1.21.0-1ubuntu0.1 [36.4 kB]
下載:10 http://ports.ubuntu.com jammy/universe arm64 python3-configargparse all 1.5.3-1 [26.9 kB]
下載:11 http://ports.ubuntu.com jammy/main arm64 python3-configobj all 5.0.6-5 [34.8 kB]
下載:12 http://ports.ubuntu.com jammy/universe arm64 python3-parsedatetime all 2.6-2 [32.9 kB]
下載:13 http://ports.ubuntu.com jammy/universe arm64 python3-zope.hookable arm64 5.1.0-1build1 [11.4 kB]
下載:14 http://ports.ubuntu.com jammy/main arm64 python3-zope.interface arm64 5.4.0-1build1 [142 kB]
下載:15 http://ports.ubuntu.com jammy/universe arm64 python3-zope.event all 4.4-3 [8,180 B]
下載:16 http://ports.ubuntu.com jammy/universe arm64 python3-zope.component all 4.3.0-3 [38.3 kB]
下載:17 http://ports.ubuntu.com jammy/universe arm64 python3-certbot all 1.21.0-1build1 [175 kB]
下載:18 http://ports.ubuntu.com jammy/universe arm64 certbot all 1.21.0-1build1 [21.3 kB]
下載:19 http://ports.ubuntu.com jammy/universe arm64 python3-certbot-nginx all 1.21.0-1 [35.4 kB]
下載:20 http://ports.ubuntu.com jammy/main arm64 python3-icu arm64 2.8.1-0ubuntu2 [486 kB]
取得 1,440 kB 用了 5s (300 kB/s)      
正在預先設定套件 ...
選取了原先未選的套件 python3-openssl。
(讀取資料庫 ... 目前共安裝了 289364 個檔案和目錄。)
正在準備解包 .../00-python3-openssl_21.0.0-1_all.deb……
解開 python3-openssl (21.0.0-1) 中...
選取了原先未選的套件 python3-josepy。
正在準備解包 .../01-python3-josepy_1.10.0-1_all.deb……
解開 python3-josepy (1.10.0-1) 中...
選取了原先未選的套件 python3-certifi。
正在準備解包 .../02-python3-certifi_2020.6.20-1_all.deb……
解開 python3-certifi (2020.6.20-1) 中...
選取了原先未選的套件 python3-idna。
正在準備解包 .../03-python3-idna_3.3-1_all.deb……
解開 python3-idna (3.3-1) 中...
選取了原先未選的套件 python3-requests。
正在準備解包 .../04-python3-requests_2.25.1+dfsg-2ubuntu0.1_all.deb……
解開 python3-requests (2.25.1+dfsg-2ubuntu0.1) 中...
選取了原先未選的套件 python3-requests-toolbelt。
正在準備解包 .../05-python3-requests-toolbelt_0.9.1-1_all.deb……
解開 python3-requests-toolbelt (0.9.1-1) 中...
選取了原先未選的套件 python3-tz。
正在準備解包 .../06-python3-tz_2022.1-1ubuntu0.22.04.1_all.deb……
解開 python3-tz (2022.1-1ubuntu0.22.04.1) 中...
選取了原先未選的套件 python3-rfc3339。
正在準備解包 .../07-python3-rfc3339_1.1-3_all.deb……
解開 python3-rfc3339 (1.1-3) 中...
選取了原先未選的套件 python3-acme。
正在準備解包 .../08-python3-acme_1.21.0-1ubuntu0.1_all.deb……
解開 python3-acme (1.21.0-1ubuntu0.1) 中...
選取了原先未選的套件 python3-configargparse。
正在準備解包 .../09-python3-configargparse_1.5.3-1_all.deb……
解開 python3-configargparse (1.5.3-1) 中...
選取了原先未選的套件 python3-configobj。
正在準備解包 .../10-python3-configobj_5.0.6-5_all.deb……
解開 python3-configobj (5.0.6-5) 中...
選取了原先未選的套件 python3-parsedatetime。
正在準備解包 .../11-python3-parsedatetime_2.6-2_all.deb……
解開 python3-parsedatetime (2.6-2) 中...
選取了原先未選的套件 python3-zope.hookable。
正在準備解包 .../12-python3-zope.hookable_5.1.0-1build1_arm64.deb……
解開 python3-zope.hookable (5.1.0-1build1) 中...
選取了原先未選的套件 python3-zope.interface。
正在準備解包 .../13-python3-zope.interface_5.4.0-1build1_arm64.deb……
解開 python3-zope.interface (5.4.0-1build1) 中...
選取了原先未選的套件 python3-zope.event。
正在準備解包 .../14-python3-zope.event_4.4-3_all.deb……
解開 python3-zope.event (4.4-3) 中...
選取了原先未選的套件 python3-zope.component。
正在準備解包 .../15-python3-zope.component_4.3.0-3_all.deb……
解開 python3-zope.component (4.3.0-3) 中...
選取了原先未選的套件 python3-certbot。
正在準備解包 .../16-python3-certbot_1.21.0-1build1_all.deb……
解開 python3-certbot (1.21.0-1build1) 中...
選取了原先未選的套件 certbot。
正在準備解包 .../17-certbot_1.21.0-1build1_all.deb……
解開 certbot (1.21.0-1build1) 中...
選取了原先未選的套件 python3-certbot-nginx。
正在準備解包 .../18-python3-certbot-nginx_1.21.0-1_all.deb……
解開 python3-certbot-nginx (1.21.0-1) 中...
選取了原先未選的套件 python3-icu。
正在準備解包 .../19-python3-icu_2.8.1-0ubuntu2_arm64.deb……
解開 python3-icu (2.8.1-0ubuntu2) 中...
設定 python3-configargparse (1.5.3-1) ...
設定 python3-parsedatetime (2.6-2) ...
設定 python3-icu (2.8.1-0ubuntu2) ...
設定 python3-zope.event (4.4-3) ...
設定 python3-zope.interface (5.4.0-1build1) ...
設定 python3-openssl (21.0.0-1) ...
設定 python3-tz (2022.1-1ubuntu0.22.04.1) ...
設定 python3-zope.hookable (5.1.0-1build1) ...
設定 python3-configobj (5.0.6-5) ...
設定 python3-certifi (2020.6.20-1) ...
設定 python3-idna (3.3-1) ...
設定 python3-josepy (1.10.0-1) ...
設定 python3-rfc3339 (1.1-3) ...
設定 python3-zope.component (4.3.0-3) ...
設定 python3-requests (2.25.1+dfsg-2ubuntu0.1) ...
設定 python3-requests-toolbelt (0.9.1-1) ...
設定 python3-acme (1.21.0-1ubuntu0.1) ...
設定 python3-certbot (1.21.0-1build1) ...
設定 certbot (1.21.0-1build1) ...
Created symlink /etc/systemd/system/timers.target.wants/certbot.timer → /lib/systemd/system/certbot.timer.
設定 python3-certbot-nginx (1.21.0-1) ...
執行 man-db (2.10.2-1) 的觸發程式……
tony1966@LX2438:~$ 


3. 向 Let's Encrypt 註冊憑證 : 

指令如下 :

sudo certbot --nginx --redirect -d tony1966.cc     

此處 -d tony1966.cc 表示為我的網站域名 http://tony1966.cc 註冊憑證, 如有多個網址就在後面加 -d domain_name 即可. --redirect 表示會自動將對 http://tony1966.cc 的請求轉成 https://tony1966.cc :

tony1966@LX2438:~$ sudo certbot --nginx --redirect -d tony1966.cc    
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel): 此處輸入我的 Hinet 信箱  

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf. You must
agree in order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y     <== 必須輸入 Y 才能繼續

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y     <== 建議輸入 Y (可收到關於 Certbot 與 Let's Encrypt 消息)
Account registered.
Requesting a certificate for tony1966.cc

Successfully received certificate.     <== 收到憑證了
Certificate is saved at: /etc/letsencrypt/live/tony1966.cc/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/tony1966.cc/privkey.pem     <== 金鑰儲存位置
This certificate expires on 2024-05-20.    <== 憑證到期日 (有效期限 3 個月) 
These files will be updated when the certificate renews.     <== 到期前Certbot 會自動更新
Certbot has set up a scheduled task to automatically renew this certificate in the background.

Deploying certificate
Successfully deployed certificate for tony1966.cc to /etc/nginx/sites-enabled/default
Congratulations! You have successfully enabled HTTPS on https://tony1966.cc

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
tony1966@LX2438:~$ 

這樣便註冊與安裝好憑證了, 有效期限為 3 個月, 但 Certbot 會自動檢查是否需要更新憑證 (使用 Crontab 計時器, 每天檢查 2 次), 所以不用擔心 HTTPS 功能會因為憑證到期未更新而停擺的問題. 可以用下列指令檢查 Certbot 自動檢查機制目前的狀態 :

sudo systemctl status certbot.timer   

tony1966@LX2438:~$ sudo systemctl status certbot.timer    
● certbot.timer - Run certbot twice daily
     Loaded: loaded (/lib/systemd/system/certbot.timer; enabled; vendor preset: enabled)
     Active: active (waiting) since Tue 2024-02-20 21:12:14 CST; 25min ago
    Trigger: Wed 2024-02-21 08:06:44 CST; 10h left
   Triggers: ● certbot.service

看到 active 表示自動檢查憑證是否到期功能目前正啟動中. 

如果想要手動更新憑證, 指令如下 :

sudo certbot renew    

這樣便完成 HTTPS 憑證的註冊安裝了, 亦即我的網站已有 HTTPS 加密傳輸功能了, 馬上開啟瀏覽器測試, 在網址列輸入 http://tony1966.cc :




網址果然如預期被自動轉成 https://tony1966.cc 且正常顯示網頁, 收工啦. 


2024-02-21 補充 :

Nginx 預設的網站設定檔位於 /etc/nginx/sites-enabled 下的 default, 用 cat 瀏覽此檔, 在最底下會看到 Certbot 已經幫我們自動修改內容 : 

tony1966@LX2438:~$ cat /etc/nginx/sites-enabled/default  

... (略) ...

server {
listen 80 default_server;          <== 監聽 80 埠 (HTTP)
listen [::]:80 default_server;

... (略) ...

root /var/www/html;               <== 網站根目錄位置

# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
    server_name tony1966.cc; # managed by Certbot    

...(略)...

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot        <== 監聽 443 埠 (HTTPS)
    ssl_certificate /etc/letsencrypt/live/tony1966.cc/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/tony1966.cc/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = tony1966.cc) {
        return 301 https://$host$request_uri;     <== 將 http 自動轉成 https
    } # managed by Certbot


listen 80 ;
listen [::]:80 ;
    server_name tony1966.cc;
    return 404; # managed by Certbot


}

2020年5月30日 星期六

好站 : 雅技資訊日誌

前天向 momo 買的一本資安書籍 :

# Kali Linux滲透測試工具 第二版 (碁峰, 陳明照, 2015)


Source : 博客來


我在博客來的書籍介紹中看到作者陳明照的部落格, 拜訪之後覺得是非常優質的資安教學網站, 值得好好來學習 :

# http://atic-tw.blogspot.com/

不過這本書我買錯了, 現在已出第三版, 我第二天發現就已辦理退貨, 其實此書第二本市圖就有, 要買就買 2020 第三版.

2020年5月8日 星期五

Kali Linux 學習筆記 (二) : Nmap 套件測試

前幾天在 Micro SD 卡上燒錄了 Kali Linux v2020.1 映像檔後插入 Raspberry Pi Zero W 板子進行開機測試, 只要開啟 ssh 服務與設定 WiFi 連網, 就可以在筆電上用 Putty 連線 Pi Zero W, 利用 Kali Linux 進行安全性滲透測試了, 對象是我這台同樣連線手機基地台的 ACER Swift 5 筆電. 以後也可以用這方式對 ESP32 等物聯網終端進行資安滲透測試.





前一篇測試參考 :

# Kali Linux 學習筆記 (一) : 樹莓派 Zero W 燒錄 Kali Linux 作業系統

本篇是閱讀 "不會C也是資安高手:用Python和駭客大戰三百回合(第二版)" 第四章後在 Pi Zero W 的 Kali Linux 上進行 Nmap 實測之紀錄.

Nmap 是 Network Mapper (網路對映器) 的簡寫, 是一款優秀的網路掃描與資安稽核之自由軟體, 也是駭客手邊的必備工具, 為美國資安專家 Gordon Lyon 以 C 與 Lua 語言開發. 通常駭客使用 Nmap 蒐集目標主機之網路設定, 應用服務與作業系統資訊, 建構出一張網路的架構圖, 並從中找到可能的安全漏洞, 其基本功能如下 :
  • 掃描主機 :
    向目標主機發送封包, 根據其反應判斷是否有開機與連網.
  • 掃描通訊埠 :
    向目標主機的特定通訊埠 (預設是常用的 1660 個埠) 發送封包, 根據其反應取得這些埠之狀態 (例如是否有開啟).
  • 檢查應用程式服務類型與版本 :
    向目標主機的特定通訊埠發送封包, 根據其反應取得與此埠對映之應用程式之服務類型與版本.
  • 偵測作業系統版本 :
    向目標主機發送封包, 根據其反應取得主機類型, 作業系統類型與版本, 
此外, Nmap 具有偽造掃描者身分 (例如 IP 與 MAC 位址偽裝) 進行隱蔽掃描, 以及避開防火牆對系統進行安全性漏洞檢查等高級稽核技術, 其 NSE (Nmap Scripting Engine) 指令碼功能可用 Lua 語言自行替 Nmap 添加功能模組以擴充 Nmap 的功能, 目前指令碼已超過 350 個. 參考 :

# https://zh.wikipedia.org/wiki/Nmap

Kali Linux 內建了非常多的資安滲透工具, Nmap 就是其中之一. 其他 Linux 分散版本一般未內建 Nmap, 對 Debian 系列 Linux 系統可用下列指令安裝 :

sudo apt-get install nmap 

登入 Kali Linux 後在終端機介面下 nmap 就會顯示其指令說明 :

root@kali:~# nmap   
Nmap 7.80 ( https://nmap.org )
Usage: nmap [Scan Type(s)] [Options] {target specification}
TARGET SPECIFICATION:
  Can pass hostnames, IP addresses, networks, etc.
  Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254
  -iL <inputfilename>: Input from list of hosts/networks
  -iR <num hosts>: Choose random targets
  --exclude <host1[,host2][,host3],...>: Exclude hosts/networks
  --excludefile <exclude_file>: Exclude list from file
HOST DISCOVERY:
  -sL: List Scan - simply list targets to scan
  -sn: Ping Scan - disable port scan
  -Pn: Treat all hosts as online -- skip host discovery
  -PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP discovery to given ports
  -PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes
  -PO[protocol list]: IP Protocol Ping
  -n/-R: Never do DNS resolution/Always resolve [default: sometimes]
  --dns-servers <serv1[,serv2],...>: Specify custom DNS servers
  --system-dns: Use OS's DNS resolver
  --traceroute: Trace hop path to each host
SCAN TECHNIQUES:
  -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans
  -sU: UDP Scan
  -sN/sF/sX: TCP Null, FIN, and Xmas scans
  --scanflags <flags>: Customize TCP scan flags
  -sI <zombie host[:probeport]>: Idle scan
  -sY/sZ: SCTP INIT/COOKIE-ECHO scans
  -sO: IP protocol scan
  -b <FTP relay host>: FTP bounce scan
PORT SPECIFICATION AND SCAN ORDER:
  -p <port ranges>: Only scan specified ports
    Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
  --exclude-ports <port ranges>: Exclude the specified ports from scanning
  -F: Fast mode - Scan fewer ports than the default scan
  -r: Scan ports consecutively - don't randomize
  --top-ports <number>: Scan <number> most common ports
  --port-ratio <ratio>: Scan ports more common than <ratio>
SERVICE/VERSION DETECTION:
  -sV: Probe open ports to determine service/version info
  --version-intensity <level>: Set from 0 (light) to 9 (try all probes)
  --version-light: Limit to most likely probes (intensity 2)
  --version-all: Try every single probe (intensity 9)
  --version-trace: Show detailed version scan activity (for debugging)
SCRIPT SCAN:
  -sC: equivalent to --script=default
  --script=<Lua scripts>: <Lua scripts> is a comma separated list of
           directories, script-files or script-categories
  --script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts
  --script-args-file=filename: provide NSE script args in a file
  --script-trace: Show all data sent and received
  --script-updatedb: Update the script database.
  --script-help=<Lua scripts>: Show help about scripts.
           <Lua scripts> is a comma-separated list of script-files or
           script-categories.
OS DETECTION:
  -O: Enable OS detection
  --osscan-limit: Limit OS detection to promising targets
  --osscan-guess: Guess OS more aggressively
TIMING AND PERFORMANCE:
  Options which take <time> are in seconds, or append 'ms' (milliseconds),
  's' (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).
  -T<0-5>: Set timing template (higher is faster)
  --min-hostgroup/max-hostgroup <size>: Parallel host scan group sizes
  --min-parallelism/max-parallelism <numprobes>: Probe parallelization
  --min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>: Specifies
      probe round trip time.
  --max-retries <tries>: Caps number of port scan probe retransmissions.
  --host-timeout <time>: Give up on target after this long
  --scan-delay/--max-scan-delay <time>: Adjust delay between probes
  --min-rate <number>: Send packets no slower than <number> per second
  --max-rate <number>: Send packets no faster than <number> per second
FIREWALL/IDS EVASION AND SPOOFING:
  -f; --mtu <val>: fragment packets (optionally w/given MTU)
  -D <decoy1,decoy2[,ME],...>: Cloak a scan with decoys
  -S <IP_Address>: Spoof source address
  -e <iface>: Use specified interface
  -g/--source-port <portnum>: Use given port number
  --proxies <url1,[url2],...>: Relay connections through HTTP/SOCKS4 proxies
  --data <hex string>: Append a custom payload to sent packets
  --data-string <string>: Append a custom ASCII string to sent packets
  --data-length <num>: Append random data to sent packets
  --ip-options <options>: Send packets with specified ip options
  --ttl <val>: Set IP time-to-live field
  --spoof-mac <mac address/prefix/vendor name>: Spoof your MAC address
  --badsum: Send packets with a bogus TCP/UDP/SCTP checksum
OUTPUT:
  -oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3,
     and Grepable format, respectively, to the given filename.
  -oA <basename>: Output in the three major formats at once
  -v: Increase verbosity level (use -vv or more for greater effect)
  -d: Increase debugging level (use -dd or more for greater effect)
  --reason: Display the reason a port is in a particular state
  --open: Only show open (or possibly open) ports
  --packet-trace: Show all packets sent and received
  --iflist: Print host interfaces and routes (for debugging)
  --append-output: Append to rather than clobber specified output files
  --resume <filename>: Resume an aborted scan
  --stylesheet <path/URL>: XSL stylesheet to transform XML output to HTML
  --webxml: Reference stylesheet from Nmap.Org for more portable XML
  --no-stylesheet: Prevent associating of XSL stylesheet w/XML output
MISC:
  -6: Enable IPv6 scanning
  -A: Enable OS detection, version detection, script scanning, and traceroute
  --datadir <dirname>: Specify custom Nmap data file location
  --send-eth/--send-ip: Send using raw ethernet frames or IP packets
  --privileged: Assume that the user is fully privileged
  --unprivileged: Assume the user lacks raw socket privileges
  -V: Print version number
  -h: Print this help summary page.
EXAMPLES:
  nmap -v -A scanme.nmap.org
  nmap -v -sn 192.168.0.0/16 10.0.0.0/8
  nmap -v -iR 10000 -Pn -p 80
SEE THE MAN PAGE (https://nmap.org/book/man.html) FOR MORE OPTIONS AND EXAMPLES

可見 Kali Linux 2020.1 版搭載的是最新的 Nmap 7.8 版. 

使用 nmap 指令以 TCP 半連接方式 (收到 SYN+ACK 後不回送 ACK, 沒有完成三向握手稱為半連接, 此為隱蔽模式, 參數 -sS) 對主機進行埠掃描之指令如下 : 

root@kali:~# nmap -oX - -p 1-500 -sS 192.168.43.14    
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE nmaprun>
<?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 7.80 scan initiated Sat May  9 01:33:29 2020 as: nmap -oX - -p 1-500 -sS 192.168.43.14 -->
<nmaprun scanner="nmap" args="nmap -oX - -p 1-500 -sS 192.168.43.14" start="1588988009" startstr="Sat May  9 01:33:29 2020" version="7.80" xmloutputversion="1.04">
<scaninfo type="syn" protocol="tcp" numservices="500" services="1-500"/>
<verbose level="0"/>
<debugging level="0"/>
<host starttime="1588988009" endtime="1588988095"><status state="up" reason="arp-response" reason_ttl="0"/>
<address addr="192.168.43.14" addrtype="ipv4"/>
<address addr="1C:1B:B5:xx:xx:xx" addrtype="mac" vendor="Intel Corporate"/>
<hostnames>
<hostname name="DESKTOP-QUTGKxx" type="PTR"/>
</hostnames>
<ports><extraports state="filtered" count="500">
<extrareasons reason="no-responses" count="500"/>
</extraports>
</ports>
<times srtt="169689" rttvar="169689" to="848445"/>
</host>
<runstats><finished time="1588988096" timestr="Sat May  9 01:34:56 2020" elapsed="87.24" summary="Nmap done at Sat May  9 01:34:56 2020; 1 IP address (1 host up) scanned in 87.24 seconds" exit="success"/><hosts up="1" down="0" total="1"/>
</runstats>
</nmaprun>

掃描結果會以 XML 格式傳回, 裡面有 192.168.43.14 這台主機的電腦名稱 (hostname), MAC 位址 (address), 以及 CPU 製造商 (vender) 等資訊. 更多的 nmap 指令用法參考 : 

資工專家 Alexsandre Norman 把 Nmap 打包整合成名為 python-nmap 的 Python 套件, 讓熟悉 Python 的程式員可利用此 API 調用 Nmap 進行安全性滲透測試, 但是 Kali Linux 預設並未搭載此套件, 需自行安裝. 參考 :

# https://pypi.org/project/python-nmap/
# https://github.com/alexandrenorman


1. 安裝 pyhton-nmap 套件 : 

root@kali:~# pip3 install python-nmap 
Collecting python-nmap
Building wheels for collected packages: python-nmap
  Running setup.py bdist_wheel for python-nmap ... done
  Stored in directory: /root/.cache/pip/wheels/bb/a6/48/4d9e2285291b458c3f17064b1dac2f2fb0045736cb88562854
Successfully built python-nmap
Installing collected packages: python-nmap
Successfully installed python-nmap-0.6.1

可見目前最新是 0.6.1 版. 安裝完成就可以進入 Python shell 將 nmap 模組匯入 :

root@kali:~# python3 
Python 3.7.5 (default, Oct 27 2019, 15:43:29)
[GCC 9.2.1 20191022] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import nmap          #匯入 nmap 模組
>>> dir(nmap)
['ET', 'PortScanner', 'PortScannerAsync', 'PortScannerError', 'PortScannerHostDict', 'PortScannerYield', 'Process', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__last_modification__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'convert_nmap_output_to_encoding', 'csv', 'io', 'nmap', 'os', 're', 'shlex', 'subprocess', 'sys']

可見此模組本身使用了 csv, io, re, sys 等內建模組, 主角是 PortScanner (同步) 與 PortScannerAsync (非同步) 等類別. 不過這是套件結構中的捷徑, 實際的類別放在下一層的 nmap.nmap 中 :

>>> dir(nmap.nmap) 
['ET', 'PortScanner', 'PortScannerAsync', 'PortScannerError', 'PortScannerHostDict', 'PortScannerYield', 'Process', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__get_last_online_version', '__last_modification__', '__loader__', '__name__', '__package__', '__scan_progressive__', '__spec__', '__version__', 'convert_nmap_output_to_encoding', 'csv', 'io', 'os', 're', 'shlex', 'subprocess', 'sys']

與上面 dir(nmap) 結果是一樣的. 接下來就可以呼叫 PortScanner 類別的建構子 PortScanner() 進行通訊埠掃描測試了.


2. 掃描通訊埠 : 

呼叫 nmap.PortScanner() 函數可掃描指定主機的通訊埠, 其參數格式如下 :

nmap.PortScanner('主機網址', '通訊埠範圍', arguments='掃描類型參數')

這三個參數都是字串, 其中通訊埠範圍用 'from-to' 表示, 例如 '1-500' 表示掃描通訊埠 1~500. arguments 為下面是從 Pi Zero W 掃描我的筆電的結果 :

>>> nm=nmap.PortScanner()   
>>> type(nm) 
<class 'nmap.nmap.PortScanner'>
>>> nm.scan('192.168.43.14', '1-500', '-sS') 
{'nmap': {'command_line': 'nmap -oX - -p 1-500 -sS 192.168.43.14', 'scaninfo': {'tcp': {'method': 'syn', 'services': '1-500'}}, 'scanstats': {'timestr': 'Fri May  8 07:00:00 2020', 'elapsed': '24.98', 'uphosts': '1', 'downhosts': '0', 'totalhosts': '1'}}, 'scan': {'192.168.43.14': {'hostnames': [{'name': 'DESKTOP-QUTGKxx', 'type': 'PTR'}], 'addresses': {'ipv4': '192.168.43.14', 'mac': '1C:1B:B5:xx:xx:xx'}, 'vendor': {'1C:1B:B5:xx:xx:xx': 'Intel Corporate'}, 'status': {'state': 'up', 'reason': 'arp-response'}}}}

可見呼叫 PortScanner() 會傳回一個 PortScanner 物件, 而呼叫此物件的 scan() 方法會送出對應的 Nmap 指令, 並將 Nmap 回應之 XML 資料轉成一個字典傳回來, 其中鍵 command_line 之值即 python-nmap 套件送出的真正 Nmap 指令, 這指令也可以呼叫 command_line() 方法取得 :

>>> nm.command_line() 
'nmap -oX - -p 1-500 -sS 192.168.43.14'

用 dir() 指令可查詢 PortScanner 物件的方法

>>> dir(nm) 
['_PortScanner__process', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_nmap_last_output', '_nmap_path', '_nmap_subversion_number', '_nmap_version_number', '_scan_result', 'all_hosts', 'analyse_nmap_xml_scan', 'command_line', 'csv', 'get_nmap_last_output', 'has_host', 'listscan', 'nmap_version', 'scan', 'scaninfo', 'scanstats']

摘要如下表 :


 PortScanner 物件之方法 說明
 scan(ip, ports, arguments) 掃描主機之通訊埠, 傳回字典
 command_line() 傳回對應之 Nmap 指令字串
 csv() 傳回以分號隔開的 csv 格式掃描回應字串
 scaninfo() 傳回掃描資訊 (字典), 例如 tcp/udp, 半連接等
 hostname() 傳回主機名稱 (字串)
 all_hosts() 傳回被掃瞄之主機 IP (串列)
 has_host(ip) 檢查是否有主機之掃描結果 (True/False)


例如 :

>>> nm.scan('192.168.43.14', '1-500', '-sS') 
{'nmap': {'command_line': 'nmap -oX - -p 1-500 -sS 192.168.43.14', 'scaninfo': {'tcp': {'method': 'syn', 'services': '1-500'}}, 'scanstats': {'timestr': 'Sat May  9 04:57:29 2020', 'elapsed': '13.29', 'uphosts': '1', 'downhosts': '0', 'totalhosts': '1'}}, 'scan': {'192.168.43.14': {'hostnames': [{'name': 'DESKTOP-QUTGKxx', 'type': 'PTR'}], 'addresses': {'ipv4': '192.168.43.14', 'mac': '1C:1B:B5:xx:xx:xx'}, 'vendor': {'1C:1B:B5:xx:xx:xx': 'Intel Corporate'}, 'status': {'state': 'up', 'reason': 'arp-response'}}}}
>>> nm.all_hosts() 
['192.168.43.14']
>>> nm.csv() 
'host;hostname;hostname_type;protocol;port;name;state;product;extrainfo;reason;version;conf;cpe\r\n'
>>> nm.has_host('192.168.43.14') 
True
>>> nm.has_host('192.168.43.15') 
False
>>> nm.scaninfo() 
{'tcp': {'method': 'syn', 'services': '1-500'}}
>>> nm.all_hosts() 
['192.168.43.14']
>>> nm.nmap_version() 
(7, 80)
>>> nm.listscan() 
['127.0.0.1']
>>> nm.scanstats() 
{'timestr': 'Sat May  9 05:44:45 2020', 'elapsed': '0.01', 'uphosts': '0', 'downhosts': '1', 'totalhosts': '1'}
>>> nm.get_nmap_last_output()
'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE nmaprun>\n<?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?>\n<!-- Nmap 7.80 scan initiated Sat May  9 05:44:45 2020 as: nmap -oX - -sL 127.0.0.1 -->\n<nmaprun scanner="nmap" args="nmap -oX - -sL 127.0.0.1" start="1589003085" startstr="Sat May  9 05:44:45 2020" version="7.80" xmloutputversion="1.04">\n<verbose level="0"/>\n<debugging level="0"/>\n<host><status state="unknown" reason="user-set" reason_ttl="0"/>\n<address addr="127.0.0.1" addrtype="ipv4"/>\n<hostnames>\n<hostname name="kali" type="PTR"/>\n</hostnames>\n</host>\n<runstats><finished time="1589003085" timestr="Sat May  9 05:44:45 2020" elapsed="0.01" summary="Nmap done at Sat May  9 05:44:45 2020; 1 IP address (0 hosts up) scanned in 0.01 seconds" exit="success"/><hosts up="0" down="1" total="1"/>\n</runstats>\n</nmaprun>\n'
>>>

上面傳入 '-sS' 掃描類型參數表示對目標主機進行半開通訊埠掃描, 回應資料包括了電腦名稱與 MAC 位址等主機資訊. 可用的掃描類型參數如下表 :


 掃描類型參數 說明
 '-sP' 對目標主機進行 ping 掃描
 '-PR' 對目標主機進行 ARP 掃描
 '-sS' 對目標主機進行半連接 TCP 通訊埠掃描
 '-sT'  對目標主機進行全連接 TCP 通訊埠掃描
 '-sU' 對目標主機進行 UDP 通訊埠掃描
 '-sV' 掃描目標主機所安裝之網路服務軟體版本
 '-O' 掃描目標主機之作業系統資訊


測試結果如下 :

>>> nm.scan('192.168.43.14', '1-500', '-sV') 
{'nmap': {'command_line': 'nmap -oX - -p 1-500 -sV 192.168.43.14', 'scaninfo': {'tcp': {'method': 'syn', 'services': '1-500'}}, 'scanstats': {'timestr': 'Fri May  8 15:43:21 2020', 'elapsed': '19.16', 'uphosts': '1', 'downhosts': '0', 'totalhosts': '1'}}, 'scan': {'192.168.43.14': {'hostnames': [{'name': 'DESKTOP-QUTGKxx', 'type': 'PTR'}], 'addresses': {'ipv4': '192.168.43.14', 'mac': '1C:1B:B5:66:xx:xx'}, 'vendor': {'1C:1B:B5:66:xx:xx': 'Intel Corporate'}, 'status': {'state': 'up', 'reason': 'arp-response'}}}}
>>> nm.scan('192.168.43.14', '1-500', '-PR') 
{'nmap': {'command_line': 'nmap -oX - -p 1-500 -PR 192.168.43.14', 'scaninfo': {'tcp': {'method': 'syn', 'services': '1-500'}}, 'scanstats': {'timestr': 'Fri May  8 15:46:01 2020', 'elapsed': '12.33', 'uphosts': '1', 'downhosts': '0', 'totalhosts': '1'}}, 'scan': {'192.168.43.14': {'hostnames': [{'name': 'DESKTOP-QUTGKxx', 'type': 'PTR'}], 'addresses': {'ipv4': '192.168.43.14', 'mac': '1C:1B:B5:66:xx:xx'}, 'vendor': {'1C:1B:B5:66:xx:xx': 'Intel Corporate'}, 'status': {'state': 'up', 'reason': 'arp-response'}}}}
>>> nm.scan('192.168.43.14', '1-500', '-sT')   
{'nmap': {'command_line': 'nmap -oX - -p 1-500 -sT 192.168.43.14', 'scaninfo': {'tcp': {'method': 'connect', 'services': '1-500'}}, 'scanstats': {'timestr': 'Fri May  8 15:47:02 2020', 'elapsed': '12.26', 'uphosts': '1', 'downhosts': '0', 'totalhosts': '1'}}, 'scan': {'192.168.43.14': {'hostnames': [{'name': 'DESKTOP-QUTGKxx', 'type': 'PTR'}], 'addresses': {'ipv4': '192.168.43.14', 'mac': '1C:1B:B5:66:xx:xx'}, 'vendor': {'1C:1B:B5:66:xx:xx': 'Intel Corporate'}, 'status': {'state': 'up', 'reason': 'arp-response'}}}}
>>> nm.scan('192.168.43.14', '1-500', '-sP')   
{'nmap': {'command_line': None, 'scaninfo': {'error': ['You cannot use -F (fast scan) or -p (explicit port selection) when not doing a port scan\nQUITTING!\n', 'You cannot use -F (fast scan) or -p (explicit port selection) when not doing a port scan\nQUITTING!\n']}, 'scanstats': {'timestr': 'Fri May  8 15:47:57 2020', 'elapsed': '0.01', 'uphosts': '0', 'downhosts': '0', 'totalhosts': '0'}}, 'scan': {}}
>>> nm.scan('192.168.43.14', '1-500', '-sU') 
{'nmap': {'command_line': 'nmap -oX - -p 1-500 -sU 192.168.43.14', 'scaninfo': {'udp': {'method': 'udp', 'services': '1-500'}}, 'scanstats': {'timestr': 'Sat May  9 04:43:45 2020', 'elapsed': '35.95', 'uphosts': '1', 'downhosts': '0', 'totalhosts': '1'}}, 'scan': {'192.168.43.14': {'hostnames': [{'name': 'DESKTOP-QUTGKxx', 'type': 'PTR'}], 'addresses': {'ipv4': '192.168.43.14', 'mac': '1C:1B:B5:xx:xx:xx'}, 'vendor': {'1C:1B:B5:xx:xx:xx': 'Intel Corporate'}, 'status': {'state': 'up', 'reason': 'arp-response'}, 'udp': {137: {'state': 'open', 'reason': 'udp-response', 'name': 'netbios-ns', 'product': '', 'version': '', 'extrainfo': '', 'conf': '3', 'cpe': ''}}}}}
>>> nm.scan('192.168.43.14', arguments='-O')
{'nmap': {'command_line': 'nmap -oX - -O 192.168.43.14', 'scaninfo': {'tcp': {'method': 'syn', 'services': '1,3-4,6-7,9,13,17,19-26,30,32-33,37,42-43,49,53,70,79-85,88-90,99-100,106,109-111,113,119,125,135,139,143-144,146,161,163,179,199,211-212,222,254-256,259,264,280,301,306,311,340,366,389,406-407,416-417,425,427,443-445,458,464-465,481,497,500,512-515,524,541,543-545,548,554-555,563,587,593,616-617,625,631,636,646,648,666-668,683,687,691,700,705,711,714,720,722,726,749,765,777,783,787,800-801,808,843,873,880,888,898,900-903,911-912,981,987,990,992-993,995,999-1002,1007,1009-1011,1021-1100,1102,1104-1108,1110-1114,1117,1119,1121-1124,1126,1130-1132,1137-1138,1141,1145,1147-1149,1151-1152,1154,1163-1166,1169,1174-1175,1183,1185-1187,1192,1198-1199,1201,1213,1216-1218,1233-1234,1236,1244,1247-1248,1259,1271-1272,1277,1287,1296,1300-1301,1309-1311,1322,1328,1334,1352,1417,1433-1434,1443,1455,1461,1494,1500-1501,1503,1521,1524,1533,1556,1580,1583,1594,1600,1641,1658,1666,1687-1688,1700,1717-1721,1723,1755,1761,1782-1783,1801,1805,1812,1839-1840,1862-1864,1875,1900,1914,1935,1947,1971-1972,1974,1984,1998-2010,2013,2020-2022,2030,2033-2035,2038,2040-2043,2045-2049,2065,2068,2099-2100,2103,2105-2107,2111,2119,2121,2126,2135,2144,2160-2161,2170,2179,2190-2191,2196,2200,2222,2251,2260,2288,2301,2323,2366,2381-2383,2393-2394,2399,2401,2492,2500,2522,2525,2557,2601-2602,2604-2605,2607-2608,2638,2701-2702,2710,2717-2718,2725,2800,2809,2811,2869,2875,2909-2910,2920,2967-2968,2998,3000-3001,3003,3005-3007,3011,3013,3017,3030-3031,3052,3071,3077,3128,3168,3211,3221,3260-3261,3268-3269,3283,3300-3301,3306,3322-3325,3333,3351,3367,3369-3372,3389-3390,3404,3476,3493,3517,3527,3546,3551,3580,3659,3689-3690,3703,3737,3766,3784,3800-3801,3809,3814,3826-3828,3851,3869,3871,3878,3880,3889,3905,3914,3918,3920,3945,3971,3986,3995,3998,4000-4006,4045,4111,4125-4126,4129,4224,4242,4279,4321,4343,4443-4446,4449,4550,4567,4662,4848,4899-4900,4998,5000-5004,5009,5030,5033,5050-5051,5054,5060-5061,5080,5087,5100-5102,5120,5190,5200,5214,5221-5222,5225-5226,5269,5280,5298,5357,5405,5414,5431-5432,5440,5500,5510,5544,5550,5555,5560,5566,5631,5633,5666,5678-5679,5718,5730,5800-5802,5810-5811,5815,5822,5825,5850,5859,5862,5877,5900-5904,5906-5907,5910-5911,5915,5922,5925,5950,5952,5959-5963,5987-5989,5998-6007,6009,6025,6059,6100-6101,6106,6112,6123,6129,6156,6346,6389,6502,6510,6543,6547,6565-6567,6580,6646,6666-6669,6689,6692,6699,6779,6788-6789,6792,6839,6881,6901,6969,7000-7002,7004,7007,7019,7025,7070,7100,7103,7106,7200-7201,7402,7435,7443,7496,7512,7625,7627,7676,7741,7777-7778,7800,7911,7920-7921,7937-7938,7999-8002,8007-8011,8021-8022,8031,8042,8045,8080-8090,8093,8099-8100,8180-8181,8192-8194,8200,8222,8254,8290-8292,8300,8333,8383,8400,8402,8443,8500,8600,8649,8651-8652,8654,8701,8800,8873,8888,8899,8994,9000-9003,9009-9011,9040,9050,9071,9080-9081,9090-9091,9099-9103,9110-9111,9200,9207,9220,9290,9415,9418,9485,9500,9502-9503,9535,9575,9593-9595,9618,9666,9876-9878,9898,9900,9917,9929,9943-9944,9968,9998-10004,10009-10010,10012,10024-10025,10082,10180,10215,10243,10566,10616-10617,10621,10626,10628-10629,10778,11110-11111,11967,12000,12174,12265,12345,13456,13722,13782-13783,14000,14238,14441-14442,15000,15002-15004,15660,15742,16000-16001,16012,16016,16018,16080,16113,16992-16993,17877,17988,18040,18101,18988,19101,19283,19315,19350,19780,19801,19842,20000,20005,20031,20221-20222,20828,21571,22939,23502,24444,24800,25734-25735,26214,27000,27352-27353,27355-27356,27715,28201,30000,30718,30951,31038,31337,32768-32785,33354,33899,34571-34573,35500,38292,40193,40911,41511,42510,44176,44442-44443,44501,45100,48080,49152-49161,49163,49165,49167,49175-49176,49400,49999-50003,50006,50300,50389,50500,50636,50800,51103,51493,52673,52822,52848,52869,54045,54328,55055-55056,55555,55600,56737-56738,57294,57797,58080,60020,60443,61532,61900,62078,63331,64623,64680,65000,65129,65389'}}, 'scanstats': {'timestr': 'Sat May  9 00:17:08 2020', 'elapsed': '165.53', 'uphosts': '1', 'downhosts': '0', 'totalhosts': '1'}}, 'scan': {'192.168.43.14': {'hostnames': [{'name': 'DESKTOP-QUTGKxx', 'type': 'PTR'}], 'addresses': {'ipv4': '192.168.43.14', 'mac': '1C:1B:B5:xx:xx:xx'}, 'vendor': {'1C:1B:B5:xx:xx:xx': 'Intel Corporate'}, 'status': {'state': 'up', 'reason': 'arp-response'}, 'tcp': {5357: {'state': 'open', 'reason': 'syn-ack', 'name': 'wsdapi', 'product': '', 'version': '', 'extrainfo': '', 'conf': '3', 'cpe': ''}}, 'portused': [{'state': 'open', 'proto': 'tcp', 'portid': '5357'}], 'osmatch': [{'name': 'AVtech Room Alert 26W environmental monitor', 'accuracy': '87', 'line': '9077', 'osclass': [{'type': 'specialized', 'vendor': 'AVtech', 'osfamily': 'embedded', 'osgen': None, 'accuracy': '87', 'cpe': []}]}, {'name': 'Microsoft Windows XP SP2', 'accuracy': '87', 'line': '81128', 'osclass': [{'type': 'general purpose', 'vendor': 'Microsoft', 'osfamily': 'Windows', 'osgen': 'XP', 'accuracy': '87', 'cpe': ['cpe:/o:microsoft:windows_xp::sp2']}]}, {'name': 'FreeBSD 6.2-RELEASE', 'accuracy': '86', 'line': '27364', 'osclass': [{'type': 'general purpose', 'vendor': 'FreeBSD', 'osfamily': 'FreeBSD', 'osgen': '6.X', 'accuracy': '86', 'cpe': ['cpe:/o:freebsd:freebsd:6.2']}]}, {'name': 'FreeBSD 10.3-STABLE', 'accuracy': '85', 'line': '26140', 'osclass': [{'type': 'general purpose', 'vendor': 'FreeBSD', 'osfamily': 'FreeBSD', 'osgen': '10.X', 'accuracy': '85', 'cpe': ['cpe:/o:freebsd:freebsd:10.3']}]}]}}}

另外也可以用 nm 字典鍵擷取資訊 :

>>> nm['192.168.43.14'].all_protocols()   
[]
>>> nm['192.168.43.14'].state() 
'up'
>>> nm['192.168.43.14'].hostname()   
'DESKTOP-QUTGKxx'
>>> nm['192.168.43.14']['tcp'].keys() 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'tcp'
>>> nm['192.168.43.14'].all_tcp()   
[]
>>> nm['192.168.43.14'].all_udp()   
[]
>>> nm['192.168.43.14'].all_sctp() 
[]
>>> nm['192.168.43.14'].has_tcp(22) 
False

但以下這幾個不知為何有錯誤 :

>>> nm['192.168.43.14']['tcp'][22] 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'tcp'
>>> nm['192.168.43.14'].tcp(22)   
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/dist-packages/nmap/nmap.py", line 975, in tcp
    return self['tcp'][port]
KeyError: 'tcp'
>>> nm['192.168.43.14']['tcp'][22]['state']   
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'tcp'
>>>


參考 :

# 黑客終極網絡掃描工具Zenmap使用方法

2020年5月5日 星期二

Kali Linux 學習筆記 (一) : 樹莓派 Zero W 燒錄 Kali Linux 作業系統

4/30 在 momo 買了下面這本書 :

# 不會C也是資安高手:用Python和駭客大戰三百回合(第二版)


Source : 博客來


此書第二章介紹資安滲透測試最常用的作業系統 : Kali Linux, 我想能否在樹莓派上面安裝 Kali Linux 呢? 答案是可以的, Kali Linux 有推出 ARM 架構的版本, 特別是有支援 Raspberry Pi Zero W, 參考 :

# 在樹莓派上安裝Kali Linux並進行設置分步教程
# Raspberry Pi 安裝 Kali Linux 當隨身漏洞檢測和網路工具盒

樹莓派測試筆記索引參考 :

# 樹莓派 Raspberry Pi 文章列表
# 樹莓派常用的 Linux 指令

1. 下載 Kali Linux 映像檔 :

先到下列網址, 點選 "RaspberryPi Foundation" :

# https://www.offensive-security.com/kali-linux-arm-images/

再點選 "Image Name" 欄位中的 "Kali Linux Raspberry Pi Zero/Zero W " 即可下載 .xz 映像檔, 我下載的是 kali-linux-2020.1-rpi0w-nexmon.zx (大小約 721 MB) :

# Kali Linux image for Raspberry Pi Zero/Zero W




將下載下來的 .xz 檔案解壓縮為 .img 映像檔 (約 7.2GB, 可用 Bandizip 軟體) :

kali-linux-2020.1-rpi0w-nexmon.img


2. 燒錄 Kali Linux 映像檔 :

準備一張 8GB 以上的 MicroSD 卡, 先用 Win 10 的格式化功能或 SDFormatter 將其格式化為 FAT16 格式, 再用 Win32 Disk Imager 將映像檔寫入, 參考 :

# 樹莓派重新安裝 Raspbian 作業系統





燒錄完成後取出 MicroSD 卡插入 Raspberry Pi Zero W 中, 準備做開機設定.


3. Kali Linux 開機與 SSH 設定 : 

將 Raspberry Pi Zero W 接好 Mini HDMI 與鍵鼠組之 USB Dongle :




左邊黑色接頭是 Mini-HDMI 轉 HDMI, 中間白色線接鍵鼠組 Dongle, 右邊橘色線是電源. 插電開機後, 螢幕會跑一堆開機檢測, 最後顯示 Kali Linux 的登入提示, 預設管理帳號為 root, 密碼為 toor :

login: root
password: toor

出現提示號表示登入成功, 用 uname 指令檢查版本與 CPU 架構 :

root@kali:~# uname -a 
Linux kali 4.19.93-Re4son+ #1 Wed Jan 8 14:55:22 AEDT 2020 armv6l GNU/Linux
root@kali:~# lsb_release -a 
-bash: lsb_release: command not found
root@kali:~# startx 
-bash: startx: command not found

可見 Kali Linux 版本是 4.19.93, CPU 是 armv61 架構, 沒有 lsb_release 指令, 預設是 CLI 介面, 沒有搭載 GUI 環境 (例如 Gnome), 需另行安裝. 

首先需設定 SSH 以利進行無頭存取 (headless access), 亦即利用筆電或 PC 透過 SSH 管理樹莓派, 這樣就不需要將樹莓派接上螢幕與鍵鼠組了, 可用 nano 或 vim 編輯器編輯 /etc/ssh/sshd_config 這個檔案 :

root@kali:~# nano /etc/ssh/sshd_config 

找尋 PermitRootLogin 與 PasswordAuthentication 這兩個參數, 將其前面的注釋 # 字元刪除, 變成如下設定 :  

PermitRootLogin yes
PasswordAuthentication yes

然後用下列兩指令重啟 SSH 功能以及開機自動開啟 SSH :

root@kali:~# service ssh restart   
root@kali:~# update-rc.d ssh enable   

這樣 ssh 服務就打開了, 但還缺個東西才能進行無頭存取 : 連上網路. Raspberry Pi Zero W 有內建 WiFi, 我們只要設定好無線網路 wlan0 即可連網.


4. 設定無線網路連線 :

Raspberry Pi Zero W 內建無線網路介面 (wlan0), 我們只要設定好無線網路 wlan0 即可連網. 以下是手動設定方式 :

首先停掉 network-manager 服務 :

root@kali:~# service network-manager stop 

然後產生無線網路設定檔 wpa.conf 用來連線無線基地台, 指令語法如下 :

wpa_passphrase SSID PASSWORD > wpa.conf

因為我都使用手機行動網路, 因此輸入手機的 SSID 與網路連線密碼 :

root@kali:~# wpa_passphrase TonyNote8 123456 > wpa.conf

這樣就可以用下列指令來連線基地台了 :

root@kali:~#  wpa_supplicant -i wlan0 -B -c wpa.cong

最後用 dhclient 要求為 wlan0 分配 IP :

root@kali:~#  dhclient wlan0

用 ifconfig 指令檢查 IP :

root@kali:~# ifconfig




可見 inet 欄位值已經變成 IP, 這樣就可以從位於同一網段的 PC 或筆電用 Putty 以 SSH 連線樹莓派進行遠端無頭存取了 :

login as: root 
root@192.168.43.10's password: toor
Linux kali 4.19.93-Re4son+ #1 Wed Jan 8 14:55:22 AEDT 2020 armv6l

The programs included with the Kali GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Kali GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Fri Nov 29 16:49:55 2019
root@kali:~#

不過上面都是手動連線基地台的方法, 每次重開機都要來一次很不方便, 可以編輯 /etc/network/interfaces 網路介面檔設定每次開機後固定連線某個基地台 (例如手機行動網路分享), 參考下列文章做法 :

# 樹莓派的 Wifi 設定 : 使用迅捷 FW150US

用 cat 指令檢視 Kali Linux 的 /etc/network/interfaces 原始內容只有 loopback 而已 :

root@kali:~# cat /etc/network/interfaces   
auto lo
iface lo inet loopback

用 nano 或 vim 編輯 /etc/network/interfaces, 加入如下連線 WiFi 網路部分 :

allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
wpa-ssid "無線基地台 SSID"
wpa-psk "無線基地台連線密碼"

完成後檢視如下 :

root@kali:~# nano /etc/network/interfaces
root@kali:~# cat /etc/network/interfaces   
auto lo
iface lo inet loopback

allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
wpa-ssid "TonyNote8"
wpa-psk "123456"

然後重開機 :

root@kali:~# reboot

用 ifconfig 檢查果然已自動連線 WiFi 基地台 :

root@kali:~# ifconfig
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 282  bytes 87248 (85.2 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 282  bytes 87248 (85.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.43.222  netmask 255.255.255.0  broadcast 192.168.43.255
        inet6 2001:b400:e705:97e7:ba27:ebff:fe18:6a95  prefixlen 64  scopeid 0x0<global>
        inet6 fe80::ba27:ebff:fe18:6a95  prefixlen 64  scopeid 0x20<link>
        ether b8:27:eb:18:6a:95  txqueuelen 1000  (Ethernet)
        RX packets 216850  bytes 316088403 (301.4 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 59544  bytes 6528293 (6.2 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

可見已獲得基地台 DHCP 伺服器指派 192.168.43.222 這個 IP 了.

不過每次連線可能會被指配不同 IP, 在無頭存取情況下 (手邊無螢幕) 無法得知 IP, 應該要求 DHCP 指派一個固定 IP, 這樣就不需要先檢查 IP 了. 作法是編輯 DHCP 設定檔 /etc/dhcpcd.conf, 加入固定 IP 即可, 參考 :

# 樹莓派 Wifi 固定 IP 的新作法

檢視此檔案發現 Kali Linux 並無此檔案 :

root@kali:~# cat /etc/dhcpcd.conf 
cat: /etc/dhcpcd.conf: No such file or directory

用 nano 或 vim 編輯此檔, 加入如下設定 :

interface wlan0
static ip_address=192.168.43.192
static routers=192.168.43.1
static domain_name_servers=192.168.43.1

其中 192.168.43.192 是我想要 DHCP 指派的固定 IP (我手機內網為 192.168.43.xxx 網段), 存檔後檢視內容如下 :

root@kali:~# nano /etc/dhcpcd.conf 
root@kali:~# cat /etc/dhcpcd.conf 
interface wlan0
static ip_address=192.168.43.192
static routers=192.168.43.1
static domain_name_servers=192.168.43.1

但是重開機後無效, 還是被指派 192.168.43.222 的 IP. 這是我前一次安裝 Rasbian 後找到有效的新作法, 顯然在 Kali Linux 不是用這方式 (或許 dhcpcd.conf 作法在最新版 Rasbian 說不定也過時了, 最近來更新看看).

我又參考了下面這篇文章做法, 直接在 /etc/network/interfaces 指定固定 IP, 這是比 dhcpcd.conf 更早的做法 :

# Kali Linux 設定IP
# Raspberry Pi:固定私有IP與dhcpcd - 葉難

root@kali:~# nano /etc/network/interfaces 
root@kali:~# cat /etc/network/interfaces   
auto lo
iface lo inet loopback

allow-hotplug wlan0
auto wlan0

iface wlan0 inet static
address 192.168.43.192
netmask 255.255.255.0
gateway 192.168.43.1
wpa-ssid "TonyNote8"
wpa-psk "123456"
root@kali:~# reboot 

同樣也是沒有用, 甚至更慘, 完全沒連線 (192.168.43.222 也沒了), Why? 難道手機基地台本身就不理會固定 IP 的要求? 這有空再研究. 反正要用 SSH 連線時查一下手機就知道 IP 了.


5. 測試 Python :

這本書使用 Python 語言, Kali Linux 同時搭載了 Python 2 與 Python 3, 直接輸入 python 進入 Python 2 Shell, 輸入 python3 則進入 Python 3 Shell :

root@kali:~# python 
Python 2.7.17 (default, Oct 19 2019, 23:36:22)
[GCC 9.2.1 20191008] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'ok' 
ok
>>> exit() 
root@kali:~# python3 
Python 3.8.2 (default, Apr  1 2020, 15:39:53)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('ok') 
ok

可見此版 Kali Linux 都是搭載最新的 Python 版本.

用 pip 檢查已安裝的 Python 套件 :

root@kali:~# pip3 list 
Package          Version
---------------- --------------
aiodns           2.0.0
asn1crypto       0.24.0
beautifulsoup4   4.8.2
blinker          1.4
certifi          2019.11.28
chardet          3.0.4
Click            7.0
click-plugins    1.1.1
colorama         0.4.3
configobj        5.0.6
cryptography     2.6.1
dbus-python      1.2.16
decorator        4.3.0
dicttoxml        1.7.4
dnspython        1.16.0
entrypoints      0.3
Flask            1.1.1
gevent           1.4.0
gpg              1.13.1-unknown
greenlet         0.4.15
grequests        0.4.0
html5lib         1.0.1
idna             2.6
ipython-genutils 0.2.0
itsdangerous     0.24
Jinja2           2.10.1
jsonschema       2.6.0
jupyter-core     4.6.1
keyring          18.0.1
keyrings.alt     3.2.0
lxml             4.4.2
MarkupSafe       1.1.0
mechanize        0.4.5
nbformat         5.0.3
netaddr          0.7.19
pip              18.1
plotly           4.4.1
pycares          3.1.1
pycrypto         2.6.1
PyGObject        3.34.0
pyinotify        0.9.6
pyOpenSSL        19.0.0
python-magic     0.4.16
pytz             2019.3
pyxdg            0.26
PyYAML           5.3
requests         2.22.0
retrying         1.3.3
RPi.GPIO         0.6.5
SecretStorage    2.3.1
setuptools       44.0.0
shodan           1.21.2
simplejson       3.16.0
six              1.13.0
soupsieve        1.9.5
texttable        1.6.2
theHarvester     3.1.0
traitlets        4.3.3
unicodecsv       0.14.1
urllib3          1.25.6
webencodings     0.5.1
Werkzeug         0.16.0
wheel            0.33.6
XlsxWriter       1.1.2


6. 關於桌面系統 :

Raspberry Pi Zero 版的 Kali Linux 預設沒有桌面系統, 開機就只有 CLI 介面而已, 執行 startx 回應 command not found 訊息, 應該是沒有搭載桌面系統. 我參考下面文章安裝 gnome 後發現開機不久一定會進入 gnome 畫面, 而且用預設帳密 root 與 toor 無法登入, 所以還是重新格式化 SD 卡重新回到 CLI 介面.

# Kali linux desktop not loading
# Kali Linux won't boot to GUI

root@kali:~# sudo apt-get install gnome    (安裝很久)

其實資安用途的 Kali Linux 主要是 CLI 操作, 桌面系統其實不重要.

總結以上測試, 燒錄完映像檔開機後, 只要編輯 /etc/ssh/sshd_config 與 /etc/network/interfaces 這兩個檔案就可以開始使用 Kali Linux 了 :

$ nano /etc/ssh/sshd_config

PermitRootLogin yes
PasswordAuthentication yes

$ service ssh restart
$ update-rc.d ssh enable

$ nano /etc/network/interfaces

auto lo
iface lo inet loopback

allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
wpa-ssid "TonyNote8"
wpa-psk "123456"


7. 查詢 IP 以便進行無頭存取 :

經過上面的 WiFi 連線設定後, 只要打開手機基地台分享, 則 Pi Zero W 開機後便會自動透過手機 WiFi 連接網路, 只要筆電也一樣連接手機基地台, 就可以利用筆電對 Pi Zero W 進行無頭存取, 完全不需要接螢幕與鍵鼠組.

首先必須從手機查詢 Pi Zero W 所獲得的 IP, 進入手機的 "設定/連接" :




點 "行動無線基地台與網路共享" :




點 "行動無線基地台" :




拉到最底下 "以連接的設備" 會找到 "kali" :




點 "kali" 即可查知 Pi Zero W 的 IP 位址了 :




這樣就可以用 Putty 來進行無頭存取了 :




參考 :

# Kali Linux won't boot to GUI
# How to boot Kali Linux in GUI mode


2020-05-06 補充 :

關於固定 IP 設定, 或許可參考下面這篇做法試試看 :

# 將樹莓派 (Raspberry Pi) 的 eth0 / wlan0 網路介面設定固定 IP

2020-05-08 補充 :

我照上面那篇測試, 發現卡在啟動 dhcpcd 服務上, 作者原文 :

"前提是 dhcpcd 和 networking 要開機時就預設啟動,指令如下:
systemctl enable dhcpcd
systemctl enable networking"

啟動 networking 沒問題, 但啟動 dhcpcd 卻有問題, 說這個服務不存在 :

root@kali:~# systemctl enable dhcpcd 
Failed to enable unit: Unit file dhcpcd.service does not exist.

我參考下列文章去安裝 dhcpcd5 卻失敗 :

# How to manually install dhcpcd?
# http://manpages.ubuntu.com/manpages/trusty/man8/dhcpcd5.8.html
# Setup DHCP or static IP address from command line in Linux
# Kali Linux常用服務配置教程安裝及配置DHCP服務
# 設定 Kali Linux 取得 DHCP IP

root@kali:~# sudo apt-get install dhcpcd5
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package dhcpcd5

沒時間去研究問題在哪, 所以就這樣吧, 反正連線 WiFi 時就可從手機輕易查到 IP.