Showing posts with label EC2. Show all posts
Showing posts with label EC2. Show all posts

Tuesday, May 30, 2023

AWS EC2 SSH接続における「Permission denied」エラーの深層と体系的解決アプローチ

Amazon Web Services (AWS) の Elastic Compute Cloud (EC2) インスタンスは、現代のクラウドコンピューティングにおける中心的な役割を担っています。開発者やインフラエンジニアがこの強力な仮想サーバーを操作する際、最も基本的かつ頻繁に行われる作業がSSH(Secure Shell)によるリモート接続です。しかし、多くのユーザーがEC2を使い始める初期段階で直面するのが、予期せぬ「Permission denied (publickey)」というエラーメッセージです。このエラーは、単なるタイプミスや設定漏れ以上に、SSH認証の根幹をなすセキュリティ原則に関わる重要なシグナルです。

このエラーに遭遇すると、多くの人はサーバー側の設定(セキュリティグループやユーザー設定など)を疑いがちですが、実は問題の根源は多くの場合、接続を試みているクライアント側、つまりあなたのローカルマシン上にあります。具体的には、EC2インスタンスへの接続に使用する秘密鍵ファイル(通常は `.pem` 拡張子を持つ)のパーミッション(権限設定)が不適切であることが原因です。

本稿では、この一見すると不可解なSSH接続エラーを根本から理解し、解決するための体系的なアプローチを提供します。単に「このコマンドを打てば解決する」という対症療法に留まらず、なぜこのエラーが発生するのか、エラーメッセージが伝える真の意味は何か、そして二度と同じ問題で悩まないための恒久的な対策とベストプラクティスまでを深く掘り下げて解説します。この知識は、EC2の操作だけでなく、広くLinux/Unixシステムにおけるセキュリティ管理全般に通じる普遍的なスキルとなるでしょう。

エラーメッセージの解読:「UNPROTECTED PRIVATE KEY FILE!」が伝える警告

問題解決の第一歩は、エラーメッセージを正確に理解することから始まります。EC2へのSSH接続に失敗した際に表示される典型的な出力は以下のようになります。

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'your-key.pem' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: your-key.pem
Permission denied (publickey).

このメッセージ群は、一連の論理的な流れに沿って表示されています。各行の意味を分解していきましょう。

1. `WARNING: UNPROTECTED PRIVATE KEY FILE!`

これは最も重要な警告です。「保護されていない秘密鍵ファイル!」という、強い調子のメッセージです。SSHクライアントは、これから使用しようとしている秘密鍵が、セキュリティ上危険な状態に置かれていることを検知しました。秘密鍵は、あなたのデジタルな身分証明書そのものであり、これが第三者に漏洩することは、物理的な鍵やパスワードが盗まれることと同等、あるいはそれ以上に深刻な事態を招きます。

2. `Permissions 0644 for 'your-key.pem' are too open.`

この行は、警告の具体的な理由を技術的に説明しています。「`your-key.pem`に対するパーミッション `0644` はあまりにもオープン(寛容)です」と述べています。ここで登場する `0644` という数字は、LinuxやmacOSなどのUnix系オペレーティングシステムでファイルのアクセス権を示す8進数表記です。

  • 最初の桁 (0): 特殊なパーミッションを指定しますが、通常は0です。
  • 2番目の桁 (6): ファイルの所有者 (Owner) の権限を示します。`6` は `4` (読み取り) + `2` (書き込み) を意味します。つまり、所有者はこのファイルを読んだり書き換えたりできます。
  • 3番目の桁 (4): ファイルが属するグループ (Group) の権限を示します。`4` は読み取り権限のみを意味します。
  • 4番目の桁 (4): 上記以外のその他のユーザー (Others) の権限を示します。これも `4` なので、読み取り権限のみを意味します。

つまり、`0644` という設定は、「ファイルの所有者は読み書き可能、しかし同じコンピュータを使用する他のユーザーもこのファイルを読み取ることができてしまう」状態を指します。秘密鍵は、その名の通り「秘密」であるべきです。所有者以外の誰にも(たとえ読み取りだけであっても)アクセスされるべきではありません。この「誰でも読める」状態を、SSHクライアントは「too open」と判断しているのです。

3. `This private key will be ignored.`

これは、SSHクライアントが下した決断です。「この秘密鍵は無視されます」と宣言しています。これはバグではなく、セキュリティを最優先する設計思想に基づく意図的な挙動です。安全でないと判断した鍵の使用を拒否することで、中間者攻撃や鍵の盗難による不正アクセスからユーザーとサーバーを保護する、一種のフェイルセーフ機構です。

4. `Permission denied (publickey).`

これが最終的にユーザーの目に留まるエラーです。ここまでの流れを理解すれば、このエラーの意味は明確です。

  1. SSHクライアントは公開鍵認証(publickey authentication)を試みようとしました。
  2. そのために指定された秘密鍵ファイルを使おうとしましたが、パーミッションが危険な状態でした。
  3. 安全のため、その秘密鍵の使用を中止(無視)しました。
  4. 結果として、認証に使える有効な秘密鍵がないため、サーバーは公開鍵認証を拒否しました。
したがって、「Permission denied」はサーバーが意地悪をしているのではなく、クライアント側が適切な「身分証明書」を提示できなかったために発生した、当然の帰結なのです。

根本解決策:`chmod`コマンドによるパーミッションの修正

原因が秘密鍵ファイルの過剰なパーミッションにあることが分かれば、解決策は明確です。このパーミッションを、SSHクライアントが安全だと判断するレベルまで制限すればよいのです。そのために使用するのが `chmod` (Change Mode) コマンドです。

`chmod 400` コマンドの詳細な解説

この問題に対する最も標準的かつ安全な解決策は、以下のコマンドを実行することです。

chmod 400 your-key.pem

このコマンドが何を行っているのかを正確に理解しましょう。

  • `chmod`: ファイルやディレクトリのアクセス権限を変更するためのUnix/Linuxコマンドです。
  • `400`: これが新しいパーミッション設定を8進数で指定する部分です。
    • 最初の桁 `4` (Owner): 所有者の権限です。`4` は「読み取り (read)」のみを許可します。書き込み (write) や実行 (execute) は許可されません。これにより、所有者自身が誤って秘密鍵を書き換えて破損させてしまう事故も防げます。
    • 2番目の桁 `0` (Group): グループの権限です。`0` は何の権限も与えない(no permissions)ことを意味します。
    • 3番目の桁 `0` (Others): その他のユーザーの権限です。これも `0` で、一切の権限を与えません。

結果として、`chmod 400` を実行した後の秘密鍵ファイルは、「所有者だけが読み取ることができ、他の誰も一切アクセスできず、所有者でさえ書き込みはできない」という、非常に厳格で安全な状態になります。これこそが、SSHクライアントが秘密鍵に要求する理想的なパーミッションなのです。

`chmod 600` との比較

インターネット上の記事やチュートリアルでは、`chmod 600 your-key.pem` というコマンドが紹介されていることもあります。この設定もSSH接続エラーを解決できます。

  • `600` の意味: 所有者に「読み取り(4) + 書き込み(2)」を許可し、グループとその他には権限を与えません(`00`)。

