ページ

ラベル AWS の投稿を表示しています。 すべての投稿を表示
ラベル AWS の投稿を表示しています。 すべての投稿を表示

2015年10月7日水曜日

VagrantでAWSのEC2を使う


今回はVagrantを使ってAWSのEC2のインスタンスを操作してみたいと思います。
※AWSのアカウントを持っておりVagrantがインストールされている前提です。


IAMユーザーの作成


AWSサービスにAPIでアクセスする為にアクセスキーを作成する必要があります
アクセスキーを作成する為IAMユーザーを作成します
  • グループの作成
まずはIAMコンソールにアクセスしログインする
メニューからグループを選択し「新しいグループの作成」 をクリック

適当なグループ名を設定します。ここではDevelopersを設定

ポリシーのアタッチではグループに権限を設定することができます。
とりあえずPowerUserAccessに設定

最後に確認画面で内容が正しければ「グループの作成」をクリックし作成する
グループ一覧画面に作成したグループが表示されていればOK

  • ユーザーの作成
メニューからユーザーを選択し「新しいユーザーの作成」 をクリック

今回は1ユーザーしか作成しないので、ユーザー名に適当な名前を入力し「作成」
今回はvagrantの名前でユーザーを作成

作成されたら「ユーザーのセキュリティ認証情報を表示」をクリックしアクセスキーをメモ、または「認証情報のダウンロード」をクリックしCSVファイルで保管

ユーザーにグループを紐付かせる為、ユーザー一覧から作成したユーザーをクリックし
「グループにユーザーを追加」 をクリック

先ほど作成したグループを選択し「グループに追加」

EC2側の設定


EC2 Management Consoleを開く
  • キーペアの作成 キーペアの作成はここを参照
  • セキュリティグループの作成
sshICMPを通すようなセキュリティグループを作成する
今回はvagrantの名前でセキュリティグループを作成

  • 起動するAMIのIDを確認
vagrantで起動したいAMIのIDを確認する為に、メニューから
「インスタンスの作成」を選択

今回はAmazon Linuxを起動する為、Amazon LinuxのIDを確認

※リージョン毎にIDが異なるらしいので注意!!

Vagrant側の設定


  • AWSプラグインのインストール
$ vagrant plugin install vagrant-aws
Installing the 'vagrant-aws' plugin. This can take a few minutes...
Installed the plugin 'vagrant-aws (0.6.0)'!
  • Vagrantfile編集
vagrant initでVagrantfileができたら↓に編集
# -*- mode: ruby -*-
# vi: set ft=ruby :

AWS_ACCESS_KEY_ID = "XXXXXXXXX" # 保存したアクセスキー
AWS_SECRET_KEY = "XXXXXXXXXXXX" # 保存したシークレットキー

Vagrant.configure(2) do |config|
  config.vm.box = "dummy"
  config.vm.box_url = "https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box"
  config.vm.synced_folder ".", "/vagrant", disabled: true

  config.vm.provider "aws" do |aws, override|
    aws.ami = "XXXXXXXXXXXXX" # 確認したAMI-ID
    aws.tags = { 'Name' => 'VagrantEC2' } # 適当な名前に設定
    aws.instance_type = "t2.micro" # 必要に応じて調整
    aws.security_groups = "vagrant" # 作成したセキュリティグループ
    aws.access_key_id = AWS_ACCESS_KEY_ID
    aws.secret_access_key = AWS_SECRET_KEY
    aws.region = "ap-northeast-1" # 必要に応じて調整
    aws.keypair_name = "XXXX" # 作成したキーペア
    override.ssh.username = "ec2-user"
    override.ssh.private_key_path = "~/.ssh/XXXX.pem" # 作成したキーペア
  end
end
config.vm.boxは今回関係ないのでダミーを設定
公式サイトと同様に設定
いざ!!Vagrantを起動してみる
vagrant up --provider=aws
エラー無く起動すればEC2のインスタンスが起動する
マネジメントコンソールからも確認出来る

後は普通にVagrantと同じように操作が可能
  • 起動
$ vagrant ssh

       __|  __|_  )
       _|  (     /   Amazon Linux AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-ami/2015.09-release-notes/
No packages needed for security; 7 packages available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-XXX-XX-XX-XXX ~]$
  • 状態確認
$ vagrant status
Current machine states:

default                   running (aws)

The EC2 instance is running. To stop this machine, you can run
`vagrant halt`. To destroy the machine, you can run `vagrant destroy`.
  • 停止
$ vagrant halt
  • 削除
$ vagrant destory -f

2014年10月10日金曜日

AWSにお世話になる 6 - PHPで遊ぶ -

PHPでWEBページのパースとJSON出力を行う

