ตั้งค่า Git Credential Manager ให้ปลอดภัยบน VPS

ทำความเข้าใจ Git Credential Storage

เมื่อ clone หรือ push repository ไปยัง remote server Git จำเป็นต้องมีการตรวจสอบสิทธิ์ (authentication) ด้วยการเก็บข้อมูล credential ไว้อย่างปลอดภัย Git มีตัวเลือกหลายแบบสำหรับการจัดเก็บ credential บน VPS เช่น store, cache, manager-core และ SSH keys

ตัวเลือกการจัดเก็บ Credential

Git มีหลายวิธีในการจัดเก็บข้อมูลการตรวจสอบสิทธิ์

  • store – เก็บ credential ในไฟล์ plain text ไม่ปลอดภัยและไม่ควรใช้บน VPS สำหรับการทำงานสำคัญ
  • cache – เก็บ credential ในหน่วยความจำชั่วคราว โดยจะลบออกหลังจากเวลาที่กำหนด
  • manager-core – ใช้ credential manager ของระบบเพื่อเก็บ credential อย่างปลอดภัย
  • SSH Keys – ใช้คู่ SSH key (public/private) แทนการใช้ password เป็นวิธีที่ปลอดภัยที่สุด

ตั้งค่า Git Credential Helper บน VPS

สำหรับ VPS บน Linux สามารถตั้งค่า credential helper ได้หลายวิธี วิธีแรกคือใช้ cache helper ซึ่งจะเก็บ credential ไว้ชั่วคราวในหน่วยความจำ

git config --global credential.helper cache

ตั้งค่าต่อไปนี้จะให้ cache ระยะเวลา 15 นาที (900 วินาที) หลังจากนั้นจะต้องใส่ credential ใหม่

git config --global credential.helper 'cache --timeout=900'

ใช้ SSH Keys แทน HTTPS

วิธีที่ปลอดภัยที่สุดคือใช้ SSH keys สำหรับการเข้าถึง Git repository ขั้นตอนแรกคือสร้าง SSH key บน VPS

ssh-keygen -t rsa -b 4096 -C "[email protected]"

คำสั่งนี้จะสร้างคู่ SSH key (public/private) ที่ยาว 4096 บิต หลังจากนั้น ให้เพิ่ม public key ไปยัง GitHub GitLab หรือ repository server ของคุณ

cat ~/.ssh/id_rsa.pub

คัดลอกเนื้อหาของ public key แล้วเพิ่มเข้าไปในการตั้งค่า SSH keys ของบัญชีของคุณบน GitHub หรือ repository server หลังจากนั้น Git จะใช้ SSH key สำหรับการตรวจสอบสิทธิ์โดยอัตโนมัติ

ตั้งค่า Keyring Integration บน Linux

หากต้องการเก็บ credential อย่างปลอดภัยมากขึ้นสามารถใช้ keyring integration บน Linux ติดตั้ง pass (password manager) หรือใช้ systemd user keyring

sudo apt-get install pass
git config --global credential.helper pass

หรือสำหรับ GNOME Keyring

sudo apt-get install gnome-keyring
git config --global credential.helper secretservice

Credential Cache Timeout

ถ้าใช้ cache helper สามารถกำหนด timeout เพื่อให้ credential ถูกลบหลังจากเวลาที่กำหนด

git config --global credential.helper 'cache --timeout=3600'

3600 วินาที เท่ากับ 1 ชั่วโมง คุณสามารถปรับค่าตามความต้องการของคุณ

หลักปฏิบัติในการ Rotate Credential

หลักปฏิบัติที่ดีคือการเปลี่ยนแปลง credential เป็นระยะ โดยเฉพาะถ้าใช้ HTTPS และ personal access tokens ควรเปลี่ยนแปลง token ทุก 30-90 วัน สำหรับ SSH keys ให้เปลี่ยนเมื่อ private key มีอายุตั้งแต่ 1 ปีขึ้นไป

ความปลอดภัยสำหรับ VPS

บน VPS ของ Dot Enterprise Cloud ควรใช้วิธีการตรวจสอบสิทธิ์ที่ปลอดภัยที่สุด ขอแนะนำให้ใช้ SSH keys และตั้งค่า ~/.ssh/config เพื่อให้ง่ายต่อการใช้งาน

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa

หากต้องใช้ HTTPS credential ให้พิจารณาใช้ cache helper กับ timeout ที่เหมาะสม โปรดจำไว้ว่า ไม่ควรเก็บ plaintext credential ในไฟล์บน VPS เพราะเสี่ยงต่อการถูกเข้าถึงโดยไม่ได้รับอนุญาต