SSHクライアントは `600` も安全なパーミッションとして受け入れます。では、`400` と `600` のどちらを使うべきでしょうか?

セキュリティの観点からは `400` がより推奨されます。 秘密鍵は一度生成されたら内容を変更する必要は全くありません。`600` のように書き込み権限を残しておくと、何らかの操作ミスでファイルの内容を空にしてしまったり、意図せず編集してしまったりするリスクが僅かながら存在します。読み取り専用の `400` に設定しておくことは、こうしたヒューマンエラーを防ぐための追加の保護層となります。「最小権限の原則」に従い、必要ない権限は与えないのがセキュリティの基本です。そのため、本稿では `400` の使用を強く推奨します。

OS別・実践的トラブルシューティング手順

理論を理解したところで、次はお使いのオペレーティングシステムに合わせた具体的な解決手順を見ていきましょう。

macOS / Linux ユーザー向け手順

macOSと各種Linuxディストリビューション(Ubuntu, CentOSなど)では、`chmod` コマンドが標準で利用できるため、手順は非常にシンプルです。

  1. ターミナルを開く:

    まず、ターミナルアプリケーションを起動します。

  2. 秘密鍵ファイルのディレクトリへ移動:

    AWSからダウンロードした `.pem` ファイルが保存されているディレクトリに `cd` コマンドで移動します。通常、`Downloads` フォルダにあることが多いでしょう。

    # 例: ダウンロードフォルダに移動する場合
    cd ~/Downloads
  3. 現在のパーミッションを確認 (推奨):

    変更前に、`ls -l` コマンドで現在のパーミッションがどうなっているか確認してみましょう。問題が発生している場合、おそらく `-rw-r--r--` (644) のように表示されるはずです。

    ls -l your-key.pem
    # 出力例: -rw-r--r-- 1 youruser staff 1696 Apr 1 10:00 your-key.pem
  4. パーミッションの変更を実行:

    いよいよ `chmod 400` を実行します。

    chmod 400 your-key.pem

    このコマンドは成功しても何もメッセージを返しません。これが正常な動作です。

  5. 変更後のパーミッションを再確認 (推奨):

    再度 `ls -l` を実行し、パーミッションが正しく変更されたことを確認します。`-r--------` (400) と表示されれば成功です。

    ls -l your-key.pem
    # 出力例: -r-------- 1 youruser staff 1696 Apr 1 10:00 your-key.pem
  6. SSH接続の再試行:

    これで準備は完了です。改めてSSH接続コマンドを実行してください。エラーが解消され、正常に接続できるはずです。

    ssh -i "your-key.pem" ec2-user@ec2-xx-xx-xx-xx.ap-northeast-1.compute.amazonaws.com

Windows ユーザー向けの包括的解決策

Windows環境では、どのツールを使ってSSH接続を試みるかによって対処法が異なります。ここでは主要な3つのシナリオについて解説します。

シナリオ1: WSL (Windows Subsystem for Linux) を使用する場合

WSLは、Windows上でLinux環境をネイティブに実行する機能です。WSL内のターミナルからSSH接続を行う場合、解決方法は上記のmacOS/Linuxと全く同じです。

  • WSLのディストリビューション(Ubuntuなど)を起動します。
  • Windowsのファイルシステムは `/mnt/c/` などにマウントされています。例えば、Windowsのダウンロードフォルダにある鍵ファイルにアクセスするには、次のように移動します。
    `cd /mnt/c/Users/YourWindowsUser/Downloads`
  • あとは `chmod 400 your-key.pem` を実行し、SSHコマンドを試すだけです。

シナリオ2: Git Bash を使用する場合

Git for Windows に同梱されている Git Bash は、`chmod` を含む多くのLinuxコマンドが使える便利なターミナルです。Git Bashを使っている場合も、macOS/Linuxの手順とほぼ同じです。

  • Git Bashを起動します。
  • `cd` コマンドで鍵ファイルのあるディレクトリに移動します。パスの形式は `/c/Users/YourUser/Downloads` のようになります。
  • `chmod 400 your-key.pem` を実行します。

シナリオ3: ネイティブのOpenSSHクライアント (PowerShell / コマンドプロンプト) を使用する場合

近年のWindows 10/11にはOpenSSHクライアントが標準搭載されており、PowerShellやコマンドプロンプトから直接 `ssh` コマンドが使えます。しかし、Windowsのファイルシステム(NTFS)はUnixのパーミッションモデルとは異なるACL(Access Control List)で権限を管理しています。そのため `chmod` は直接使えません。代わりに、GUI(グラフィカルユーザーインターフェース)でファイルのセキュリティ設定を変更する必要があります。

  1. ファイルのプロパティを開く:

    エクスプローラーで `.pem` ファイルを右クリックし、「プロパティ」を選択します。

  2. セキュリティ設定へ移動:

    表示されたウィンドウで「セキュリティ」タブをクリックし、「詳細設定」ボタンを押します。

  3. 継承の無効化:

    「セキュリティの詳細設定」ウィンドウの左下にある「継承の無効化」ボタンをクリックします。ダイアログが表示されたら、「このオブジェクトから継承されたアクセス許可をすべて削除します。」を選択します。これにより、上位フォルダからの権限設定がクリアされ、このファイル固有の権限を設定できるようになります。

  4. 不要なアクセスの削除:

    「アクセス許可エントリ」のリストが空になるか、いくつかのエントリが残る場合があります。自分のユーザーアカウント以外のエントリ(例: `SYSTEM`, `Administrators`)はすべて選択して「削除」ボタンで削除します。

  5. 自分自身のアクセス権を追加:

    「追加」ボタンをクリックし、「プリンシパルの選択」を押します。テキストボックスに自分のWindowsユーザー名を入力して「名前の確認」を押し、OKします。 「基本的なアクセス許可」の画面で、「フルコントロール」にチェックを入れるか、最低限「読み取り」にチェックが入っていることを確認します。その後、「OK」を押してすべてのウィンドウを閉じます。

この一連の操作により、`.pem` ファイルは「あなたのアカウントだけがアクセスできる」状態になり、これはUnixの `chmod 400` や `chmod 600` と同等のセキュリティレベルと見なされます。この後、PowerShellやコマンドプロンプトからSSH接続を試みれば、パーミッションエラーは解消されているはずです。

再発防止とより高度な鍵管理

問題を一度解決するだけでなく、将来的に同じ轍を踏まないように仕組みを整えることが重要です。ここでは、より洗練された鍵管理の方法を紹介します。

鍵管理のベストプラクティス

  1. `~/.ssh` ディレクトリの活用: SSH関連のファイル(秘密鍵、公開鍵、設定ファイルなど)は、ホームディレクトリ直下の `.ssh` という専用ディレクトリにまとめて管理するのが標準的な慣習です。このディレクトリはデフォルトでパーミッションが `700` (所有者のみ読み書き実行可能) に設定されており、セキュリティ上も望ましいです。
  2. 鍵の即時移動と権限設定: AWSコンソールから `.pem` ファイルをダウンロードしたら、すぐに `~/Downloads` から `~/.ssh/` ディレクトリに移動させ、直ちに `chmod 400 ~/.ssh/your-key.pem` を実行する癖をつけましょう。