※その前に・・・TeraTermでのEC2接続
1. TeraTerm起動し、IPアドレスを入力















2. セキュリティ警告が出るが、IPが変わるので無視



















3. ユーザ名に「ec2-user」を秘密鍵 RSA/DSA/~を使うにチェックし、秘密鍵に
     作成したXXX.pemファイルを指定























これで接続できるはず^^

apache, php, mysqlのインストール

※環境・・・Amazon Linux
以下コマンドを実行。
  sudo yum -y install apache php mysql

また、phpでよく使われるらしいmbstringも入れる。
  sudo yum -y install php-mbstring

起動、設定
  ・起動
  sudo service start httpd

  ・Linux起動時にサービスがスタートするように設定
  sudo chkconfig httpd on

テスト用のphpページ作成
<?php
  phpinfo();
?>

↓ブラウザでアクセス



















PHPでのJSON出力

びっくりするぐらい簡単にできた^^;
以下参考URL
http://webdelog.info/blog/2012/01/12/php-output-json.html

PHPでのWEBページ読み込み

こちらもすんなりいけそう。。
以下参考URL
http://webings.net/php/filegetcontents/

が、

文字コードがちゃんとできてないごたorz
webページを読み込む file_get_contentsで取得したコンテンツを
mb_convert_encodingで文字コード変換できるらしい。

以下参考URL
http://blogs.yahoo.co.jp/nob_ll/45477291.html
http://jp2.php.net/manual/ja/mbstring.supported-encodings.php

2014年8月9日土曜日

AWSにお世話になる 5 - LDAP -

LDAP(認証)サーバーの導入と設定


LDAPについて・・・
LDAP(Lightweight Directory Access Protocol)はTCP/IP上で稼働するX-500をベースとするディレクトリサービス。
ディレクトリは「エントリ」という単位で構成、DIT(Directory Information Tree)と呼ばれる階層を持つ。各エントリは個別識別子であるDN(Distinguished Name)と属性、オブジェクトクラスを持ち、LDIF(LDAP Data Interchange Format)と呼ばれるテキスト形式で記述。



















1. OpenLDAPの導入
サーバー名とドメイン名が正しく設定されているか確認。
ubuntu@chopper:~$ cat /etc/hostname
chopper
ubuntu@chopper:~$ cat /etc/hosts

127.0.0.1 chopper.tony.com chopper

※書籍ではドメイン名がお名前.comで取得したドメイン名だったので
  もしかしたらうまく導入できないかも。。。

OpenLDAPインストール
ubuntu@chopper:~$ sudo apt-get install -y slapd ldap-utils db5.1-util
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  libdb5.1 libltdl7 libodbc1 libperl5.18 libslp1
Suggested packages:
  libmyodbc odbc-postgresql tdsodbc unixodbc-bin slpd openslp-doc
The following NEW packages will be installed:
  db5.1-util ldap-utils libdb5.1 libltdl7 libodbc1 libperl5.18 libslp1 slapd
