GitHubセキュリティとは

GitHubセキュリティ機能は、コードの脆弱性や情報漏洩を防ぐツール群です。

主要なセキュリティ機能

  • 🔒 Dependabot(依存関係の脆弱性検出)
  • 🛡️ Code scanning(コードの脆弱性検出)
  • 🔑 Secret scanning(秘密情報の検出)
  • 🔐 Security advisories(脆弱性報告)
  • 👮 Branch protection(ブランチ保護)

Dependabot - 依存関係管理

Dependabotとは

依存パッケージの脆弱性を自動検出し、修正PRを作成してくれる機能です。

有効化方法

Settings > Security > Code security and analysis

✅ Dependabot alerts
✅ Dependabot security updates
✅ Dependabot version updates

Dependabot設定ファイル

# .github/dependabot.yml

version: 2
updates:
  # npm パッケージ
  - package-ecosystem: "npm"
    directory: "/"
    schedule:
      interval: "weekly"
      day: "monday"
    open-pull-requests-limit: 5
    reviewers:
      - "username"
    labels:
      - "dependencies"
      - "javascript"
  
  # Docker イメージ
  - package-ecosystem: "docker"
    directory: "/"
    schedule:
      interval: "weekly"
  
  # GitHub Actions
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "monthly"

Dependabot PRの処理

1. Dependabotが自動的にPRを作成
2. CI/CDテストが自動実行
3. レビュー
4. 問題なければマージ

# コマンドでDependabot制御
@dependabot rebase
@dependabot recreate
@dependabot merge
@dependabot close

バージョン範囲の指定

// package.json でセマンティックバージョニング
{
  "dependencies": {
    "express": "^4.18.0",  // 4.x.x の最新
    "lodash": "~4.17.0",   // 4.17.x の最新
    "axios": "1.2.3"       // 固定バージョン
  }
}

Secret Scanning - 秘密情報検出

Secret Scanningとは

APIキー、パスワード、トークンなどの秘密情報をコミットから検出します。

有効化

Settings > Code security and analysis

✅ Secret scanning
✅ Push protection(プッシュ前にブロック)

検出される秘密情報

  • AWS Access Key
  • Google API Key
  • GitHub Personal Access Token
  • Stripe API Key
  • SSH Private Key
  • Database Connection String

誤って秘密情報をコミットした場合

1. Security > Secret scanning alerts で確認
2. 秘密情報を無効化(APIキーを再発行など)
3. Gitの履歴から削除

# 履歴から削除(慎重に!)
git filter-branch --force --index-filter \
  "git rm --cached --ignore-unmatch config/secrets.yml" \
  --prune-empty --tag-name-filter cat -- --all

# または BFG Repo-Cleaner を使用
bfg --delete-files secrets.yml
git reflog expire --expire=now --all
git gc --prune=now --aggressive

# 強制プッシュ
git push origin --force --all

秘密情報の正しい管理

# .env ファイル(Gitにコミットしない)
API_KEY=sk_test_xxxxxxxxxxxx
DATABASE_URL=postgres://user:pass@localhost/db

# .gitignore に追加
.env
.env.local
config/secrets.yml
*.pem
*.key

# 環境変数で管理
export API_KEY="sk_test_xxxxxxxxxxxx"

# GitHub Secrets で管理
Settings > Secrets and variables > Actions

Code Scanning - コードの脆弱性検出

CodeQLの設定

# .github/workflows/codeql-analysis.yml

name: "CodeQL"

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 0 * * 1'  # 毎週月曜日

jobs:
  analyze:
    name: Analyze
    runs-on: ubuntu-latest
    permissions:
      security-events: write
    
    strategy:
      matrix:
        language: ['javascript', 'python']
    
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      
      - name: Initialize CodeQL
        uses: github/codeql-action/init@v2
        with:
          languages: ${{ matrix.language }}
      
      - name: Autobuild
        uses: github/codeql-action/autobuild@v2
      
      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@v2

検出される脆弱性

  • SQLインジェクション
  • XSS(クロスサイトスクリプティング)
  • コマンドインジェクション
  • パストラバーサル
  • 安全でない暗号化
  • ハードコードされた認証情報

脆弱性の修正

1. Security > Code scanning alerts で確認
2. 詳細を読み、推奨される修正方法を確認
3. コードを修正
4. PRを作成
5. CodeQLが再スキャン
6. 問題が解決されたことを確認

Branch Protection - ブランチ保護

保護ルールの設定

Settings > Branches > Add rule

Branch name pattern: main

✅ Require a pull request before merging
  - Require approvals: 2
  - Dismiss stale pull request approvals when new commits are pushed
  - Require review from Code Owners

✅ Require status checks to pass before merging
  - Require branches to be up to date before merging
  - Status checks: CI, CodeQL, Tests

✅ Require conversation resolution before merging