# ダウンロード直後に行う一連のコマンド例
mv ~/Downloads/your-key.pem ~/.ssh/
chmod 400 ~/.ssh/your-key.pem

`~/.ssh/config` ファイルによる接続の効率化

毎回長い `ssh -i ...` コマンドを打つのは面倒ですし、間違いのもとです。`~/.ssh/` ディレクトリ内に `config` という名前のファイルを作成することで、接続情報を一元管理し、コマンドを劇的に簡略化できます。

`~/.ssh/config` ファイルに以下のように記述します。

# ~/.ssh/config ファイルの内容

Host my-web-server
    HostName ec2-xx-xx-xx-xx.ap-northeast-1.compute.amazonaws.com
    User ec2-user
    IdentityFile ~/.ssh/your-key.pem
    Port 22

Host my-db-server
    HostName ec2-yy-yy-yy-yy.ap-northeast-1.compute.amazonaws.com
    User ubuntu
    IdentityFile ~/.ssh/another-key.pem
    Port 22
  • `Host`: 接続のエイリアス(ニックネーム)を定義します。
  • `HostName`: EC2インスタンスのパブリックDNS名またはIPアドレス。
  • `User`: ログインするユーザー名。
  • `IdentityFile`: 使用する秘密鍵ファイルのパス。
  • `Port`: SSHポート(通常は22)。

このように設定しておけば、今後は以下の短いコマンドを打つだけで接続できます。

ssh my-web-server

`config` ファイルがホスト名、ユーザー名、鍵ファイルのパスを自動的に補完してくれるため、コマンドがシンプルになり、複数のサーバーを管理する際に非常に便利です。

パーミッション修正後も接続できない場合の追加チェックリスト

`chmod 400` を実行してもまだ `Permission denied` エラーが出る場合、問題は別の場所にある可能性があります。以下の項目を順に確認してください。

チェック1: 正しいユーザー名を使用していますか?
EC2インスタンスのデフォルトユーザー名は、使用しているAMI(Amazon Machine Image)によって異なります。間違ったユーザー名でログインしようとすると、当然ながら拒否されます。
  • Amazon Linux 2: `ec2-user`
  • Ubuntu: `ubuntu`
  • CentOS: `centos`
  • Debian: `admin`
  • RHEL: `ec2-user` または `root`
チェック2: セキュリティグループの設定は適切ですか?
EC2インスタンスにアタッチされているセキュリティグループが、あなたのIPアドレスからのSSH接続(TCPポート22)を許可しているか確認してください。インバウンドルールに、タイプ「SSH」、ポート「22」、ソース「マイIP」または特定のIPアドレス範囲が設定されている必要があります。
チェック3: 正しいキーペアを使用していますか?
複数のEC2インスタンスやキーペアを管理していると、インスタンスAを起動した際のキー(A.pem)ではなく、インスタンスBのキー(B.pem)を使って接続しようとしてしまうことがあります。AWS EC2コンソールで対象インスタンスを選択し、「詳細」タブでどのキーペア名が関連付けられているか再確認してください。
チェック4: インスタンスのパブリックIPアドレスは変わっていませんか?
Elastic IPを割り当てていないEC2インスタンスは、停止・起動のたびにパブリックIPアドレスが変わる可能性があります。古いIPアドレスに接続しようとしていないか、EC2コンソールで現在のIPアドレスを確認してください。
チェック5: ネットワークACL(NACL)がブロックしていませんか?
NACLはサブネットレベルで動作するもう一つのファイアウォールです。通常はデフォルトで全トラフィックを許可していますが、カスタム設定されている場合、SSH(ポート22)のインバウンドおよびアウトバウンド(特にエフェメラルポート範囲)がブロックされている可能性があります。

結論:エラーはセキュリティ機能であるという理解

AWS EC2へのSSH接続で遭遇する「`WARNING: UNPROTECTED PRIVATE KEY FILE!`」とそれに続く「`Permission denied (publickey)`」エラーは、多くの初学者を戸惑わせる壁です。しかし、本稿で詳述した通り、これはシステムの不具合やバグではなく、ユーザーを潜在的な危険から守るための意図された、極めて重要なセキュリティ機能です。

このエラーは、SSHというプロトコルが、認証情報の機密性をいかに重視しているかを物語っています。単に `chmod 400` というコマンドを機械的に実行して解決するだけでなく、なぜそのパーミッションが必要なのか、`0644` がなぜ危険なのかを理解することで、あなたのクラウドインフラ管理能力は一段階上のレベルに引き上げられます。

適切な鍵管理、パーミッション設定の習慣化、そして `~/.ssh/config` のようなツールを活用した効率的な運用は、セキュアで安定したクラウド環境を維持するための基礎体力となります。今日解決したこの一つのエラーは、より堅牢なシステムを構築するための貴重な学びの機会だったと捉え、今後のAWS活用に活かしていきましょう。

Monday, May 8, 2023

Navigating AWS EC2 SSH Access: A Deep Dive into Permissions and Connectivity

Connecting to an Amazon Web Services (AWS) EC2 instance is a fundamental task for developers, system administrators, and DevOps engineers. Secure Shell (SSH) provides the encrypted channel for this remote administration. However, the path to a successful connection is often fraught with cryptic permission errors that can halt progress. Among the most common is the dreaded "UNPROTECTED PRIVATE KEY FILE!" warning, a security measure that, while essential, can be a source of significant frustration.

This article provides a comprehensive exploration of this specific SSH permission error. We will deconstruct the error message to understand its security implications, provide detailed, platform-specific solutions for Linux, macOS, and Windows, and broaden our scope to cover other related connectivity issues. By understanding the underlying principles of file permissions and AWS security configurations, you can move from troubleshooting to seamless, secure access to your cloud infrastructure.

The Anatomy of an SSH Connection Failure: Deconstructing the Warning

When you attempt to connect to an EC2 instance and your private key file has incorrect permissions, your SSH client will refuse to proceed and present a block of text that looks intimidating but is actually quite informative. Let's break it down line by line.

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!      @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'your-key.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: your-key.pem
Permission denied (publickey).

This isn't a single error, but a chain reaction of warnings and failures. Understanding each part is key to grasping the core problem.

  • WARNING: UNPROTECTED PRIVATE KEY FILE!: This is the primary alert. It's a client-side check performed by your SSH software (like OpenSSH on Linux/macOS or PuTTY on Windows). It has detected that your private key file, the secret key that proves your identity to the EC2 instance, is not properly secured on your local machine.
  • Permissions 0644 for 'your-key.pem' are too open.: This line provides the specific technical reason for the warning. The file's permissions, represented by the octal code 0644, are deemed insecure. We will delve into what this code means shortly, but in essence, it signifies that users other than yourself can read the file. Your private key should be a secret known only to you; if others can read it, they could potentially copy it and impersonate you to gain access to your server.
  • It is required that your private key files are NOT accessible by others.: This is a plain-language reinforcement of the security principle at play. The SSH client is designed to enforce this best practice to prevent accidental security breaches.
  • This private key will be ignored. & bad permissions: ignore key: your-key.pem: These lines state the direct consequence. Because the key is insecure, the SSH client will not use it for authentication. It's as if you didn't provide a key at all.
  • Permission denied (publickey).: This is the final, server-side result. Your client attempted to connect to the EC2 instance. Since it ignored your insecure private key, it couldn't present a valid credential. The EC2 instance's SSH daemon (the server-side software) correctly rejected the connection attempt because the public key authentication method failed.