0 upgraded, 8 newly installed, 0 to remove and 4 not upgraded.
Need to get 2,343 kB of archives.
After this operation, 7,904 kB of additional disk space will be used.
Get:1 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/universe libdb5.1 amd64 5.1.29-7ubuntu1 [580 kB]
Get:2 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main libltdl7 amd64 2.4.2-1.7ubuntu1 [35.0 kB]
Get:3 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main libodbc1 amd64 2.2.14p2-5ubuntu5 [175 kB]
Get:4 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main libperl5.18 amd64 5.18.2-2ubuntu1 [1,322 B]
Get:5 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main libslp1 amd64 1.2.1-9 [45.1 kB]
Get:6 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main slapd amd64 2.4.31-1+nmu2ubuntu8 [1,317 kB]
Get:7 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/universe db5.1-util amd64 5.1.29-7ubuntu1 [66.6 kB]
Get:8 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main ldap-utils amd64 2.4.31-1+nmu2ubuntu8 [123 kB]
Fetched 2,343 kB in 0s (3,414 kB/s)
Preconfiguring packages ...
Selecting previously unselected package libdb5.1:amd64.
(Reading database ... 51210 files and directories currently installed.)
Preparing to unpack .../libdb5.1_5.1.29-7ubuntu1_amd64.deb ...
Unpacking libdb5.1:amd64 (5.1.29-7ubuntu1) ...
Selecting previously unselected package libltdl7:amd64.
Preparing to unpack .../libltdl7_2.4.2-1.7ubuntu1_amd64.deb ...
Unpacking libltdl7:amd64 (2.4.2-1.7ubuntu1) ...
Selecting previously unselected package libodbc1:amd64.
Preparing to unpack .../libodbc1_2.2.14p2-5ubuntu5_amd64.deb ...
Unpacking libodbc1:amd64 (2.2.14p2-5ubuntu5) ...
Selecting previously unselected package libperl5.18.
Preparing to unpack .../libperl5.18_5.18.2-2ubuntu1_amd64.deb ...
Unpacking libperl5.18 (5.18.2-2ubuntu1) ...
Selecting previously unselected package libslp1.
Preparing to unpack .../libslp1_1.2.1-9_amd64.deb ...
Unpacking libslp1 (1.2.1-9) ...
Selecting previously unselected package slapd.
Preparing to unpack .../slapd_2.4.31-1+nmu2ubuntu8_amd64.deb ...
Unpacking slapd (2.4.31-1+nmu2ubuntu8) ...
Selecting previously unselected package db5.1-util.
Preparing to unpack .../db5.1-util_5.1.29-7ubuntu1_amd64.deb ...
Unpacking db5.1-util (5.1.29-7ubuntu1) ...
Selecting previously unselected package ldap-utils.
Preparing to unpack .../ldap-utils_2.4.31-1+nmu2ubuntu8_amd64.deb ...
Unpacking ldap-utils (2.4.31-1+nmu2ubuntu8) ...
Processing triggers for ureadahead (0.100.0-16) ...
Processing triggers for ufw (0.34~rc-0ubuntu2) ...
Processing triggers for man-db (2.6.7.1-1) ...
Setting up libdb5.1:amd64 (5.1.29-7ubuntu1) ...
Setting up libltdl7:amd64 (2.4.2-1.7ubuntu1) ...
Setting up libodbc1:amd64 (2.2.14p2-5ubuntu5) ...
Setting up libperl5.18 (5.18.2-2ubuntu1) ...
Setting up libslp1 (1.2.1-9) ...
Setting up slapd (2.4.31-1+nmu2ubuntu8) ...
  Creating new user openldap... done.
  Creating initial configuration... done.
  Creating LDAP directory... done.
 * Starting OpenLDAP slapd                                                         [ OK ] 
Setting up db5.1-util (5.1.29-7ubuntu1) ...
Setting up ldap-utils (2.4.31-1+nmu2ubuntu8) ...
Processing triggers for libc-bin (2.19-0ubuntu6) ...
Processing triggers for ureadahead (0.100.0-16) ...

Processing triggers for ufw (0.34~rc-0ubuntu2) ...

途中LDAPの管理者パスワードを設定する
























2. OpenLDAPの基本構成と基本コマンド
UbuntuのOpenLDAPでは「/etc/ldap/slapd.conf」設定ファイルによる管理は行いません。
LDAP管理の為の独立したDITがあり、LDAPサーバー(slapdデーモン)を再起動しなくても動的に構成を変更できる仕組みになっています。これらの手法は「slapd-configメソッド」や「RTC(Real Time Configuration)」メソッド、「cn=configメソッド」と呼ばれています。

具体的にはLDAPの構成ファイルが「/etc/ldap/slapd.d」のディレクトリ下で、テキスト形式のLDIFファイル(拡張子「.ldif」)で管理されています。

OpenLDAPでは、2つのDITがあり、cn=config DITとは別にドメインデータDITがあります。それぞれで使用するコマンドオプション、LDAPプロトコル、実行者権限が異なる。

・OpenLDAPの基本コマンド
    ldapsearch      -> LDAPディレクトリからエントリを検索
    ldapadd           -> LDAPディレクトリへエントリを追加
    ldapmodify     -> LDAPディレクトリのエントリを更新
    ldapdelete       -> LDAPディレクトリからエントリを削除
    slapcat            -> LDAPディレクトリからLDIFファイルをエクスポートする

例)cn=configからdnを検索
ubuntu@chopper:~$ sudo ldapsearch -Q -LLL -Y EXTERNAL -H ldapi:/// -b cn=config dn
dn: cn=config

dn: cn=module{0},cn=config

dn: cn=schema,cn=config

dn: cn={0}core,cn=schema,cn=config

dn: cn={1}cosine,cn=schema,cn=config

dn: cn={2}nis,cn=schema,cn=config

dn: cn={3}inetorgperson,cn=schema,cn=config

dn: olcBackend={0}hdb,cn=config

dn: olcDatabase={-1}frontend,cn=config

dn: olcDatabase={0}config,cn=config


dn: olcDatabase={1}hdb,cn=config

肝心のドメインがうまくできているかですが。。。
ubuntu@chopper:~$ ldapsearch -x -LLL -b dc=chopper,dc=tony,dc=com
No such object (32)

Matched DN: dc=tony,dc=com

ダメごたーでしたorz
という事で、LDAPは一時中断で^^;