✅ Require signed commits

✅ Require linear history

✅ Include administrators(管理者も従う)

✅ Restrict who can push to matching branches
  - Only specific users/teams

CODEOWNERSファイル

# .github/CODEOWNERS

# デフォルトオーナー
*       @team-leads

# フロントエンド
*.js    @frontend-team
*.tsx   @frontend-team
*.css   @frontend-team

# バックエンド
*.py    @backend-team
*.go    @backend-team

# インフラ
*.yml   @devops-team
*.tf    @devops-team

# ドキュメント
*.md    @docs-team

# 特定のディレクトリ
/src/auth/  @security-team

Two-Factor Authentication(2FA)

2FAの有効化

Settings > Password and authentication > Two-factor authentication

1. 「Enable two-factor authentication」をクリック
2. Authenticator app(推奨)またはSMSを選択
3. QRコードをスキャン
4. 確認コードを入力
5. リカバリーコードを保存

組織での2FA強制

Organization Settings > Authentication security

✅ Require two-factor authentication for everyone in the organization

SSHキーとGPG署名

SSH キーの設定

# SSH キー生成
ssh-keygen -t ed25519 -C "your_email@example.com"

# 公開鍵をコピー
cat ~/.ssh/id_ed25519.pub

# GitHubに登録
Settings > SSH and GPG keys > New SSH key

GPG署名(コミット署名)

# GPGキー生成
gpg --full-generate-key

# 公開鍵を表示
gpg --armor --export YOUR_EMAIL

# GitHubに登録
Settings > SSH and GPG keys > New GPG key

# Gitに設定
git config --global user.signingkey YOUR_KEY_ID
git config --global commit.gpgsign true

# 署名付きコミット
git commit -S -m "Signed commit"

Personal Access Token

トークンの作成

Settings > Developer settings > Personal access tokens > Tokens (classic)

Note: CI/CD Token
Expiration: 90 days
Scopes:
  ✅ repo
  ✅ workflow
  ✅ write:packages

Fine-grained tokens(推奨)

Personal access tokens > Fine-grained tokens

Repository access: Only select repositories
Permissions:
  - Contents: Read and write
  - Pull requests: Read and write
  - Workflows: Read and write

トークンの使用

# HTTPS clone with token
git clone https://YOUR_TOKEN@github.com/user/repo.git

# 環境変数で管理
export GITHUB_TOKEN="ghp_xxxxxxxxxxxx"

# GitHub Actions で使用
env:
  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

監査ログ

アクティビティの確認

Organization > Settings > Audit log

確認できる内容:
- リポジトリへのアクセス
- 設定変更
- メンバーの追加・削除
- Secretsの変更
- ブランチ保護の変更

セキュリティポリシー

SECURITY.mdの作成

# SECURITY.md

## セキュリティポリシー

### サポートされるバージョン

| Version | Supported          |
| ------- | ------------------ |
| 5.1.x   | :white_check_mark: |
| 5.0.x   | :x:                |
| 4.0.x   | :white_check_mark: |
| < 4.0   | :x:                |

### 脆弱性の報告

セキュリティ脆弱性を発見した場合:

1. **公開のIssueを作成しないでください**
2. security@example.comにメールしてください
3. または GitHub Security Advisories を使用してください

### レスポンス時間

- 初回応答: 48時間以内
- 修正リリース: 重大度により7-30日

セキュリティアドバイザリ

Private Advisoryの作成

Security > Advisories > New draft security advisory

Title: SQL Injection in user search
CVE ID: Request CVE ID
Severity: High
Affected versions: < 2.5.0
Patched versions: 2.5.0

Description:
ユーザー検索機能にSQLインジェクションの脆弱性...

# 修正PRを非公開で作成可能

ベストプラクティス

1. 最小権限の原則

  • 必要最小限の権限のみ付与
  • Personal Access Tokenは短命に
  • 定期的に権限を見直す

2. 定期的な監査

# 定期的にチェック
- Dependabot alerts
- Secret scanning alerts
- Code scanning alerts
- 未使用のトークン・キーの削除

3. 教育とドキュメント

  • チームにセキュリティ意識を啓蒙
  • SECURITY.mdで報告方法を明示
  • インシデント対応手順を文書化

4. 自動化

# GitHub Actionsで定期スキャン
schedule:
  - cron: '0 0 * * 0'  # 毎週日曜日

まとめ

GitHubセキュリティ機能を活用して安全な開発環境を構築できます。

重要ポイント

  • Dependabotで依存関係を最新に
  • Secret scanningで秘密情報漏洩を防ぐ
  • Code scanningで脆弱性を早期発見
  • Branch protectionでコード品質を担保
  • 2FAで不正アクセスを防ぐ

次のステップ

  • SAST/DASTツールの導入
  • ペネトレーションテスト
  • Bug Bountyプログラム