In short, the problem isn't with your AWS configuration (yet), but with the security of the private key file on your own computer. Your SSH client is acting as a responsible guardian, refusing to transmit a secret that it considers compromised.

The Foundation of the Fix: Understanding Unix File Permissions

To solve the "too open" permissions issue, one must first understand how permissions work in Unix-like operating systems (Linux, macOS, BSD). Files and directories have permissions assigned to three distinct classes of users:

  • User (Owner): The specific user account that owns the file.
  • Group: A group of users who share a set of permissions.
  • Others: Everyone else on the system.

For each of these classes, three primary permissions can be granted or denied:

  • Read (r): The ability to view the contents of the file.
  • Write (w): The ability to modify or delete the file.
  • Execute (x): The ability to run the file as a program (for files) or enter it (for directories).

Octal Notation Explained

These permissions are often represented using a three-digit octal (base-8) number, like the 0644 from our error message. Each digit corresponds to a user class (User, Group, Others) and is the sum of the values for the granted permissions:

  • Read (r) = 4
  • Write (w) = 2
  • Execute (x) = 1

Let's re-examine the problematic permission set, 644:

  • The first digit, 6, applies to the User (Owner). It is the sum of Read (4) + Write (2), meaning the owner can read and write to the file.
  • The second digit, 4, applies to the Group. It represents Read (4) only, meaning members of the file's group can read its contents.
  • The third digit, 4, applies to Others. It also represents Read (4) only, meaning any user on the system can read the file.

This is where the security risk lies. The "Others" permission allows any account on your machine to read your private key. The SSH client rightly refuses to use such a key.

The Secure Permission Setting: `400`

The solution is to change the permissions to a more restrictive setting. The most commonly recommended setting for a private key is 400.

  • The first digit, 4, applies to the User (Owner). It means Read (4) only. The owner can read the key (which is necessary for the SSH client to use it) but cannot accidentally write to or modify it.
  • The second digit, 0, applies to the Group. A value of 0 means no permissions—group members can neither read, write, nor execute the file.
  • The third digit, 0, applies to Others. Similarly, a value of 0 means no permissions for anyone else.

With 400 permissions, only you, the owner, can read the key. This satisfies the security requirement of the SSH client.

Resolving the Permission Error: Platform-Specific Instructions

The method for changing file permissions differs based on your operating system. Below are detailed instructions for the most common environments.

For Linux and macOS Users

Users of Linux-based distributions (like Ubuntu, CentOS, Amazon Linux) and macOS have access to the powerful `chmod` (change mode) command-line utility. This is the most direct way to fix the issue.

  1. Open Your Terminal: Launch the terminal application on your system.
  2. Navigate to Your Key's Location: Your .pem file is typically saved in your `Downloads` folder or a dedicated `.ssh` directory within your home folder (`~/.ssh/`). Use the `cd` (change directory) command to get there. For example:
    cd ~/Downloads
    Or, if you've moved it to your `.ssh` directory:
    cd ~/.ssh
  3. Verify Current Permissions (Optional but Recommended): You can see the current permissions using the `ls -l` command. This will show a detailed listing, including the permissions string (e.g., `-rw-r--r--`).
    ls -l your-key.pem
    The output might look like this, confirming the "too open" state:
    -rw-r--r-- 1 youruser staff 1696 Oct 26 10:30 your-key.pem
  4. Change the Permissions: Execute the `chmod` command to set the permissions to `400`.
    chmod 400 your-key.pem
    This command produces no output if successful.
  5. Verify the New Permissions: Run `ls -l` again to confirm the change.
    ls -l your-key.pem
    The output should now reflect the new, secure permissions:
    -r-------- 1 youruser staff 1696 Oct 26 10:30 your-key.pem
    Notice how `-rw-r--r--` has changed to `-r--------`. This visually confirms that only the owner has read access.
  6. Attempt the SSH Connection Again: With the permissions corrected, your SSH command should now work as expected.
    ssh -i "your-key.pem" ec2-user@ec2-xx-xx-xx-xx.compute-1.amazonaws.com

For Windows Users

Traditionally, Windows used a different permission model (ACLs) and lacked a built-in `chmod` command. However, modern versions of Windows 10 and 11 provide several ways to manage these permissions, from a graphical interface to powerful command-line tools.

Method 1: Using the File Properties GUI (Recommended for Most Users)

This method does not require the command line and is the most intuitive for those comfortable with the Windows interface.

  1. Locate the File: Open File Explorer and navigate to where you saved your .pem file.
  2. Open Properties: Right-click on the .pem file and select Properties.
  3. Go to the Security Tab: In the Properties window, click on the Security tab. You will likely see multiple users and groups listed (like `SYSTEM`, `Administrators`, and your user account), which is why the key is considered "too open".
  4. Access Advanced Settings: Click the Advanced button at the bottom right.
  5. Disable Inheritance: In the "Advanced Security Settings" window, you'll see a button at the bottom left labeled "Disable inheritance". Click it. A pop-up will ask what you want to do with the current inherited permissions. Select "Convert inherited permissions into explicit permissions on this object." This keeps the current permissions but allows you to edit them.
  6. Remove Unnecessary Users: Now, you can remove all security principals except for your own user account. Select each entry one by one (e.g., `Administrators`, `SYSTEM`) and click the Remove button. Be careful not to remove your own user account.
  7. Confirm Final Permissions: After removing the others, you should be left with only one entry: your user account. The permissions for this entry should be sufficient (e.g., "Read & execute", "Read", or "Full control"). Click OK to apply the changes, and then OK again on the Properties window.

By performing these steps, you have effectively replicated the `chmod 400` command by ensuring that only your user identity has any access rights to the file. Your SSH client (whether it's the built-in Windows OpenSSH, PuTTY, or one within WSL) will now recognize the file as secure.

Method 2: Using PowerShell (for Command-Line Users)

PowerShell provides robust commands for managing file permissions.

  1. Open PowerShell as Administrator: Search for PowerShell, right-click, and select "Run as administrator".
  2. Navigate to the key's directory:
    cd "C:\path\to\your\keys"
  3. Run the following commands:
    
    # Get the file object
    $path = ".\your-key.pem"
    $acl = Get-Acl $path
    
    # Set the rule to remove inheritance and existing rules
    $acl.SetAccessRuleProtection($true, $false)
    
    # Create a new rule that gives only the current user read access
    $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, "Read", "Allow")
    $acl.SetAccessRule($rule)
    
    # Apply the new ACL to the file
    Set-Acl $path $acl
            

This script programmatically strips all existing permissions and adds a single new one granting only your current user read access.

Beyond File Permissions: Other Common EC2 SSH Hurdles

Fixing the private key permission is a critical step, but it's not the only thing that can go wrong. If you've corrected the permissions and still can't connect, the problem likely lies elsewhere in the chain. Here are the next most common areas to investigate.