AWSにお世話になる 4 - VPC設定 -

VPNを利用したVPCの設定

セキュリティグループをIPアドレスが「10.8.0.n(n=1~254)」だけを通す様に設定する。
ICMPについてはpingのみを有効にする。
ただし、UDP:123とUDP:1194だけは開いておかないと各サーバーにアクセスできない。
  UDP:123 -> NTPが使用
  UDP:1194 -> OpenVPN自身が使用

・現在の設定





















SSHとICMPを変更
・変更後









検証してみる
・VPN接続し、10.8.0.1でpingやssh接続を行う
$ ping -c3 10.8.0.1
PING 10.8.0.1 (10.8.0.1): 56 data bytes
64 bytes from 10.8.0.1: icmp_seq=0 ttl=64 time=29.541 ms
64 bytes from 10.8.0.1: icmp_seq=1 ttl=64 time=28.900 ms
64 bytes from 10.8.0.1: icmp_seq=2 ttl=64 time=33.298 ms

--- 10.8.0.1 ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 28.900/30.580/33.298/1.940 ms

$ ssh -i coby.pem ubuntu@10.8.0.1
Welcome to Ubuntu 14.04.1 LTS (GNU/Linux 3.13.0-29-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

  System information as of Sat Aug  9 13:38:16 JST 2014

  System load:  0.0               Processes:           123
  Usage of /:   10.4% of 7.74GB   Users logged in:     0
  Memory usage: 7%                IP address for eth0: 172.31.2.237
  Swap usage:   0%

  => There is 1 zombie process.

  Graph this data and manage this system at:
    https://landscape.canonical.com/

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud


Last login: Sat Aug  2 18:46:50 2014 from kd106172180044.ppp-bb.dion.ne.jp
ubuntu@chopper:~$ ls
2.x  2.x.zip  ca.crt  pair_mba.crt  pair_mba.key

どちらも正常に接続できる事を確認。

・パブリックIPでpingやssh接続を行う
$ ping -c3 54.64.12.196
PING 54.64.12.196 (54.64.12.196): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1

--- 54.64.12.196 ping statistics ---
3 packets transmitted, 0 packets received, 100.0% packet loss
$ ssh -i coby.pem ubuntu@54.64.12.196
^C

どちらも接続できない事を確認

ちゃんとVPCが設定されている様子^^

2014年8月2日土曜日

AWSにお世話になる 3 - VPN設定 -

今回はVPNの設定。

書籍通りOpenVPNで環境構築。

1. セキュリティグループの設定











UDP 1194ポートを解放する。

2. OpenVPNのインストール
ubuntu@chopper:~$ sudo apt-get install -y openvpn
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  liblzo2-2 libpkcs11-helper1
Suggested packages:
  easy-rsa
The following NEW packages will be installed:
  liblzo2-2 libpkcs11-helper1 openvpn
0 upgraded, 3 newly installed, 0 to remove and 4 not upgraded.
Need to get 469 kB of archives.
After this operation, 1,339 kB of additional disk space will be used.
Get:1 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty-updates/main liblzo2-2 amd64 2.06-1.2ubuntu1.1 [46.1 kB]
Get:2 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main libpkcs11-helper1 amd64 1.11-1 [42.2 kB]
Get:3 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main openvpn amd64 2.3.2-7ubuntu3 [380 kB]
Fetched 469 kB in 0s (1,027 kB/s)
Preconfiguring packages ...
Selecting previously unselected package liblzo2-2:amd64.
(Reading database ... 51108 files and directories currently installed.)
Preparing to unpack .../liblzo2-2_2.06-1.2ubuntu1.1_amd64.deb ...
Unpacking liblzo2-2:amd64 (2.06-1.2ubuntu1.1) ...
Selecting previously unselected package libpkcs11-helper1:amd64.
Preparing to unpack .../libpkcs11-helper1_1.11-1_amd64.deb ...
Unpacking libpkcs11-helper1:amd64 (1.11-1) ...
Selecting previously unselected package openvpn.
Preparing to unpack .../openvpn_2.3.2-7ubuntu3_amd64.deb ...
Unpacking openvpn (2.3.2-7ubuntu3) ...
Processing triggers for man-db (2.6.7.1-1) ...
Processing triggers for ureadahead (0.100.0-16) ...
Setting up liblzo2-2:amd64 (2.06-1.2ubuntu1.1) ...
Setting up libpkcs11-helper1:amd64 (1.11-1) ...
Setting up openvpn (2.3.2-7ubuntu3) ...
 * Restarting virtual private network daemon(s)...                                         *   No VPN is running.
Processing triggers for libc-bin (2.19-0ubuntu6) ...
Processing triggers for ureadahead (0.100.0-16) ...

設定に必要なファイルをダウンロード。
ubuntu@chopper:~$ wget https://github.com/OpenVPN/easy-rsa/archive/release/2.x.zip
--2014-08-02 17:09:07--  https://github.com/OpenVPN/easy-rsa/archive/release/2.x.zip
Resolving github.com (github.com)... 192.30.252.130
Connecting to github.com (github.com)|192.30.252.130|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://codeload.github.com/OpenVPN/easy-rsa/zip/release/2.x [following]
--2014-08-02 17:09:08--  https://codeload.github.com/OpenVPN/easy-rsa/zip/release/2.x
Resolving codeload.github.com (codeload.github.com)... 192.30.252.145
Connecting to codeload.github.com (codeload.github.com)|192.30.252.145|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/zip]
Saving to: ‘2.x.zip’

    [   <=>                                           ] 47,064       100KB/s   in 0.5s   