1. Incorrect Security Group Configuration

A Security Group acts as a virtual firewall for your EC2 instance, controlling inbound and outbound traffic. By far the most common network-related issue is a Security Group that does not allow SSH traffic.

  • The Rule: Your instance's Security Group must have an inbound rule that allows traffic on TCP port 22 (the standard port for SSH).
  • The Source IP: The source for this rule determines who can attempt to connect.
    • 0.0.0.0/0 (Anywhere): This allows any IP address on the internet to connect to your instance's SSH port. It is convenient for initial setup but is a significant security risk, as it exposes your instance to scanners and brute-force attacks from across the globe. This should not be used in production environments.
    • My IP: The AWS console has a handy feature to automatically populate the source with your current public IP address. This is much more secure, as it restricts access to only your network. The downside is that if your public IP changes (common on home or mobile networks), you will need to update this rule.
    • Custom IP Range: You can specify a custom CIDR block, such as your office's static IP range, to provide stable and secure access for your team.

How to Check: In the EC2 console, select your instance, and in the details pane below, click on the "Security" tab. You will see the attached Security Groups. Click on a group to view its "Inbound rules" and verify the port 22 rule is correctly configured.

2. Incorrect Username or Public DNS/IP

The SSH command has three main components: the key, the user, and the host. An error in any of them will cause failure.

  • Username: The default username is determined by the Amazon Machine Image (AMI) used to launch the instance. Using the wrong one will result in a `Permission denied` error. Common defaults include:
    • Amazon Linux 2: ec2-user
    • Ubuntu Server: ubuntu
    • CentOS: centos
    • Debian: admin
    • RHEL: ec2-user or root
  • Public DNS/IP Address: If you stop and then start an EC2 instance, its public IP address and public DNS name will change by default, unless you have assigned an Elastic IP to it. Always double-check in the EC2 console that you are using the current, correct address in your SSH command. A `Connection timed out` error often points to an old, incorrect IP address.

3. Network Access Control Lists (NACLs)

Less common but still possible, Network ACLs are another layer of firewall security that operate at the subnet level. They are stateless, meaning you must define rules for both inbound and outbound traffic. If your Security Group is configured correctly but you still can't connect, check the NACL associated with your instance's subnet to ensure it allows inbound traffic on port 22 and outbound traffic on ephemeral ports (1024-65535) for the return communication.

Proactive Security: Best Practices for Key Management

Troubleshooting is reactive. A better long-term strategy is to adopt best practices that prevent these issues from occurring in the first place.

  • Secure Storage: Always store your private keys in a secure, permission-controlled directory, such as `~/.ssh/` on Linux/macOS. Immediately set the permissions to `400` after downloading a new key.
  • Never Share Private Keys: A private key is a credential, like a password. It should never be shared, emailed, or checked into a version control system like Git. If another user needs access, create a new IAM user for them or add their public key to the instance's `~/.ssh/authorized_keys` file.
  • Use Different Keys for Different Environments: Avoid using the same key pair for development, staging, and production environments. Isolating keys limits the blast radius if one is ever compromised.
  • Consider AWS Systems Manager Session Manager: For a more modern and arguably more secure approach, consider using AWS Systems Manager Session Manager. It allows you to get a secure shell in your browser or terminal without needing to manage SSH keys or open port 22 in your security groups at all. It relies on an IAM role and an agent on the instance, centralizing access control and logging within AWS itself.

By understanding the mechanics of SSH permissions and the broader AWS networking and security landscape, you can transform a frustrating roadblock into a routine check. A secure and reliable connection to your EC2 instances is the foundation of effective cloud management, and mastering its setup is a vital skill for any cloud professional.

Thursday, January 31, 2019

EC2 인스턴스 접속 불가능? 'REMOTE HOST IDENTIFICATION HAS CHANGED' 오류의 근본 원인과 해결법

클라우드 컴퓨팅의 선두주자 AWS(Amazon Web Services)의 EC2(Elastic Compute Cloud) 인스턴스는 개발자, 시스템 관리자, 그리고 수많은 IT 전문가들에게 강력하고 유연한 가상 서버 환경을 제공합니다. 개발 환경 구축부터 프로덕션 서비스 운영까지, EC2는 이제 현대 IT 인프라의 핵심적인 부분으로 자리 잡았습니다. EC2 인스턴스를 생성하고, 탄력적 IP(Elastic IP)를 할당하고, 정성껏 만든 `.pem` 키 페어를 이용해 SSH(Secure Shell)로 접속을 시도하는 순간, 많은 사용자들이 당혹스러운 경고 메시지를 마주하게 됩니다.


@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@       WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!      @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
Please contact your system administrator.
Add correct host key in /home/username/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /home/username/.ssh/known_hosts:5
  remove with:
  ssh-keygen -f "/home/username/.ssh/known_hosts" -R "your-ec2-instance-ip"
ECDSA host key for your-ec2-instance-ip has changed and you have requested strict checking.
Host key verification failed.

이 무시무시한 경고 메시지는 'REMOTE HOST IDENTIFICATION HAS CHANGED!'라는 문구와 함께 "누군가 당신을 도청하고 있을 수 있다(man-in-the-middle attack)!"는 섬뜩한 가능성까지 제시합니다. 처음 이 메시지를 접하면 해킹을 당했거나, 계정에 심각한 문제가 생긴 것은 아닌지 불안감에 휩싸이기 쉽습니다. 하지만 결론부터 말하자면, 대부분의 경우 이는 실제 공격 상황이 아니라, SSH의 매우 중요한 보안 메커니즘이 정상적으로 작동하고 있다는 신호입니다. 여러분의 로컬 컴퓨터가 여러분을 보호하기 위해 접속을 의도적으로 차단하고 있는 것입니다.

이 글에서는 이 'REMOTE HOST IDENTIFICATION HAS CHANGED' 오류가 왜 발생하는지, 그 근본적인 원인이 되는 SSH의 호스트 키 인증 매커니즘을 심도 있게 파헤쳐 볼 것입니다. 그리고 단순히 문제를 해결하는 명령어 한 줄을 소개하는 것을 넘어, 상황에 따른 다양한 해결 방법과 각 방법의 장단점, 나아가 이러한 문제를 미연에 방지할 수 있는 예방책까지 총망라하여 완벽하게 이해하고 대처할 수 있도록 도와드리겠습니다.

1. 오류의 근원: SSH와 '신뢰의 증표', 호스트 키(Host Key)

문제를 해결하기 위해서는 먼저 그 원인을 알아야 합니다. 이 오류의 핵심에는 SSH의 '호스트 키 검증(Host Key Verification)'이라는 보안 절차가 있습니다. 이는 마치 우리가 처음 방문하는 은행에서 신분증을 제시하여 본인임을 확인하고, 다음 방문부터는 안면 인식이나 지문으로 더 빠르게 신원을 확인하는 과정과 유사합니다.

1.1. SSH 통신과 중간자 공격(Man-in-the-Middle Attack)의 위협

SSH는 클라이언트(우리의 노트북 또는 데스크톱)와 서버(EC2 인스턴스) 간의 모든 통신을 암호화하여 안전하게 만들어주는 프로토콜입니다. 우리가 입력하는 명령어, 서버가 보내오는 응답 등 모든 데이터가 암호화되어 중간에 누군가 가로채더라도 내용을 알 수 없습니다.

하지만 여기서 한 가지 치명적인 허점이 생길 수 있습니다. 만약 우리가 접속하려는 '진짜' EC2 서버가 아닌, 해커가 만든 '가짜' 서버에 접속하게 된다면 어떻게 될까요? 해커는 우리의 접속 요청을 중간에서 가로채 자신의 가짜 서버로 연결합니다. 우리는 진짜 서버에 접속한 줄 알고 아이디와 비밀번호, 혹은 중요한 명령어를 입력하게 되고, 해커는 이 모든 정보를 얻어낸 뒤 다시 진짜 서버로 요청을 전달해 우리에게 정상적인 응답을 보여줍니다. 우리는 아무것도 눈치채지 못하지만, 우리의 모든 정보는 해커에게 노출됩니다. 이를 '중간자 공격(Man-in-the-Middle Attack, MITM)'이라고 부릅니다.

1.2. 중간자 공격을 막는 방패: 호스트 키와 `known_hosts` 파일

SSH는 이러한 중간자 공격을 방지하기 위해 '호스트 키'라는 매우 영리한 장치를 사용합니다.

  • 호스트 키(Host Key): 모든 SSH 서버(EC2 인스턴스 포함)는 처음 설치되고 설정될 때, 고유한 한 쌍의 키(공개키와 개인키)를 생성합니다. 이것이 바로 '호스트 키'입니다. 이 키는 해당 서버의 '신분증'과 같은 역할을 합니다.
  • 첫 만남 (최초 접속): 우리가 어떤 서버에 생애 처음으로 SSH 접속을 시도하면, 클라이언트(우리의 컴퓨터)는 해당 서버에게 "너의 신분증(호스트 키의 공개키)을 보여줘"라고 요청합니다. 서버는 자신의 공개키를 보내주고, 우리 컴퓨터는 다음과 같은 질문을 합니다.

The authenticity of host 'ec2-xx-xx-xx-xx.ap-northeast-2.compute.amazonaws.com (xx.xx.xx.xx)' can't be established.
ECDSA key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no/[fingerprint])? 

이 메시지의 의미는 "이 서버는 처음 보는 곳인데, 이 서버의 키 지문(fingerprint)이 이거래. 정말 이 서버가 네가 접속하려는 그 서버가 맞아? 연결을 계속할까?"라고 묻는 것입니다. 여기서 우리가 yes를 입력하면, 우리 컴퓨터는 '아, 이 IP 주소(또는 도메인)의 신분증은 이것이구나'라고 판단하고, 해당 서버의 IP 주소와 공개키 정보를 자신의 '신뢰 목록'에 저장합니다.

  • `known_hosts` 파일: 이 '신뢰 목록'이 바로 우리 컴퓨터의 ~/.ssh/known_hosts 파일입니다. 이 파일은 우리가 신뢰하기로 결정한 모든 서버들의 주소와 그들의 고유한 공개키 정보를 기록해두는 일종의 '보안 연락처'입니다.

1.3. 'REMOTE HOST IDENTIFICATION HAS CHANGED' 오류가 발생하는 시나리오

자, 이제 모든 조각이 맞춰졌습니다. 오류 메시지가 발생하는 상황은, 우리가 다시 같은 주소로 접속을 시도했는데, 서버가 제시한 '신분증(호스트 키)'이 known_hosts 파일에 기록된 '신분증'과 다를 때 발생합니다.

우리 컴퓨터는 이렇게 생각합니다. "어? 분명 이 IP 주소를 가진 서버의 신분증은 A였는데, 방금 접속하니 B라는 다른 신분증을 내미네? 이거 중간에 누가 서버를 바꿔치기한 것일 수 있어! (중간자 공격 가능성!) 일단 연결을 차단하고 사용자에게 알려야겠다!" 이것이 바로 'REMOTE HOST IDENTIFICATION HAS CHANGED!' 경고의 본질입니다.

그렇다면 AWS EC2 환경에서 왜 이런 일이 흔하게 발생할까요? 실제 해킹이 아니라면 말이죠.

  • 가장 흔한 원인: 탄력적 IP(Elastic IP) 재사용
    • 기존에 사용하던 EC2 인스턴스(A 서버)를 종료(Terminate)했습니다. 이 인스턴스는 12.34.56.78 이라는 탄력적 IP를 사용하고 있었습니다.
    • 새로운 EC2 인스턴스(B 서버)를 생성하고, 똑같은 탄력적 IP 주소인 12.34.56.78을 할당했습니다.
    • 우리 컴퓨터의 `known_hosts` 파일에는 여전히 12.34.56.78 = 'A 서버의 호스트 키'라고 기록되어 있습니다.
    • 이제 12.34.56.78로 접속을 시도하면, B 서버는 자신의 새로운 호스트 키를 제시합니다.
    • 우리 컴퓨터는 'A 서버의 호스트 키'를 기대했지만 'B 서버의 호스트 키'를 받았으므로, 불일치를 감지하고 접속을 차단합니다.
  • 기타 원인
    • 인스턴스의 OS 재설치: 기존 인스턴스를 유지한 채로 운영체제(OS)를 새로 설치하면, SSH 서버 데몬이 새로 설정되면서 새로운 호스트 키를 생성할 수 있습니다.
    • AMI(Amazon Machine Image)로 인스턴스 복제: 기존 인스턴스의 AMI를 떠서 새로운 인스턴스를 생성할 때, 일부 설정에 따라 부팅 시 새로운 호스트 키를 생성하도록 구성된 경우가 있습니다.
    • 로드 밸런서 또는 프록시 변경: 직접적인 원인은 아니지만, 접속 경로상의 네트워크 장비가 변경되면서 다른 서버로 연결이 라우팅될 때도 유사한 문제가 발생할 수 있습니다.

결론적으로 EC2 환경에서의 이 오류는, IP 주소는 그대로인데 그 IP 주소에 연결된 실제 가상 머신(과 그 호스트 키)이 변경되었기 때문에 발생하는 지극히 정상적인 보안 경고인 셈입니다.

2. 단계별 해결 방법: 안전하고 빠른 방법부터 수동적인 방법까지

원인을 명확히 이해했으니 이제 해결 방법을 알아볼 차례입니다. "이 IP 주소의 주인이 바뀐 것이 맞다"고 우리 컴퓨터에게 알려주어 `known_hosts` 파일의 낡은 정보를 갱신해주면 됩니다. 여기에는 여러 가지 방법이 있으며, 각 방법의 특징을 이해하고 가장 적절한 방법을 선택하는 것이 좋습니다.

해결 방법 1: 가장 안전하고 권장되는 방법 - `ssh-keygen` 사용하기

이 방법은 SSH가 직접 제공하는 도구를 사용하여 `known_hosts` 파일에서 특정 호스트의 정보만 정확하고 깔끔하게 제거하는 가장 이상적인 방법입니다. 오류 메시지에서도 이 방법을 친절하게 안내하고 있습니다.


  remove with:
  ssh-keygen -f "/home/username/.ssh/known_hosts" -R "your-ec2-instance-ip"