2014-08-02 17:09:09 (100 KB/s) - ‘2.x.zip’ saved [47064]

ubuntu@chopper:~$ ls
2.x.zip

ZIPファイルの解凍
ubuntu@chopper:~$ sudo apt-get install -y unzip
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Suggested packages:
  zip
The following NEW packages will be installed:
  unzip
0 upgraded, 1 newly installed, 0 to remove and 4 not upgraded.
Need to get 193 kB of archives.
After this operation, 390 kB of additional disk space will be used.
Get:1 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ trusty/main unzip amd64 6.0-9ubuntu1 [193 kB]
Fetched 193 kB in 0s (3,367 kB/s)
Selecting previously unselected package unzip.
(Reading database ... 51192 files and directories currently installed.)
Preparing to unpack .../unzip_6.0-9ubuntu1_amd64.deb ...
Unpacking unzip (6.0-9ubuntu1) ...
Processing triggers for mime-support (3.54ubuntu1) ...
Processing triggers for man-db (2.6.7.1-1) ...
Setting up unzip (6.0-9ubuntu1) ...
ubuntu@chopper:~$ unzip -d 2.x 2.x.zip

rootユーザで必要なファイルをコピー
root@chopper:/home/ubuntu# mkdir /etc/openvpn/easy-rsa
root@chopper:/home/ubuntu# ls
2.x  2.x.zip
root@chopper:/home/ubuntu# pwd
/home/ubuntu
root@chopper:/home/ubuntu# cd 2.x
2.x/     2.x.zip  
root@chopper:/home/ubuntu# cd 2.x
root@chopper:/home/ubuntu/2.x# ls
easy-rsa-release-2.x
root@chopper:/home/ubuntu/2.x# cd easy-rsa-release-2.x/
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x# ls
configure.ac  COPYING  COPYRIGHT.GPL  distro  doc  easy-rsa  Makefile.am  README
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x# cd easy-rsa/
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x/easy-rsa# ls
2.0  Windows
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x/easy-rsa# cd 2.0/
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x/easy-rsa/2.0# ls
build-ca        build-key-pkcs12  inherit-inter      pkitool          whichopensslcnf
build-dh        build-key-server  list-crl           revoke-full
build-inter     build-req         openssl-0.9.6.cnf  sign-req
build-key       build-req-pass    openssl-0.9.8.cnf  sign-server-req
build-key-pass  clean-all         openssl-1.0.0.cnf  vars

root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x/easy-rsa/2.0# cp -r * /etc/openvpn/easy-rsa/
root@chopper:/home/ubuntu# mkdir /etc/openvpn/easy-rsa
root@chopper:/home/ubuntu# ls
2.x  2.x.zip
root@chopper:/home/ubuntu# pwd
/home/ubuntu
root@chopper:/home/ubuntu# cd 2.x
2.x/     2.x.zip  
root@chopper:/home/ubuntu# cd 2.x
root@chopper:/home/ubuntu/2.x# ls
easy-rsa-release-2.x
root@chopper:/home/ubuntu/2.x# cd easy-rsa-release-2.x/
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x# ls
configure.ac  COPYING  COPYRIGHT.GPL  distro  doc  easy-rsa  Makefile.am  README
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x# cd easy-rsa/
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x/easy-rsa# ls
2.0  Windows
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x/easy-rsa# cd 2.0/
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x/easy-rsa/2.0# ls
build-ca        build-key-pkcs12  inherit-inter      pkitool          whichopensslcnf
build-dh        build-key-server  list-crl           revoke-full
build-inter     build-req         openssl-0.9.6.cnf  sign-req
build-key       build-req-pass    openssl-0.9.8.cnf  sign-server-req
build-key-pass  clean-all         openssl-1.0.0.cnf  vars
root@chopper:/home/ubuntu/2.x/easy-rsa-release-2.x/easy-rsa/2.0# cp -r * /etc/openvpn/easy-rsa/