ssh-keygen은 SSH 키를 생성, 관리, 변환하는 유틸리티이며, -R 옵션은 'Remove'의 약자로, 지정된 호스트 이름을 `known_hosts` 파일에서 제거하는 역할을 합니다.

실행 절차:

  1. 터미널(Mac의 Terminal, Windows의 PowerShell, WSL 또는 Git Bash 등)을 엽니다.
  2. 다음 명령어를 입력합니다. <삭제할_서버_IP_또는_도메인> 부분에 문제가 발생한 EC2 인스턴스의 IP 주소나 도메인 이름을 입력합니다.

ssh-keygen -R <삭제할_서버_IP_또는_도메인>

예시: 문제가 발생한 서버의 IP 주소가 `12.34.56.78`인 경우


ssh-keygen -R 12.34.56.78

예시: EC2의 퍼블릭 DNS 주소가 `ec2-12-34-56-78.ap-northeast-2.compute.amazonaws.com`인 경우


ssh-keygen -R ec2-12-34-56-78.ap-northeast-2.compute.amazonaws.com

실행 결과:

명령어를 실행하면 다음과 같은 메시지가 나타나며, 지정된 호스트 정보가 `known_hosts` 파일에서 제거되었음을 알려줍니다.


# Host 12.34.56.78 found: line 5
/home/username/.ssh/known_hosts updated.
Original contents retained as /home/username/.ssh/known_hosts.old

이 메시지는 `/home/username/.ssh/known_hosts` 파일의 5번째 줄에서 해당 IP 정보를 찾아 업데이트했으며, 만약을 대비해 원본 파일을 `known_hosts.old`라는 이름으로 백업해두었다는 의미입니다.

후속 조치:

이제 `known_hosts` 파일에서 이전 서버의 '신분증' 기록이 깨끗하게 사라졌습니다. 다시 평소처럼 SSH 접속을 시도합니다.


ssh -i "my-key.pem" ec2-user@12.34.56.78

그러면 맨 처음 서버에 접속했을 때와 같이, 새로운 서버의 '신분증'을 등록할 것인지 묻는 메시지가 다시 나타납니다.


The authenticity of host '12.34.56.78 (12.34.56.78)' can't be established.
...
Are you sure you want to continue connecting (yes/no/[fingerprint])?

여기서 yes를 입력하면 새로운 EC2 인스턴스의 호스트 키가 `known_hosts` 파일에 새로 등록되고, 정상적으로 접속이 완료됩니다.

이 방법의 장점:

  • 안전성: 문제가 된 특정 호스트의 정보만 정확히 제거하므로 다른 정상적인 서버의 접속 정보에 영향을 주지 않습니다.
  • 정확성: 파일 내용을 직접 수정할 때 발생할 수 있는 실수를 방지합니다.
  • 공식적인 방법: SSH 개발자들이 의도하고 권장하는 방식입니다.

해결 방법 2: 수동으로 `known_hosts` 파일 수정하기

내부적으로 어떤 일이 일어나는지 직접 확인하고 싶거나, `ssh-keygen` 명령어가 익숙하지 않은 경우 `known_hosts` 파일을 직접 편집기에서 열어 문제가 되는 라인을 삭제할 수도 있습니다. 오류 메시지에 보통 문제가 되는 라인 번호가 표시되므로 생각보다 어렵지 않습니다.


Offending ECDSA key in /home/username/.ssh/known_hosts:5

위 메시지는 `known_hosts` 파일의 5번째 줄이 문제의 원인임을 알려줍니다.

실행 절차:

  1. 선호하는 텍스트 편집기(nano, vim, emacs 또는 VS Code와 같은 GUI 편집기)로 `known_hosts` 파일을 엽니다. Linux나 macOS에서는 보통 ~/.ssh/known_hosts에 위치합니다.

nano 편집기를 사용하는 경우:


nano ~/.ssh/known_hosts

vim 편집기를 사용하는 경우:


vim ~/.ssh/known_hosts
  1. 파일을 열면 다음과 비슷한 내용을 볼 수 있습니다. 각 줄이 하나의 신뢰하는 서버 정보를 담고 있습니다. 최신 SSH 설정에서는 보안을 위해 호스트 이름과 IP가 해싱(hashing)되어 알아보기 어려울 수 있습니다.

(해싱되지 않은 경우의 예)


github.com,140.82.112.4 ssh-rsa AAAA...
gitlab.com,172.65.251.78 ssh-ed25519 AAAA...
12.34.56.78 ecdsa-sha2-nistp256 AAAA...  <-- 문제가 되는 라인!
bitbucket.org,104.192.141.1 ssh-rsa AAAA...

(해싱된 경우의 예)


|1|b3X...|pYq... ecdsa-sha2-nistp256 AAAA...
|1|jK1...|sL9... ecdsa-sha2-nistp256 AAAA... <-- 문제가 되는 라인이지만, 어느 서버인지 알기 힘듦.
  1. 오류 메시지에서 알려준 라인 번호(예: 5번째 줄)로 이동하거나, 문제가 되는 IP 주소 또는 호스트 이름이 포함된 라인을 찾습니다.
  2. 해당 라인 전체를 삭제합니다. (vim에서는 `dd` 커맨드, nano에서는 `Ctrl+K` 등으로 한 줄을 삭제할 수 있습니다.)
  3. 파일을 저장하고 편집기를 종료합니다. (nano에서는 `Ctrl+X`, `Y`, `Enter`. vim에서는 `:wq`)
  4. 이제 해결 방법 1과 마찬가지로 다시 SSH 접속을 시도하고, yes를 입력하여 새로운 키를 등록하면 됩니다.

이 방법의 장단점:

  • 장점: `known_hosts` 파일의 구조를 직접 눈으로 확인할 수 있어 학습에 도움이 됩니다.
  • 단점: 실수로 다른 중요한 서버의 키를 삭제할 위험이 있습니다. 특히 호스트 이름이 해싱된 경우, 정확한 라인을 찾기가 까다로울 수 있어 라인 번호 정보가 없다면 권장되지 않습니다.

해결 방법 3: 빠르고 거칠지만 추천하지 않는 방법 - `known_hosts` 파일 전체 삭제/이름 변경

가장 빠르고 간단하게 문제를 회피하는 방법은 `known_hosts` 파일 자체를 삭제하거나 이름을 바꿔버리는 것입니다.


# 파일 삭제
rm ~/.ssh/known_hosts

# 또는 파일 이름 변경 (조금 더 안전한 백업)
mv ~/.ssh/known_hosts ~/.ssh/known_hosts.bak

이 명령어를 실행하면 '보안 연락처' 자체가 사라집니다. 따라서 다음에 어떤 서버에 접속하든, 심지어 이전에 문제없이 잘 접속하던 다른 모든 서버(예: GitHub, 회사 내부 서버 등)에 대해서도 처음 접속하는 것처럼 "Are you sure you want to continue connecting (yes/no)?"라는 질문을 다시 받게 됩니다.