/etc/openvpn/easy-rsa/varsの修正
root@chopper:/etc/openvpn/easy-rsa# diff vars vars.org 
64,68c64,68
< export KEY_COUNTRY="JP"
< export KEY_PROVINCE=“XXXXXX-ken"
< export KEY_CITY=“XXXXXXX-shi"
< export KEY_ORG=“XXXXXXX"
< export KEY_EMAIL=“XXXXXXXXXXXXXXXXX"
---
> export KEY_COUNTRY="US"
> export KEY_PROVINCE="CA"
> export KEY_CITY="SanFrancisco"
> export KEY_ORG="Fort-Funston"
> export KEY_EMAIL="me@myhost.mydomain"

CA認証鍵ペア(公開鍵/秘密鍵)の作成
root@chopper:/etc/openvpn/easy-rsa# ./clean-all
root@chopper:/etc/openvpn/easy-rsa# ./build-ca
Generating a 2048 bit RSA private key
..................................................................+++
..............................................................................................+++
writing new private key to 'ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [JP]:
State or Province Name (full name) [XXXXXX-ken]:
Locality Name (eg, city) [XXXXXXX-shi]:
Organization Name (eg, company) [XXXXXXX]:
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:.
Common Name (eg, your name or your server's hostname) [XXXXXXX CA]:.
Name [EasyRSA]:XXXXXXXXXXXX
Email Address [XXXXXXXXX@gmail.com]:

作成されたか確認
root@chopper:/etc/openvpn/easy-rsa# ls -la keys
total 20
drwx------ 2 root root 4096 Aug  2 17:20 .
drwxr-xr-x 3 root root 4096 Aug  2 17:19 ..
-rw-r--r-- 1 root root 1639 Aug  2 17:20 ca.crt
-rw------- 1 root root 1704 Aug  2 17:20 ca.key
-rw-r--r-- 1 root root    0 Aug  2 17:19 index.txt
-rw-r--r-- 1 root root    3 Aug  2 17:19 serial

サーバー認証鍵ペア(公開鍵/秘密鍵)の作成
サーバー認証鍵の名前:kizaru
root@chopper:/etc/openvpn/easy-rsa# ./build-key-server kizaru
Generating a 2048 bit RSA private key
..................+++
..................................................................................................................+++
writing new private key to 'kizaru.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [JP]:
State or Province Name (full name) [XXXXXXX-ken]:
Locality Name (eg, city) [XXXXXXX-shi]:
Organization Name (eg, company) [XXXXXXX]:
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:.
Common Name (eg, your name or your server's hostname) [kizaru]:
Name [EasyRSA]:XXXXXXXXXXXXXX
Email Address [XXXXXXXXXXX@gmail.com]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:.
An optional company name []:.
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'JP'
stateOrProvinceName   :PRINTABLE:’XXXXXXXXXXX'
localityName          :PRINTABLE:’XXXXXXXXXXX'
organizationName      :PRINTABLE:’XXXXXX'
commonName            :PRINTABLE:’XXXXXX'
name                  :PRINTABLE:’XXXXXXXXXXXXXXXXX'
emailAddress          :IA5STRING:’XXXXXXXXX@gmail.com'
Certificate is to be certified until Jul 30 08:25:29 2024 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

確認
root@chopper:/etc/openvpn/easy-rsa# ls -la keys
total 56
drwx------ 2 root root 4096 Aug  2 17:25 .
drwxr-xr-x 3 root root 4096 Aug  2 17:19 ..
-rw-r--r-- 1 root root 5410 Aug  2 17:25 01.pem
-rw-r--r-- 1 root root 1639 Aug  2 17:20 ca.crt
-rw------- 1 root root 1704 Aug  2 17:20 ca.key
-rw-r--r-- 1 root root  138 Aug  2 17:25 index.txt
-rw-r--r-- 1 root root   21 Aug  2 17:25 index.txt.attr
-rw-r--r-- 1 root root    0 Aug  2 17:19 index.txt.old
-rw-r--r-- 1 root root 5410 Aug  2 17:25 kizaru.crt
-rw-r--r-- 1 root root 1074 Aug  2 17:25 kizaru.csr
-rw------- 1 root root 1704 Aug  2 17:25 kizaru.key
-rw-r--r-- 1 root root    3 Aug  2 17:25 serial
-rw-r--r-- 1 root root    3 Aug  2 17:19 serial.old

ディフィー・ヘルマン(Diffie Hellman)パラメータを生成
http://ja.wikipedia.org/wiki/ディフィー・ヘルマン鍵共有

root@chopper:/etc/openvpn/easy-rsa# ./build-dh
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
...............................................................................................................................................................................................................................................................................................................+.....................................................................................................................................+...........................................................................................................................................................+............................................+.............................................................................................................................................................+........................................................................+...................................................................+..+..............................................+.................................................................................................................+.........................................+...............................................................................................................................................................+.......................................................................................................................+.........................+........................................................................+............+.+.................................................................................................................................................................................................................................................+......++*++*
root@chopper:/etc/openvpn/easy-rsa# ls -la keys
total 60
drwx------ 2 root root 4096 Aug  2 17:29 .
drwxr-xr-x 3 root root 4096 Aug  2 17:19 ..
-rw-r--r-- 1 root root 5410 Aug  2 17:25 01.pem
-rw-r--r-- 1 root root 1639 Aug  2 17:20 ca.crt
-rw------- 1 root root 1704 Aug  2 17:20 ca.key
-rw-r--r-- 1 root root  424 Aug  2 17:29 dh2048.pem
-rw-r--r-- 1 root root  138 Aug  2 17:25 index.txt
-rw-r--r-- 1 root root   21 Aug  2 17:25 index.txt.attr
-rw-r--r-- 1 root root    0 Aug  2 17:19 index.txt.old
-rw-r--r-- 1 root root 5410 Aug  2 17:25 kizaru.crt
-rw-r--r-- 1 root root 1074 Aug  2 17:25 kizaru.csr
-rw------- 1 root root 1704 Aug  2 17:25 kizaru.key
-rw-r--r-- 1 root root    3 Aug  2 17:25 serial
-rw-r--r-- 1 root root    3 Aug  2 17:19 serial.old

各ファイルを「/etc/openvpn」へコピー
root@chopper:/etc/openvpn/easy-rsa# cd keys
root@chopper:/etc/openvpn/easy-rsa/keys# ls
01.pem  ca.key      index.txt       index.txt.old  kizaru.csr  serial
ca.crt  dh2048.pem  index.txt.attr  kizaru.crt     kizaru.key  serial.old
root@chopper:/etc/openvpn/easy-rsa/keys# cp ca.crt kizaru.crt kizaru.key dh2048.pem /etc/openvpn

サーバーコンフィグレーションファイルの設定
root@chopper:/usr/share/doc/openvpn/examples/sample-config-files# cp server.conf.gz /etc/openvpn/
root@chopper:/usr/share/doc/openvpn/examples/sample-config-files# cd /etc/openvpn/
root@chopper:/etc/openvpn# ls
ca.crt  dh2048.pem  easy-rsa  kizaru.crt  kizaru.key  server.conf.gz  update-resolv-conf
root@chopper:/etc/openvpn# gunzip server.conf.gz 
root@chopper:/etc/openvpn# ls
ca.crt  dh2048.pem  easy-rsa  kizaru.crt  kizaru.key  server.conf  update-resolv-conf
root@chopper:/etc/openvpn# cp -p server.conf server.conf.org
root@chopper:/etc/openvpn# vi server.conf
root@chopper:/etc/openvpn# diff server.conf server.conf.org
79,80c79,80
< cert kizaru.crt
< key kizaru.key  # This file should be kept secret
---
> cert server.crt
> key server.key  # This file should be kept secret
87c87
< dh dh2048.pem
---
> dh dh1024.pem
204c204
< client-to-client
---
> ;client-to-client

OpenVPNサーバーの起動&確認
root@chopper:/etc/openvpn# /etc/init.d/openvpn start
 * Starting virtual private network daemon(s)...                                           *   Autostarting VPN 'server'                                                            root@chopper:/etc/openvpn# ifconfig
eth0      Link encap:Ethernet  HWaddr 06:91:33:6c:2d:c4  
          inet addr:XXX.XXX.XXX.XXX  Bcast:XXX.XXX.XXX.XXX  Mask:255.255.240.0
          inet6 addr: XXXX::XXX:XXXX:XXXX:XXXX/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
          RX packets:6799 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4882 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1156820 (1.1 MB)  TX bytes:587391 (587.3 KB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
          inet addr:XXX.XXX.XXX.XXX  P-t-P:XXX.XXX.XXX.XXX  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)


サーバー側でクライアントの認証鍵ペアを作成
Mac Book Air 用のペアの名前を「pair_mba」とする。
root@chopper:/etc/openvpn/easy-rsa# ./build-key pair_mba
Generating a 2048 bit RSA private key
........................................................................................................................+++
..........................+++
writing new private key to 'pair_mba.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [JP]:
State or Province Name (full name) [XXXXXX-ken]:
Locality Name (eg, city) [XXXXXXX-shi]:
Organization Name (eg, company) [XXXXXX]:
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:.
Common Name (eg, your name or your server's hostname) [pair_mba]:
Name [EasyRSA]:XXXXXXXXXXX
Email Address [XXXXXXXXXXX@gmail.com]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:.
An optional company name []:.
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'JP'
stateOrProvinceName   :PRINTABLE:’XXXXXXXXXXXX'
localityName          :PRINTABLE:’XXXXXXXXXXXX'
organizationName      :PRINTABLE:’XXXXXXX'
commonName            :T61STRING:’XXXXXXXX'
name                  :PRINTABLE:’XXXXXXXXXXXXXXX'
emailAddress          :IA5STRING:’XXXXXXXXX@gmail.com'
Certificate is to be certified until Jul 30 08:44:22 2024 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

作成したCA公開鍵と各認証鍵ペアを「/home/ubuntu」へコピーし所有者変更
root@chopper:/etc/openvpn/easy-rsa/keys# cp ca.crt pair_mba.crt pair_mba.key ~ubuntu
root@chopper:/etc/openvpn/easy-rsa/keys# cd ~ubuntu/
root@chopper:/home/ubuntu# ls
2.x  2.x.zip  ca.crt  pair_mba.crt  pair_mba.key
root@chopper:/home/ubuntu# chown ubuntu:ubuntu ca.crt pair_mba.*


3. VPNクライアントの導入

書籍ではUbuntuとWindowsで行っていた為、MBAから接続する為に以下サイトを参考
http://blog.suz-lab.com/2012/09/mac108centos63openvpnvpn.html

MBA側にCA公開鍵と各認証鍵ペアをリモートコピー
$ scp -i coby.pem ubuntu@IPアドレス:~ubuntu/ca.crt .
ca.crt                                                  100% 1639     1.6KB/s   00:00    
$ scp -i coby.pem ubuntu@IPアドレス:~ubuntu/pair_mba.* .
pair_mba.crt                                            100% 5295     5.2KB/s   00:00    
pair_mba.key                                            100% 1708     1.7KB/s   00:00  

クライアント設定に必要なコンフィグレーションファイルをリモートコピー
$ scp -i coby.pem ubuntu@IPアドレス:/usr/share/doc/openvpn/examples/sample-config-files/client.conf .
client.conf                                             100% 3427     3.4KB/s   00:00    
$ ls
ca.crt coby.pem pair_mba.crt
client.conf junichi.pem pair_mba.key

編集
$ diff client.conf client.conf.org 
42c42
< remote IPアドレス
---
> remote my-server-1 1194
89,90c89,90
< cert pair_mba.crt
< key pair_mba.key
---
> cert client.crt
> key client.key

ユーザルートのLibrary/openvpn配下に各ファイルをコピー
$ cp /Users/{ユーザ名}/Documents/develop/AWS/ca.crt .
$ cp /Users/{ユーザ名}/Documents/develop/AWS/pair_mba.* .
$ cp /Users/{ユーザ名}/Documents/develop/AWS/client.conf .
$ ls
ca.crt client.conf pair_mba.crt pair_mba.key

Tunnelblickを起動し接続




クライアント側接続確認
$ ifconfig tun0
tun0: flags=8851<UP,POINTOPOINT,RUNNING,SIMPLEX,MULTICAST> mtu 1500
inet XX.X.X.X --> XX.X.X.X netmask 0xffffffff 
open (pid 12770)

サーバーへPing確認
$ ping -c3 サーバIP
PING サーバIP (サーバIP): 56 data bytes
64 bytes from サーバIP: icmp_seq=0 ttl=64 time=30.420 ms
64 bytes from サーバIP: icmp_seq=1 ttl=64 time=31.279 ms
64 bytes from サーバIP: icmp_seq=2 ttl=64 time=31.343 ms

--- サーバIP ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 30.420/31.014/31.343/0.421 ms

サーバー側接続確認
ubuntu@chopper:~$ ping -c3 IPアドレス
PING IPアドレス (IPアドレス) 56(84) bytes of data.
64 bytes from IPアドレス: icmp_seq=1 ttl=64 time=29.0 ms
64 bytes from IPアドレス: icmp_seq=2 ttl=64 time=29.0 ms
64 bytes from IPアドレス: icmp_seq=3 ttl=64 time=135 ms

--- IPアドレス ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 29.006/64.608/135.766/50.316 ms

VPN経由でsshログイン
$ ssh -i coby.pem ubuntu@IPアドレス
ubuntu@chopper:~$ 
大丈夫そう^^

とりあえず双方で接続はでけた^^
ただ固定IPふってないからインスタンスを再起動する度にクライアント側の設定ファイルを変更しないといけないorz

次回はVPCへ・・・