이 방법은 왜 추천하지 않는가?

  • 보안 수준 저하: 이 방법은 모든 서버에 대한 신뢰 정보를 초기화합니다. 이는 모든 문의 '신뢰의 증표'를 없애고 매번 신분증을 새로 확인하는 것과 같습니다. 만약 사용자가 무의식적으로 모든 연결에 yes를 누르는 습관이 있다면, 실제 중간자 공격이 발생했을 때 알아채지 못하고 공격에 노출될 수 있습니다.
  • 불편함: 관리하는 서버가 많을수록 모든 서버의 키를 다시 확인하고 등록해야 하므로 매우 번거롭습니다.

이 방법은 오직 관리하는 서버가 단 하나뿐이고, 다른 중요한 서버 접속 기록이 전혀 없는, 완전히 격리된 테스트 환경에서만 최후의 수단으로 고려해볼 수 있습니다.

3. 예방 및 고급 팁: 애초에 오류를 마주하지 않으려면?

문제를 해결하는 것도 중요하지만, 더 나은 방법은 애초에 이런 상황을 덜 마주치도록 환경을 구성하는 것입니다.

3.1. 인스턴스 종료(Terminate) vs 정지(Stop)

EC2 인스턴스를 잠시 사용하지 않을 때는 '종료(Terminate)' 대신 '정지(Stop)'하는 습관을 들이는 것이 좋습니다.

  • 정지(Stop): 인스턴스는 꺼지지만, 루트 볼륨(EBS)과 설정 정보(호스트 키 포함)는 그대로 보존됩니다. 다시 '시작(Start)'하면 원래의 상태 그대로 부팅됩니다. 따라서 호스트 키가 변경되지 않아 SSH 오류가 발생하지 않습니다. (단, 퍼블릭 IP는 변경될 수 있으므로 탄력적 IP를 사용하는 것이 좋습니다.)
  • 종료(Terminate): 인스턴스와 연결된 루트 볼륨이 완전히 삭제됩니다(설정에 따라 보존도 가능). 이는 가상 머신을 영구적으로 폐기하는 것과 같습니다. 나중에 같은 IP로 새 인스턴스를 만들어도 그것은 완전히 다른 컴퓨터이므로 호스트 키도 다릅니다.

단순히 개발/테스트를 잠시 멈추는 경우라면 '정지'를 활용하여 불필요한 SSH 키 충돌을 예방할 수 있습니다.

3.2. SSH 설정 파일(`~/.ssh/config`) 활용하기

매번 긴 SSH 명령어를 입력하는 대신, ~/.ssh/config 파일을 활용하면 접속을 훨씬 편리하고 체계적으로 관리할 수 있으며, 이 문제에 대한 임시 해결책도 적용할 수 있습니다.

~/.ssh/config 파일에 다음과 같이 호스트 정보를 등록합니다.


# ~/.ssh/config 파일

Host my-dev-server
    HostName 12.34.56.78
    User ec2-user
    IdentityFile ~/.ssh/my-key.pem

Host my-prod-server
    HostName 56.78.12.34
    User ubuntu
    IdentityFile ~/.ssh/prod-key.pem

이렇게 설정하면, 이제 터미널에서 ssh my-dev-server 라는 간단한 명령만으로 접속할 수 있습니다.

만약 특정 호스트가 매우 자주 재생성되어 `REMOTE HOST IDENTIFICATION HAS CHANGED` 오류가 반복적으로 발생하는 임시 테스트 서버라면, 다음과 같은 옵션을 주의해서 추가할 수 있습니다.


Host temp-test-instance
    HostName 12.34.56.99
    User ec2-user
    IdentityFile ~/.ssh/test-key.pem
    # 아래 두 옵션은 보안 검사를 비활성화하므로 주의가 필요합니다.
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
  • StrictHostKeyChecking no: `known_hosts` 파일에 키가 없거나 변경되었을 때, 질문하지 않고 자동으로 키를 추가하거나 업데이트합니다. 이는 편리하지만 중간자 공격에 취약해집니다.
  • UserKnownHostsFile /dev/null: 이 호스트에 대한 키 정보를 `known_hosts` 파일에 아예 기록하지 않습니다. 매번 연결할 때마다 서버 키를 확인하지 않게 됩니다.

경고: 이 옵션들은 SSH의 핵심 보안 기능을 비활성화하는 것입니다. 중요한 프로덕션 서버나 개인정보를 다루는 서버에는 절대로 사용해서는 안 됩니다. 오직 내용이 언제든 사라져도 상관없는, 신뢰할 수 있는 네트워크 내의 일회성 테스트 인스턴스에만 제한적으로 사용해야 합니다.

결론: 오류 메시지는 적이 아닌 친구

'REMOTE HOST IDENTIFICATION HAS CHANGED!'는 처음 마주하면 당황스럽고 위협적으로 느껴지는 오류입니다. 하지만 그 이면에는 우리의 연결을 안전하게 보호하려는 SSH의 충실한 보안 메커니즘이 있습니다. 이 경고는 "당신이 접속하려는 서버의 신원이 바뀌었습니다. 의도한 변경이 맞는지 확인해주세요."라고 우리에게 보내는 중요한 신호입니다.

이제 우리는 이 오류의 원인이 EC2 환경에서 IP 주소는 유지된 채 서버 인스턴스 자체가 교체되었을 때 주로 발생한다는 사실을 알았습니다. 또한, 가장 안전하고 권장되는 해결책은 `ssh-keygen -R ` 명령어를 사용하여 오래된 키 정보를 깔끔하게 제거하는 것임을 배웠습니다.

이 경험을 통해 우리는 단순히 문제를 해결하는 것을 넘어, SSH가 어떻게 우리의 통신을 보호하는지, 그리고 `known_hosts` 파일이 어떤 중요한 역할을 하는지에 대해 더 깊이 이해하게 되었습니다. 다음에 이 메시지를 다시 만나더라도, 당황하지 않고 "아, 서버가 바뀌었구나. 이전 기록을 지워주고 새롭게 신뢰 관계를 맺어야지"라고 차분하게 대처할 수 있는 능력을 갖추게 된 것입니다. 클라우드 시대를 살아가는 개발자와 엔지니어에게 이러한 기본적인 보안 원리를 이해하는 것은 더욱 강력하고 안정적인 시스템을 구축하는 밑거름이 될 것입니다.

Wednesday, August 22, 2018

AWS EC2 ssh 접속시 'Permissions 0644 for '___.pem' are too open.' 에러 해결법

SSH로 AWS EC2에 접속할 때 권한 오류가 발생하는 경우

SSH로 AWS EC2에 접속할 때 다음과 같은 권한 오류가 발생할 수 있습니다.

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'xxx.pem' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: xxx.pem
Permission denied (publickey).
  

이러한 오류는 AWS EC2의 pem 파일 권한이 잘못 설정되어 발생합니다. pem 파일 권한을 변경하려면 다음 단계를 따르세요.

  1. 터미널을 열고 pem 파일의 위치로 이동합니다.
  2. 다음 명령을 입력합니다.chmod 400 xxx.pem
  3. 명령을 실행한 후 다시 SSH로 AWS EC2에 접속해 보세요.

이렇게 하면 권한 오류가 해결되고 AWS EC2에 접속할 수 있습니다.