ねじまきまきまき -Random Note-

やったこと忘れないための雑記

エクスプローラーで狙ったフォルダを開くワンライナー

同じ処理を書けと言われても思い出せない

前提として、WSLを使えばたぶん行けるけど、その方法は今回パス。

主に仕事用のWindowsPCで使うことを想定して、だけど。

メールとかいろんなもので共有されたパスのフォルダをエクスプローラーで開くってのがそこそこにある。

ファイル名を指定して実行のダイアログとかエクスプローラーのアドレス履歴に貼り付けてってのがだいたいの遷移方法だと思う。

自分の場合は、ファイル名を指定して実行のダイアログを呼び出したり、エクスプローラーを起動したりってのがどうにも億劫に感じていた。

今まではVBSを使用して該当フォルダを開くっていうスクリプトを作っていて、ツールバースクリプトショートカットを置いて、それを起動すれば動くみたいな感じのものを使っていた。

一応VBSのものはVBSのものでエラーハンドリングもしていたし、当時使用してたコミュニケーションツールでパスを装飾することになっていたので、その装飾文字を除外するみたいな機能も盛り込んでいたりした。

機能としてはやることが単純なので、特に不満はないのだが、如何せん同じものを作ろうとしたときに、すぐに思い出せる気がしてならないのが難点。

ということで、コマンドプロンプトとかPowerShellあたりでどうにかできないかなーって思ってやってみた。

やりかたをいろいろ検討

例えば、コマンドでクリップボード操作が行える場合は、その結果を使えそう。

このためにclipコマンドを見てみるとこんな感じ。

clip /?

CLIP

説明:
    コマンド ライン ツールの出力を Windows クリップボードにリダイレクトします。
    その出力されたテキストをほかのプログラムに貼り付けることができます。

パラメーター一覧:
    /?                  このヘルプを表示します。

例:
    DIR | CLIP          現在のディレクトリ一覧のコピーを Windows クリップボード
                        に貼り付けます。

    CLIP < README.TXT   readme.txt ファイルのテキストのコピーを Windows
                        クリップボードに貼り付けます。

これを見る限り、クリップボードに入れることは出来ても出すことは無理。

コマンドが駄目だとすれば、PowerShellのコマンドレットではどうか。

docs.microsoft.com

しっかりとクリップボードから値を取得すると書かれている。

ということで、PowerShellを使用すれば値の取得は簡単にできることが分かった。

ではどうやって実行するか

値を取得したとしてもそれをどうやって実行するかだが、startコマンドやexplorerコマンドに引数として値を渡すことができればいい。

こういう場合、LinuxとかUnixではxargsコマンドを使って別コマンドに引数を渡すことができる。

例として、/hoge/fugaから一般ファイルで、ファイル拡張子がtxtのファイルを探して、それらのls -lの結果を標準出力する場合はこんな感じ。

find /hoge/fuga -type f -name "\*.txt" | xargs ls -l

ということで、コマンドプロンプトで同じようなことができないかと見てみたが、どうやらxargs相当のコマンドはないということだけがわかった。

パイプ"|"を使用することで、左のコマンド結果を右コマンドの標準入力に送り込めるというは変わらないようだけど、やりたいことは引数に値を与えたいので、この方法は使えない。

ということで、Powershellのみでクリップボードを取得して、取得した値を開くという動作を行うことをやってみる。

コマンドレットの確認

www.atmarkit.co.jp

www.atmarkit.co.jp

Get-Clipboardは先述の通り、値をとってくる。

Invoke-Itemはファイルやフォルダを開く。

ということで、この2つのコマンドレットでできるっぽい。

以下でやっていることはここでやっていることと同じ。 loner49th.hatenablog.com

とりあえず、PowerShellを起動して、以下を打ち込んでみるとうまく動作することが見て取れる。 ※実行前にクリップボードに「C:\」とかをコピーしておく。

$extPath = Get-Clipboard
Invoke-Item $extPath

PowerShellスクリプトのセキュリティ対応

PowerShellスクリプトはセキュリティ設定によって、初期状態では実行できないようになっている。 www.atmarkit.co.jp

これを回避するために、起動用のbatを管理者権限で実行して、PowerShellスクリプトの実行許可設定を変更ののちにPowerShellスクリプトを実行。

その後に実行許可設定を元に戻すことがある。

とはいえ、この2行を実行するためにわざわざそんなことをやるぐらいなら、そんなものは作りたくないというのもあるので、powershellコマンドに実行処理を引数で渡す方法にて実現してみる。

起動方法

以下に記載の通り、powershellコマンドに引数で処理内容を記載して実行する。

powershellコマンドは引数をセミコロン";"で区切ることで、ワンライナーが実現できる。

この処理実行はコマンドプロンプトから実行できる。

powershell $extPath = Get-Clipboard; Invoke-Item $extPath

後はこれを記載したrun.batみたいなbatファイルを用意しておけば、コマンドプロンプトが起動してやりたいことをやってくれる。

ちなみに実行時にコマンドプロンプトのウインドウが表示されるのも煩わしいという場合は、batファイルのショートカットを作成し、ショートカットのプロパティから実行時の大きさを最小化に設定すればよい。

サーバーのSSL/TSLテストをやってみる

サーバーのSSL/TLSテストについて

CMAN

CMAN SSLチェック【証明書・プロトコル・暗号スイート確認】

日本語で使えるので、いろいろ使いやすいが、TLS1.3に対応していない。

SSL Server Test

Qualys SSL Server Test

サーバーのSSLテストでよく使われるらしい。

ただし、有料プランでなければ標準ポート(443)以外のチェックが行えないため、標準ポート以外でチェックしたい場合はできない。

testssl.sh

tsetss testssl(git)

WebサーバーのSSL/TLSの対応状況とか、使用可能な証明書アルゴリズムとか脆弱性の対応状況を一括で確認できるbashスクリプト

拡張子が「sh」となっているが、中身を見てみるとどうやら「bash」っぽい。

bashが使用できるシステムであればたぶん汎用的に使用できる。

ポートについても443以外のカスタムポートをチェックすることも可能。

testssl.shでやってみる

wgetでもgitでもいいので、とりあえずダウンロードして動かしてみるといろいろわかる。

usageはこんな感じ。

もちろん、オプションなしでtestssl.shを実行すれば同じものが見ることができる。

$ ./testssl.sh

     "testssl.sh [options] <URI>"    or    "testssl.sh <options>"

"testssl.sh <option>", where <option> is mostly standalone and one of:

     --help                        what youre looking at
     -b, --banner                  displays banner + version of testssl.sh
     -v, --version                 same as previous
     -V, --local [pattern]         pretty print all local ciphers (of openssl only). If search pattern supplied: it is an
                                   an ignore case word pattern of cipher hexcode or any other string in its name, kx or bits

"testssl.sh [options] <URI>", where <URI> is:

     <URI>                         host|host:port|URL|URL:port   port 443 is default, URL can only contain HTTPS as a protocol

  and [options] is/are:

     -t, --starttls <protocol>     Does a run against a STARTTLS enabled service which is one of ftp, smtp, lmtp, pop3, imap,
                                   xmpp, xmpp-server, telnet, ldap, nntp, postgres, mysql
     --xmpphost <to_domain>        For STARTTLS xmpp or xmpp-server checks it supplies the domainname (like SNI)
     --mx <domain/host>            Tests MX records from high to low priority (STARTTLS, port 25)
     --file/-iL <fname>            Mass testing option: Reads one testssl.sh command line per line from <fname>.
                                   Can be combined with --serial or --parallel. Implicitly turns on "--warnings batch".
                                   Text format 1: Comments via # allowed, EOF signals end of <fname>
                                   Text format 2: nmap output in greppable format (-oG), 1 port per line allowed
     --mode <serial|parallel>      Mass testing to be done serial (default) or parallel (--parallel is shortcut for the latter)
     --warnings <batch|off>        "batch" doesnt continue when a testing error is encountered, off continues and skips warnings
     --connect-timeout <seconds>   useful to avoid hangers. Max <seconds> to wait for the TCP socket connect to return
     --openssl-timeout <seconds>   useful to avoid hangers. Max <seconds> to wait before openssl connect will be terminated

single check as <options>  ("testssl.sh URI" does everything except -E and -g):
     -e, --each-cipher             checks each local cipher remotely
     -E, --cipher-per-proto        checks those per protocol
     -s, --std, --standard         tests certain lists of cipher suites by strength
     -f, --fs, --nsa               checks forward secrecy settings
     -p, --protocols               checks TLS/SSL protocols (including SPDY/HTTP2)
     -g, --grease                  tests several server implementation bugs like GREASE and size limitations
     -S, --server-defaults         displays the servers default picks and certificate info
     -P, --server-preference       displays the servers picks: protocol+cipher
     -x, --single-cipher <pattern> tests matched <pattern> of ciphers
                                   (if <pattern> not a number: word match)
     -c, --client-simulation       test client simulations, see which client negotiates with cipher and protocol
     -h, --header, --headers       tests HSTS, HPKP, server/app banner, security headers, cookie, reverse proxy, IPv4 address

     -U, --vulnerable              tests all (of the following) vulnerabilities (if applicable)
     -H, --heartbleed              tests for Heartbleed vulnerability
     -I, --ccs, --ccs-injection    tests for CCS injection vulnerability
     -T, --ticketbleed             tests for Ticketbleed vulnerability in BigIP loadbalancers
     --BB, --robot                 tests for Return of Bleichenbachers Oracle Threat (ROBOT) vulnerability
     --SI, --starttls-injection    tests for STARTTLS injection issues
     -R, --renegotiation           tests for renegotiation vulnerabilities
     -C, --compression, --crime    tests for CRIME vulnerability (TLS compression issue)
     -B, --breach                  tests for BREACH vulnerability (HTTP compression issue)
     -O, --poodle                  tests for POODLE (SSL) vulnerability
     -Z, --tls-fallback            checks TLS_FALLBACK_SCSV mitigation
     -W, --sweet32                 tests 64 bit block ciphers (3DES, RC2 and IDEA): SWEET32 vulnerability
     -A, --beast                   tests for BEAST vulnerability
     -L, --lucky13                 tests for LUCKY13
     -WS, --winshock               tests for winshock vulnerability
     -F, --freak                   tests for FREAK vulnerability
     -J, --logjam                  tests for LOGJAM vulnerability
     -D, --drown                   tests for DROWN vulnerability
     -4, --rc4, --appelbaum        which RC4 ciphers are being offered?

tuning / connect options (most also can be preset via environment variables):
     --fast                        omits some checks: using openssl for all ciphers (-e), show only first preferred cipher.
     -9, --full                    includes tests for implementation bugs and cipher per protocol (could disappear)
     --bugs                        enables the "-bugs" option of s_client, needed e.g. for some buggy F5s
     --assume-http                 if protocol check fails it assumes HTTP protocol and enforces HTTP checks
     --ssl-native                  fallback to checks with OpenSSL where sockets are normally used
     --openssl <PATH>              use this openssl binary (default: look in $PATH, $RUN_DIR of testssl.sh)
     --proxy <host:port|auto>      (experimental) proxy connects via <host:port>, auto: values from $env ($http(s)_proxy)
     -6                            also use IPv6. Works only with supporting OpenSSL version and IPv6 connectivity
     --ip <ip>                     a) tests the supplied <ip> v4 or v6 address instead of resolving host(s) in URI
                                   b) arg "one" means: just test the first DNS returns (useful for multiple IPs)
     -n, --nodns <min|none>        if "none": do not try any DNS lookups, "min" queries A, AAAA and MX records
     --sneaky                      leave less traces in target logs: user agent, referer
     --user-agent <user agent>     set a custom user agent instead of the standard user agent
     --ids-friendly                skips a few vulnerability checks which may cause IDSs to block the scanning IP
     --phone-out                   allow to contact external servers for CRL download and querying OCSP responder
     --add-ca <CA files|CA dir>    path to <CAdir> with *.pem or a comma separated list of CA files to include in trust check
     --basicauth <user:pass>       provide HTTP basic auth information.
     --reqheader <header>          add custom http request headers

output options (can also be preset via environment variables):
     --quiet                       dont output the banner. By doing this you acknowledge usage terms normally appearing in the banner
     --wide                        wide output for tests like RC4, BEAST. FS also with hexcode, kx, strength, RFC name
     --show-each                   for wide outputs: display all ciphers tested -- not only succeeded ones
     --mapping <openssl|           openssl: use the OpenSSL cipher suite name as the primary name cipher suite name form (default)
                iana|rfc             -> use the IANA/(RFC) cipher suite name as the primary name cipher suite name form
                no-openssl|          -> dont display the OpenSSL cipher suite name, display IANA/(RFC) names only
                no-iana|no-rfc>      -> dont display the IANA/(RFC) cipher suite name, display OpenSSL names only
     --color <0|1|2|3>             0: no escape or other codes,  1: b/w escape codes,  2: color (default), 3: extra color (color all ciphers)
     --colorblind                  swap green and blue in the output
     --debug <0-6>                 1: screen output normal but keeps debug output in /tmp/.  2-6: see "grep -A 5 ^DEBUG= testssl.sh"
     --disable-rating              Explicitly disables the rating output

file output options (can also be preset via environment variables)
     --log, --logging              logs stdout to ${NODE}-p${port}${YYYYMMDD-HHMM}.log in current working directory (cwd)
     --logfile|-oL <logfile>       logs stdout to dir/${NODE}-p${port}${YYYYMMDD-HHMM}.log. If logfile is a dir or to a specified logfile
     --json                        additional output of findings to flat JSON file ${NODE}-p${port}${YYYYMMDD-HHMM}.json in cwd
     --jsonfile|-oj <jsonfile>     additional output to the specified flat JSON file or directory, similar to --logfile
     --json-pretty                 additional JSON structured output of findings to a file ${NODE}-p${port}${YYYYMMDD-HHMM}.json in cwd
     --jsonfile-pretty|-oJ <jsonfile>  additional JSON structured output to the specified file or directory, similar to --logfile
     --csv                         additional output of findings to CSV file ${NODE}-p${port}${YYYYMMDD-HHMM}.csv in cwd or directory
     --csvfile|-oC <csvfile>       additional output as CSV to the specified file or directory, similar to --logfile
     --html                        additional output as HTML to file ${NODE}-p${port}${YYYYMMDD-HHMM}.html
     --htmlfile|-oH <htmlfile>     additional output as HTML to the specified file or directory, similar to --logfile
     --out(f,F)ile|-oa/-oA <fname> log to a LOG,JSON,CSV,HTML file (see nmap). -oA/-oa: pretty/flat JSON.
                                   "auto" uses ${NODE}-p${port}${YYYYMMDD-HHMM}. If fname if a dir uses dir/${NODE}-p${port}${YYYYMMDD-HHMM}
     --hints                       additional hints to findings
     --severity <severity>         severities with lower level will be filtered for CSV+JSON, possible values <LOW|MEDIUM|HIGH|CRITICAL>
     --append                      if (non-empty) <logfile>, <csvfile>, <jsonfile> or <htmlfile> exists, append to file. Omits any header
     --overwrite                   if <logfile>, <csvfile>, <jsonfile> or <htmlfile> exists it overwrites it without any warning
     --outprefix <fname_prefix>    before  ${NODE}. above prepend <fname_prefix>


Options requiring a value can also be called with = e.g. testssl.sh -t=smtp --wide --openssl=/usr/bin/openssl <URI>.
<URI> always needs to be the last parameter.

パラメータのURIについては、「example.com:8080」みたいにすればポート指定が可能。

この辺りを使用して、こんな感じで実行してみる。

./testssl.sh --html example.com:8080
./testssl.sh --log example.com:8080

htmlオプションは結果をHTMLで記録してくれるので、Linuxで実行した結果をWindowsで見たいといった場合に使いやすい。

logオプションは結果をbashの装飾機能を使って色付けしてくれるので、bashコンソール上で再確認するといった場合は使いやすい。

ただし、Windowsでログファイルを見る場合は、タグに制御コードを使用しているため、見辛くくなってしまう。

なお、htmlオプションやlogオプションの有無に関わらず実行結果はコンソールに標準出力される。

実行結果

やってみた結果はこんな感じ(一部抜粋)

###########################################################
    testssl.sh       3.1dev from [https://testssl.sh/dev/](https://testssl.sh/dev/)
 (895a6b9 2021-03-11 10:42:52 -- )
 This program is free software. Distribution and
             modification under GPLv2 permitted.
      USAGE w/o ANY WARRANTY. USE IT AT YOUR OWN RISK!

       Please file bugs @ [https://testssl.sh/bugs/](https://testssl.sh/bugs/)
 ###########################################################

 Using "OpenSSL 1.0.2-chacha (1.0.2k-dev)" \[~183 ciphers\]
 on ik1-419-41682:./bin/openssl.Linux.x86\_64
 (built: "Jan 18 17:12:17 2019", platform: "linux-x86\_64")

 Start 2021-03-20 22:07:04        -->> 100.100.100.100:8080 (example.com) <<--

 rDNS (100.100.100.100):  example.com.
 Service detected:       HTTP

 Testing protocols via sockets except NPN+ALPN 

 SSLv2 not offered (OK)
 SSLv3 not offered (OK)
 TLS 1 not offered
 TLS 1.1 not offered
 TLS 1.2 offered (OK)
 TLS 1.3 not offered and downgraded to a weaker protocol
 NPN/SPDY not offered
 ALPN/HTTP2 not offered

 Testing cipher categories 

 NULL ciphers (no encryption) not offered (OK)
 Anonymous NULL Ciphers (no authentication) not offered (OK)
 Export ciphers (w/o ADH+NULL) not offered (OK)
 LOW: 64 Bit + DES, RC\[2,4\], MD5 (w/o export) not offered (OK)
 Triple DES Ciphers / IDEA not offered
 Obsoleted CBC ciphers (AES, ARIA etc.) offered
 Strong encryption (AEAD ciphers) with no FS offered (OK)
 Forward Secrecy strong encryption (AEAD ciphers) offered (OK)

 Testing server's cipher preferences 

 Has server cipher order? no (NOT ok)
 Negotiated protocol TLSv1.2
 Negotiated cipher AES128-GCM-SHA256 -- inconclusive test, matching cipher in list missing, better see below
 Cipher per protocol

Hexcode  Cipher Suite Name (OpenSSL)       KeyExch.   Encryption  Bits     Cipher Suite Name (IANA/RFC)
-----------------------------------------------------------------------------------------------------------------------------
SSLv2
 - 
SSLv3
 - 
TLSv1
 - 
TLSv1.1
 - 
TLSv1.2 (no server order, thus listed by strength)
 xc030   ECDHE-RSA-AES256-GCM-SHA384       ECDH 521   AESGCM      256      TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384              
 xc028   ECDHE-RSA-AES256-SHA384           ECDH 521   AES         256      TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384              
 xc014   ECDHE-RSA-AES256-SHA              ECDH 521   AES         256      TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA                 
 xcca8   ECDHE-RSA-CHACHA20-POLY1305       ECDH 521   ChaCha20    256      TLS\_ECDHE\_RSA\_WITH\_CHACHA20\_POLY1305\_SHA256        
 xc077   ECDHE-RSA-CAMELLIA256-SHA384      ECDH 521   Camellia    256      TLS\_ECDHE\_RSA\_WITH\_CAMELLIA\_256\_CBC\_SHA384         
 x9d     AES256-GCM-SHA384                 RSA        AESGCM      256      TLS\_RSA\_WITH\_AES\_256\_GCM\_SHA384                    

 Testing vulnerabilities 

 Heartbleed (CVE-2014-0160)                not vulnerable (OK), no heartbeat extension
 CCS (CVE-2014-0224)                       not vulnerable (OK)
 Ticketbleed (CVE-2016-9244), experiment.  not vulnerable (OK)
 ROBOT not vulnerable (OK)
 Secure Renegotiation (RFC 5746) supported (OK)
 Secure Client-Initiated Renegotiation VULNERABLE (NOT ok), DoS threat (6 attempts)
 CRIME, TLS (CVE-2012-4929)                not vulnerable (OK)
 BREACH (CVE-2013-3587)                    no gzip/deflate/compress/br HTTP compression (OK)  - only supplied "/" tested
 POODLE, SSL (CVE-2014-3566)               not vulnerable (OK), no SSLv3 support
 TLS\_FALLBACK\_SCSV (RFC 7507)              No fallback possible (OK), no protocol below TLS 1.2 offered
 SWEET32 (CVE-2016-2183, CVE-2016-6329)    not vulnerable (OK)
 FREAK (CVE-2015-0204)                     not vulnerable (OK)
 DROWN (CVE-2016-0800, CVE-2016-0703)      not vulnerable on this host and port (OK)
                                           make sure you don't use this certificate elsewhere with SSLv2 enabled services
                                           https://censys.io/ipv4?q=2DA7122DD4B5E469076E1331612447F67B73AA399AA7388775C717ED5BD07725 could help you to find out
 LOGJAM (CVE-2015-4000), experimental      not vulnerable (OK): no DH EXPORT ciphers, no DH key detected with <= TLS 1.2
 BEAST (CVE-2011-3389)                     not vulnerable (OK), no SSL3 or TLS1
 LUCKY13 (CVE-2013-0169), experimental     potentially VULNERABLE, uses cipher block chaining (CBC) ciphers with TLS. Check patches
 Winshock (CVE-2014-6321), experimental    not vulnerable (OK) - ARIA, CHACHA or CCM ciphers found
 RC4 (CVE-2013-2566, CVE-2015-2808)        no RC4 ciphers detected (OK)

 Running client simulations (HTTP) via sockets 

 Rating specs (not complete)  SSL Labs's 'SSL Server Rating Guide' (version 2009q from 2020-01-30)
 Specification documentation [https://github.com/ssllabs/research/wiki/SSL-Server-Rating-Guide](https://github.com/ssllabs/research/wiki/SSL-Server-Rating-Guide)
 Protocol Support (weighted)  100 (30)
 Key Exchange    (weighted)  90 (27)
 Cipher Strength (weighted)  90 (36)
 Final Score 93
 Overall Grade A
 Grade cap reasons Grade capped to A. HSTS is not offered

 Done 2021-03-20 22:09:14 \[ 132s\] -->> 100.100.100.100:8080 (example.com) <<--

testssl結果

Overall GradeはAだったので、概ねは問題ないのだが、以下の点が気になった。

Secure Client-Initiated Renegotiation VULNERABLE (NOT ok), DoS threat (6 attempts)

Qiita # testssl.sh の Secure Client-Initiated Renegotiation チェック

ここを見てみると、CVE-2011-1473の対応が出来ていないということらしい。

stone修正

脆弱性に対応するには、自分のサーバ構成上どうしてもstoneを修正する必要がある。

現在の設定オプションを見てみると、SSLフラグに関する設定は後付けできないので、ソースを修正することにする。

stoneでCTXオプションを設定している箇所があるので、そこに1行追加する。

    SSL_CTX_set_options(ss->ctx, opts->off);
    ↓
    SSL_CTX_set_options(ss->ctx, opts->off);
    SSL_CTX_set_options(ss->ctx, SSL_OP_NO_RENEGOTIATION);

SSL_CTX_set_optionsではビットマスクを使用してオプションを追加して、複数セットしたとしてもクリアされない。

ということで、修正したソースを使用してmakeしたものに入れ替えて改めてtestssl.shを実行すると、Secure Client-Initiated Renegotiationの部分が「not vulnerable (OK)」となったので、対応は完了。

リバースプロキシが使用しているcipher suiteの対処をした

ちゃんとしたSSL化をしてみる

今回の経緯と目的

現状としてGoogle Chrome等で検証を行ってみると、encrypt自体はされているものの状態として望ましくない感じっていうことが実はあった。 f:id:neji_shiki:20210312153927p:plain

これに対応するためにオプションにOpenSSL 1.0.2で使用できるcipher suiteの指定をしてみたが、起動してもエラーとなって使えない状況となっていた。

そのためOpenSSL 1.1.1を使えるようにすることで、ここら辺を打開できるか試してみようっていう試み。

サーバの状態

現状として、使用しているサーバーはCentOS7で、CentOS7のOpenSSLはバージョンが古い(サポート期限なんてとっくに切れている)。

使用しているCentOSとOpenSSLのバージョンはこんな感じ。

OpenSSLのバージョンを調べると、2019年12月31日にサポート期限が切れているのがわかる。

$ cat /etc/redhat-release
CentOS Linux release 7.9.2009 (Core)

$ openssl version
OpenSSL 1.0.2k-fips  26 Jan 2017

stoneをmakeするためにopenssl-develパッケージをインストールしていたけど、これも1.0.2となっている。

$ sudo yum info openssl-devel
インストール済みパッケージ
名前                : openssl-devel
アーキテクチャー    : x86_64
エポック            : 1
バージョン          : 1.0.2k
リリース            : 21.el7_9
容量                : 3.1 M
リポジトリー        : installed
提供元リポジトリー  : updates
要約                : Files for development of applications which will use OpenSSL
URL                 : http://www.openssl.org/
ライセンス          : OpenSSL
説明                : OpenSSL is a toolkit for supporting cryptography. The openssl-devel
                    : package contains include files needed to develop applications which
                    : support various cryptographic algorithms and protocols.

OpenSSL 1.1.1をインストール

適当に見た感じでは、OpenSSL 1.1.1では openssl-devel 1.0.2に含まれるヘッダーファイルが含まれているっぽい。

とはいえ、CentOS7にOpenSSL 1.1.1をインストールする場合はソースから行う必要があるみたいなので、システム全体じゃなくて作業用のユーザーのみ入れ替えを行う感じでインストールを行う。

リポジトリパスを追加すればyumとかのコマンドで行けたかもしれないけど、詳しくは見ていない。

参考 : とりあえずこの辺り

 # CentOS7にOpenSSL1.1.1をインストール

 CentOS 7.6 にソースコードから OpenSSL 1.1.1c をインストールする - らくがきちょう

インストールが終わると、OpenSSL 1.1.1が使用可能になったことがわかる。

ただし、root等の別ユーザーやシステムとしてはOpenSSL 1.0.2を使用している状態となっている。

$ openssl version
OpenSSL 1.1.1j  16 Feb 2021

$ sudo openssl version
OpenSSL 1.0.2k-fips  26 Jan 2017

stoneのmakeやり直し

Makefile編集

stoneのMakefileを編集して、インストールしたOpenSSL 1.1.1をとりあえず使用するように変更する。

きれいな編集はしていないけど、編集内容はこんな感じ。

Makefile内に使用するopensslコマンドのパスを変更して、SSL_LIBSについてもlibディレクトリのパスを追加している。

linuxタグのオプションについては不要かと思ったけど、「-D_GNU_SOURCE」を追加している。

23c23
<
< SSL=          /usr/local/ssl
---
> SSL=          /usr/local/openssl/bin/
26c27
< SSL_LIBS=     -lssl -lcrypto
---
> SSL_LIBS=     -L/usr/local/openssl/lib/ -lssl -lcrypto
99c100
<       $(MAKE) FLAGS="-O -Wall -DCPP='\"/usr/bin/cpp -traditional\"' -DPTHREAD -DUNIX_DAEMON -DPRCTL -DSO_ORIGINAL_DST=80 -DUSE_EPOLL $(FLAGS)" LIBS="-lpthread $(LIBS)" stone
---
>       $(MAKE) FLAGS="-O -Wall -DCPP='\"/usr/bin/cpp -traditional\"' -DPTHREAD -DUNIX_DAEMON -DPRCTL -DSO_ORIGINAL_DST=80 $(SSL_FLAGS) -DUSE_EPOLL -D_GNU_SOURCE $(FLAGS)" LIBS="-lpthread $(LIBS)" stone

stone.c編集

stone.cについてもOpenSSL 1.1.1を使用するために修正が必要となる。

 参考tcpリピータのstone - 極限環境材料化学研究室

ここにある通り、stone.c内のSSL_state()をSSL_get_state()に置き換えを行う。

make実行

makeを行うと、OpenSSL 1.0.2からOpenSSL 1.1.1を使用することに変更したために以下のような警告が発生する。 とりあえず警告自体は無視することにした。

makeを実行する前にOpenSSL 1.1.1のための環境変数も設定する。

$ export C_INCLUDE_PATH=/usr/local/openssl/include/
$ make linux-ssl
make TARGET=linux ssl_stone LIBS="-ldl"
make[1]: ディレクトリ `/Local/stone' に入ります
make FLAGS="-DUSE_POP -DUSE_SSL -DCONST_SSL_METHOD -DOPENSSL_NO_TLS1 -DOPENSSL_NO_SSL2 -DOPENSSL_NO_SSL3 " LIBS="-ldl -L/usr/local/openssl/lib/ -lssl -lcrypto" linux
make[2]: ディレクトリ `/Local/stone' に入ります
make FLAGS="-O -Wall -DCPP='\"/usr/bin/cpp -traditional\"' -DPTHREAD -DUNIX_DAEMON -DPRCTL -DSO_ORIGINAL_DST=80 -DUSE_SSL -DCONST_SSL_METHOD -DOPENSSL_NO_TLS1 -DOPENSSL_NO_SSL2 -DOPENSSL_NO_SSL3 -DUSE_EPOLL -D_GNU_SOURCE -DUSE_POP -DUSE_SSL -DCONST_SSL_METHOD -DOPENSSL_NO_TLS1 -DOPENSSL_NO_SSL2 -DOPENSSL_NO_SSL3 " LIBS="-lpthread -ldl -L/usr/local/openssl/lib/ -lssl -lcrypto" stone
make[3]: ディレクトリ `/Local/stone' に入ります
cc -D_GNU_SOURCE  -O -Wall -DCPP='"/usr/bin/cpp -traditional"' -DPTHREAD -DUNIX_DAEMON -DPRCTL -DSO_ORIGINAL_DST=80 -DUSE_SSL -DCONST_SSL_METHOD -DOPENSSL_NO_TLS1 -DOPENSSL_NO_SSL2 -DOPENSSL_NO_SSL3 -DUSE_EPOLL -D_GNU_SOURCE -DUSE_POP -DUSE_SSL -DCONST_SSL_METHOD -DOPENSSL_NO_TLS1 -DOPENSSL_NO_SSL2 -DOPENSSL_NO_SSL3  -o stone stone.c -lpthread -ldl -L/usr/local/openssl/lib/ -lssl -lcrypto
stone.c: 関数 ‘asyncHealthCheck’ 内:
stone.c:2087:5: 警告: ‘ERR_remove_state’ は廃止されました (宣言位置 /usr/local/openssl/include/openssl/err.h:261) [-Wdeprecated-declarations]
     ASYNC_END;
     ^
stone.c: 関数 ‘asyncConn’ 内:
stone.c:4228:5: 警告: ‘ERR_remove_state’ は廃止されました (宣言位置 /usr/local/openssl/include/openssl/err.h:261) [-Wdeprecated-declarations]
     ASYNC_END;
     ^
stone.c: 関数 ‘asyncAcceptConnect’ 内:
stone.c:7123:5: 警告: ‘ERR_remove_state’ は廃止されました (宣言位置 /usr/local/openssl/include/openssl/err.h:261) [-Wdeprecated-declarations]
     ASYNC_END;
     ^
stone.c: 関数 ‘repeater’ 内:
stone.c:8067:5: 警告: ‘ERR_remove_state’ は廃止されました (宣言位置 /usr/local/openssl/include/openssl/err.h:261) [-Wdeprecated-declarations]
     ERR_remove_state(0);
     ^
stone.c: 関数 ‘sslopts’ 内:
stone.c:9355:2: 警告: ‘TLSv1_2_server_method’ は廃止されました (宣言位置 /usr/local/openssl/include/openssl/ssl.h:1890) [-Wdeprecated-declarations]
  if (isserver) opts->meth = TLSv1_2_server_method();
  ^
stone.c:9356:2: 警告: ‘TLSv1_2_client_method’ は廃止されました (宣言位置 /usr/local/openssl/include/openssl/ssl.h:1891) [-Wdeprecated-declarations]
  else opts->meth = TLSv1_2_client_method();
  ^
stone.c:9360:2: 警告: ‘TLSv1_1_server_method’ は廃止されました (宣言位置 /usr/local/openssl/include/openssl/ssl.h:1884) [-Wdeprecated-declarations]
  if (isserver) opts->meth = TLSv1_1_server_method();
  ^
stone.c:9361:2: 警告: ‘TLSv1_1_client_method’ は廃止されました (宣言位置 /usr/local/openssl/include/openssl/ssl.h:1885) [-Wdeprecated-declarations]
  else opts->meth = TLSv1_1_client_method();
  ^
make[3]: ディレクトリ `/Local/stone' から出ます
make[2]: ディレクトリ `/Local/stone' から出ます
make[1]: ディレクトリ `/Local/stone' から出ます

makeしたstoneの確認

依存している共有ライブラリの確認

lddコマンドを使用してライブラリにopenssl1.1.1のものが含まれているかを確認。 以下の例だと「libssl.so.1.1」「libcrypto.so.1.1」がopenssl1.1.1のもの。

 ldd ./stone
        linux-vdso.so.1 =>  (0x00007ffd6ed8c000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f95bfde1000)
        libdl.so.2 => /lib64/libdl.so.2 (0x00007f95bfbdd000)
        libssl.so.1.1 => /usr/local/openssl/lib/libssl.so.1.1 (0x00007f95bf94b000)
        libcrypto.so.1.1 => /usr/local/openssl/lib/libcrypto.so.1.1 (0x00007f95bf45f000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f95bf091000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f95bfffd000)
        libz.so.1 => /lib64/libz.so.1 (0x00007f95bee7b000)

起動確認

新しいバイナリで同じようにリバースプロキシを立ち上げた場合に使用されるcipher suiteを確認。

こんな感じでConnectionの項目が変わっている。 f:id:neji_shiki:20210312153932p:plain

ということで、TLS 1.2で怒られない感じのcipher suiteを使用したリバースプロキシの立ち上げにはこれで成功した感じ。

とはいえ、NginxとかApacheをおとなしく使うほうが導入の手間は少ないと思う。

Docker使えばすぐに立ち上がるしね。

WebサーバのSSL化対応

■WebサーバのSSL

keitaircのSSL化を棚上げしていたものをようやくやったので、その話。

■Reverse Proxy(トンネリング)の構築に向けて

keitaircのssl化はマニュアルにある通り、mod_ssl等を利用することを想定している。
keitairc自体はApacheやNGINXに代表されるようなHTTPサーバ上で動いているわけじゃなく、keitairc自身が簡易サーバとして動作しているため、わざわざmod_sslモジュールを使うためだけにApacheを立ち上げるのもめんどくさい。
そこで、NGINXなどでReverse Proxyを立ち上げてトンネリングすることで、サーバの外はhttpsで動作し、サーバ内は今まで通りhttpで動作させることにした。

イメージとしてのReverse Proxyの導入イメージはこんな感じ。
HTTPS<-->HTTPをReverse Proxyで繋ぐ。
HTTPSの処理はReverse Proxyにて行うため、HTTPより奥では処理に変更がないことになる。

            +--------------------------------------+
            |Server                                |
            |+---------+  +----------+  +--------+||
            || Reverse |  | keitairc |  | tiarra |||
Inter Net --||  Proxy  |--|  (HTTP)  |--| (TCP)  |||
            || (HTTPS) |  |          |  |        |||
            |+---------+  +----------+  +--------+||
            +--------------------------------------+

■いろいろな選択肢

■選択肢 Apacheを使う(mod_proxy/mod_ssl)

Apacheのモジュールとして動作するため、基本的にApache+(mod_proxy or/and mod_ssl)として動作させる。 現状ではhttpdが必要な用途がReverse Proxyのみのため、正直面倒。

■選択肢 NGINXを使う

静的HTMLコンテンツの配信に長けているhttpdの一種。 一応モジュールの追加でCGIも動作させることもできるらしい。 とはいえ、Apache同様にhttpdが必要な用途がReverse Proxyのみのため、面倒なことに変わりはない。

■選択肢 other

■gost

go言語で書かれたgostっていう多機能プロトコル変換中継simple tunnelソフトウェアらしい。
# gost - GO Simple Tunnel がすごい

■stone

c言語で書かれたアプリケーションレベルの TCP & UDP リピーター。 ## Simple Repeater

■用途として一番しっくり来たstoneを使用する

sourceをDLしてmakeしないといけないのだが、だいたいeldorado-of.infoのWiki/stoneの通りにコマンドを打ち込むだけで苦も無く実行可能バイナリが出来上がる。
ただし、使用しているバージョンは正式版ではあるが、2008-02-05にリリースされたバージョンでもあるので、ここが厄介。
ということで、stoneのCVSを覗いてみるとOpenSSL 1.1.1に対応したソースが公開されているので、wgetコマンドにCVSのtarballリンクアドレスを指定して、ソースをまとめてダウンロードして使用する。
このバージョンだと先の説明にあったようなmakefileの書き換えや、ワーニング等は発生しなかった。

■stoneのmake完了後の動作確認

makeが終わったら動作確認のために適当に起動をしてみる。
以下例はstoneを外側ポート1000で待ち受けて、内側ポート1100とつなぐという感じ。
これで動作が確認出来たらひとまずよしとする。

stone localhost:1000 1100

SSLサーバ証明書

Webサーバをhttps化するにあたって、SSLサーバ証明書が必要になる。
いろいろ発行機関はあるが、個人利用であるためLet’s Encryptを使用することにした。

Let’s Encryptでの証明書発行準備

certbot導入

Let’s Encryptの証明書発行においては、ホームページに記載のある通りcertbotを導入する方向にした。
参考サイトを見つつこれもインストールと証明書の発行を行っていく。
 # CentOS7】Lets EncryptでSSL証明書を取得

■証明書自動更新設定

Let's Encryptの証明書については、期限が3か月なので、自動更新の設定も併せて実施する。
とりあえずは証明書更新コマンドの確認をしてみる。

sudo certbot renew --dry-run

コマンドが正常に動作することを確認したら、cronに設定を追加する。 証明書更新は1か月を切ったら新しいのが発行できるらしいのと、証明書更新コマンド自体は実行して空振りに終わるか更新できるかなので、月1回実行する形の例。 これで毎月1日の0時0分に実行される形になる。

00 00 01  *  * sudo /usr/bin/certbot renew

■stone起動設定

confファイルを使用することでコマンドラインオプションを定義ファイルとして保存できるので、起動条件を変更する場合も簡単になる。

■定義ファイル作成

以下は証明書と秘密鍵の指定とTLS1.2の指定、HTTP<->HTTPSのトンネルを行うポート設定を指定する。
他の指定は用途毎に指定する。

-z key=/etc/letsencrypt/live/example.com/privkey.pem
-z cert=/etc/letsencrypt/live/example.com/cert.pem
-z verify,none
-z CApath=/etc/letsencrypt/live/example.com
-z tls1.2
stone localhost:1000 1100/ssl

■stone起動確認

証明書を起動時に読み込む必要があるので、証明書のシンボリックリンク等を専用の場所に作成するか、certbotに合わせてrootで起動してみる。
これでstoneの起動が確認できたらブラウザアクセスをして接続できることを確認する。

nohup sudo /usr/local/bin/stone -C target_conf &

■起動用シェル

stone起動用に以下のシェルを作成。
サーバリブート時の起動と、証明書更新時の自動再起動を想定した再起動を行うために最低限必要なことだけを行っている。
プロセスを再起動するため、ポート開放の可能性を考えて適当に10秒スリープさせている。

#!/bin/bash -l
cd /Local/stone_home

## Kill
if [ `ps -ef | egrep "stone.+conf" | egrep -v "grep|sudo|bash" | wc -l` -ne 0 ]; then
        for stone_proc in `ps -ef| egrep "stone.+conf" | egrep -v "grep|sudo|bash" | awk '{print $2}'`
        do
                sudo kill -9 $stone_proc
        done
fi

sleep 10

## Start
for target_conf in `ls stone*.conf`
do
        if [ `ps -ef | egrep $target_conf | egrep -v "grep|sudo|bash" | wc -l` -eq 0 ]; then
                nohup sudo /usr/local/bin/stone -C $target_conf 1>/dev/null 2>&1 &
        fi
done

このシェルをサーバ起動時及び、certbot起動後に動作するようにcronを設定して終わり。

@reboot /Local/stone_run.bash 1>/dev/null 2>&1 &
00 00 01  *  * sudo /usr/bin/certbot renew && /Local/stone_run.bash 1>/dev/null 2>&1 &

メモ用にWikiを構築しようとした話

メモの溜め込みにWikiを使おうって思った

VPS立てた後に使おうかなって考えてたものにWikiがある。
特に目新しいことをやろうとか、大仰なことをやろうとかいうのではなくて、メモの書き留めに使いたいって理由。
Google KeepとかMicorosoft ONENOTEとか、今の時代となっては自動的にバックアップと同期までしてくれるツールがあふれているので、急いではいなかった。

昔の環境と今の事情

当時はZaurus(たぶんSL-C3000)でw3mを使用してその中のローカルCGI機能を使ってWiki(RandomNote)を動かしていたんだけど、今となってはスマホがあるし、通信量は気にするほどでもないし、サーバーがあるからそれを使えばいいよねっていう感じ。

ちなみに昔使っていた時は新しいWikiクローンがどんどん生まれていた気がするけど、10年も経つとどんどん減っているみたいで、当時使っていたRandomNoteしかり、なかなか使えそうなWikiクローンが見つからなかった。
用途としてはメモとしての機能に重点を置いているので、動作がシンプルであればあるほどいいぐらい。

とりあえずの候補

Scrapmemo

昔使っていたRandomNoteの構想に近いことから候補にした。
だーっと書いたものをすべてテキストファイルとして管理してくれるので、ファイル管理もサーバー管理も楽そう。

Konawiki3

これもDBではなくて、テキストファイルにデータを書き込むやつ。
Konawiki2はDBを使うのと機能も豊富らしいけど、データの取り扱いが楽なのがよさそう。

Hiki

アクセス制限やユーザ管理が行えるので、インターネット上での個人用という用途に向く。

# FreeStyleWiki

昔関わっていたプロジェクトで情報共有のために建てた気がする。

mono

RandomNoteの作者によるもの。
記法もないので、書き溜めるだけ書き溜める用途には向く。

PukiWiki

Yukiwikiがなくなっていたので、こっちもなくなっているかと思ったぐらいの古参。
むしろメンテナンスもされているようで、安定して使えることができそう。

とりあえずの候補(番外編)

番外編として、ローカル環境(パソコン上)で同じような使い方ができるものについて考えてみる。

ひとりWiki

定番中の定番(だと思う)。
これ1つで導入が終わるので、環境のことなんて考えなくていいっていうのはすごい。

Obsidian

ノートの取り方であるZettelkasten(gigazine内記事)について調べていたところ見つけたやつ。
発想としてはひとりWikiにかなり似通っている。
Zettelkastenの実践で真価を発揮しそう。

今のところの決着

ひとまずはObsidianでMarkdownファイルを扱いつつ、Zettelkastenをやってみることにした。
Webサーバの構築とかファイアウォール設定もあるしなーってめんどくさくなってきたので、楽なほうに転んだ。
そのうちちゃんと考えるかも。

SSHクライアントとしてのVS Code

TeratermじゃなくてVS Codeで直接いじれる環境も作ろうかなっと

だいたいTerminalソフトとしてはTeraTermを愛用しているわけだけど、せっかくVS Codeもあるし、VS CodeSSH開発環境も整えようというあれこれ。

接続できない問題

とはいえ、2台目の構築だったのでそんなに手間取ることもないだろうなって思ったら、こんな感じのエラーが出てうまくいかなかった。

[xx:xx:xx.xxx] Log Level: 2
[xx:xx:xx.xxx] remote-ssh@0.63.0
[xx:xx:xx.xxx] win32 x64
[xx:xx:xx.xxx] SSH Resolver called for "ssh-remote+hogehoge.hogehoge", attempt 1
[xx:xx:xx.xxx] "remote.SSH.useLocalServer": false
[xx:xx:xx.xxx] "remote.SSH.showLoginTerminal": false
[xx:xx:xx.xxx] "remote.SSH.remotePlatform": {}
[xx:xx:xx.xxx] "remote.SSH.sshPath": undefined
[xx:xx:xx.xxx] "remote.SSH.sshConfigurationFile": undefined
[xx:xx:xx.xxx] "remote.SSH.useFlock": true
[xx:xx:xx.xxx] "remote.SSH.lockfilesInTmp": false
[xx:xx:xx.xxx] "remote.SSH.localServerDownload": auto
[xx:xx:xx.xxx] "remote.SSH.remoteServerListenOnSocket": false
[xx:xx:xx.xxx] "remote.SSH.showLoginTerminal": false
[xx:xx:xx.xxx] SSH Resolver called for host: hogehoge.hogehoge
[xx:xx:xx.xxx] Setting up SSH remote "hogehoge.hogehoge"
[xx:xx:xx.xxx] Using commit id "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" and quality "stable" for server
[xx:xx:xx.xxx] Install and start server if needed
[xx:xx:xx.xxx] Checking ssh with "ssh -V"
[xx:xx:xx.xxx] > OpenSSH_for_Windows_7.7p1, LibreSSL 2.6.5

[xx:xx:xx.xxx] Running script with connection command: ssh -T -D 65312 "hogehoge.hogehoge" bash
[xx:xx:xx.xxx] Terminal shell path: C:\Windows\System32\cmd.exe
[xx:xx:xx.xxx] > The authenticity of host '[hogehoge.hogehoge]:XXXX ([XXX.XXX.XXX.XXX]:XXXX)'
> can't be established.
> ECDSA key fingerprint is SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
> Are you sure you want to continue connecting (yes/no)?]0;C:\Windows\System32\cmd.exe
[xx:xx:xx.xxx] Got some output, clearing connection timeout
[xx:xx:xx.xxx] Detected fingerprint confirmation message
[xx:xx:xx.xxx] Showing fingerprint confirmation dialog
[xx:xx:xx.xxx] Got fingerprint response: yes
[xx:xx:xx.xxx] "install" wrote data to terminal: "yes"
[xx:xx:xx.xxx] > y
[xx:xx:xx.xxx] > Are you sure you want to continue connecting (yes/no)? yes
> Warning: Permanently added '[hogehoge.hogehoge]:XXXX,[XXX.XXX.XXX.XXX]:XXXX' 
> (ECDSA) to the list of known hosts.
[xx:xx:xx.xxx] > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
[xx:xx:xx.xxx] > @         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> Permissions for 'XXXXXXXXXXXXXX//id_rsa' are too open.
> It is required that your private key files are NOT accessible by others.
> This private key will be ignored.
> Load key "XXXXXXXXXXXXXX//id_rsa": bad permissions
> XXXX@hogehoge.hogehoge: Permission denied (publickey).
> プロセスが、存在しないパイプに書き込もうとしました。
> 
[xx:xx:xx.xxx] "install" terminal command done
[xx:xx:xx.xxx] Install terminal quit with output: プロセスが、存在しないパイプに書き込もうとしました。
[xx:xx:xx.xxx] Received install output: プロセスが、存在しないパイプに書き込もうとしました。
[xx:xx:xx.xxx] Stopped parsing output early. Remaining text: プロセスが、存在しないパイプに書き込もうとしました。
[xx:xx:xx.xxx] Failed to parse remote port from server output
[xx:xx:xx.xxx] Resolver error: Error: 
	at Function.Create (c:\Users\user\.vscode\extensions\ms-vscode-remote.remote-ssh-0.63.0\out\extension.js:1:64027)
	at Object.t.handleInstallOutput (c:\Users\user\.vscode\extensions\ms-vscode-remote.remote-ssh-0.63.0\out\extension.js:1:62766)
	at k (c:\Users\user\.vscode\extensions\ms-vscode-remote.remote-ssh-0.63.0\out\extension.js:1:312915)
	at processTicksAndRejections (internal/process/task_queues.js:94:5)
	at async c:\Users\user\.vscode\extensions\ms-vscode-remote.remote-ssh-0.63.0\out\extension.js:1:310801
	at async Object.t.withShowDetailsEvent (c:\Users\user\.vscode\extensions\ms-vscode-remote.remote-ssh-0.63.0\out\extension.js:1:405790)
	at async Object.t.resolve (c:\Users\user\.vscode\extensions\ms-vscode-remote.remote-ssh-0.63.0\out\extension.js:1:314454)
	at async c:\Users\user\.vscode\extensions\ms-vscode-remote.remote-ssh-0.63.0\out\extension.js:127:110333
[xx:xx:xx.xxx] ------

見た感じPrivate Keyの権限問題だったんだけど、Private Key自体は開けるし、なんでだろうと思ってconfigファイルをC:\Users\ユーザ名/.ssh/configからC:\ProgramData\ssh\ssh_configに移動したりしたんだけど結局駄目だった。
というか、C:\ProgramData\ssh\ssh_configに至ってはVS Codeで編集したものが他のテキストエディタでは繁栄されていなかったり、その逆が起こったりでそういう意味でも使うのを躊躇する事象が発生した。

Windowsでファイル自体の権限情報触ったのっていつ以来だろう

結局のところ、Windowsではあまり使用しない権限情報を編集することで使用することができるようになった。
ここにたどり着かなかったら駄目だったかもしれない。
qiita.com

TerminalソフトとVS Codeのttyについて

TerminalソフトなんかでサーバOSに接続した場合、wとかwhoコマンドでセッション情報を確認することがよくあると思う。
個人だとそうはないかもしれないけど、チーム開発だとあるよね。

TeraTermなんかでももちろんそうで、Teratermを使用した場合のwhoコマンドの結果はこんな感じになる。

$ who
xxxxxx   pts/0        2021-01-31 16:54 (XXXXXXXXXXXXXXXXXXXXXXXXXXXX)

これに対して、VS Codeの場合はwとかwhoではセッション情報が帰ってこない。
(設定ちゃんとやればいいのかもしれないけど)
これに対してpsコマンドでログイン状態を見てみるとこういうことになっていた。

Teraterm
root      1432     1  0 16:54 ?        00:00:00 sshd: xxxxxx [priv]
xxxxxx    1434  1432  0 16:54 ?        00:00:00 sshd: xxxxxx@pts/0

VS Code
root      1603     1  0 17:05 ?        00:00:00 /usr/sbin/sshd -D
root      5324  1603  0 18:22 ?        00:00:00 sshd: xxxxxx [priv]
xxxxxx    5326  5324  0 18:22 ?        00:00:00 sshd: xxxxxx@notty

面白いのはTeratermではpts/0ということなので、仮想端末情報が割り当てられている。
それに対してVS Codeでは仮想端末情報が割り当てられていないため、nottyとなっていること。
ttyが割り当てられていないため、wやwhoで異なる結果となったというのは納得できるところ。

ログインシェルの種類によってはVS CodeのRemote-SSHが使用できないというのもあるらしいが、一応そういうこともないのでいいのかもしれない。

sshポート変更とかファイアウォールとか

VPSで借りてるCentOS7のセキュリティ設定あれやこれやっていう話。

とくに目新しいことをやるわけじゃないので、よくあるような設定をやっていく。

ブルートフォースって一般的よね

適当にセキュアログの最新20件とかとってみるとこんな感じ。
これだけ見ても割と頻繁にやってきているのがよくわかる。

$ sudo grep "Invalid user" /var/log/secure | tail -20
Jan 29 16:47:24 ******** sshd[21619]: Invalid user device from 142.93.185.255 port 39216
Jan 29 16:47:24 ******** sshd[21621]: Invalid user mysql from 142.93.185.255 port 39274
Jan 29 16:47:24 ******** sshd[21623]: Invalid user gpu from 142.93.185.255 port 39316
Jan 29 16:47:24 ******** sshd[21625]: Invalid user yjh from 142.93.185.255 port 39358
Jan 29 16:47:25 ******** sshd[21632]: Invalid user test from 142.93.185.255 port 39484
Jan 29 16:47:26 ******** sshd[21640]: Invalid user heliulu from 142.93.185.255 port 39658
Jan 29 16:47:26 ******** sshd[21642]: Invalid user xguest from 142.93.185.255 port 39712
Jan 29 16:47:26 ******** sshd[21647]: Invalid user hangchen from 142.93.185.255 port 39778
Jan 29 16:47:27 ******** sshd[21653]: Invalid user liuhui from 142.93.185.255 port 39904
Jan 29 16:47:27 ******** sshd[21658]: Invalid user user from 142.93.185.255 port 39994
Jan 29 16:47:27 ******** sshd[21664]: Invalid user test from 142.93.185.255 port 40118
Jan 29 16:47:27 ******** sshd[21666]: Invalid user gym from 142.93.185.255 port 40152
Jan 29 16:47:28 ******** sshd[21668]: Invalid user test from 142.93.185.255 port 40200
Jan 29 16:47:28 ******** sshd[21675]: Invalid user admin from 142.93.185.255 port 40328
Jan 29 16:47:28 ******** sshd[21677]: Invalid user wwwlogs from 142.93.185.255 port 40368
Jan 29 16:47:28 ******** sshd[21679]: Invalid user ubuntu from 142.93.185.255 port 40406
Jan 29 16:47:29 ******** sshd[21681]: Invalid user tsc_dev from 142.93.185.255 port 40444
Jan 29 16:47:29 ******** sshd[21685]: Invalid user upload from 142.93.185.255 port 40538
Jan 29 16:47:29 ******** sshd[21688]: Invalid user dmdba from 142.93.185.255 port 40572
Jan 29 16:47:29 ******** sshd[21690]: Invalid user test from 142.93.185.255 port 40624

とりあえずこいつらを防ぐためにfail2banの導入とか設定とかをやっていく。

設定項目

  • fail2ban導入
  • firewalld設定
  • sshd設定変更

fail2ban導入

インストールとか設定なんかはこの辺りを参考にただやっていく。
knowledge.sakura.ad.jp
www.khstasaba.com
qiita.com
note.classact.co.jp
CentOS7の場合、iptableじゃなくてfirewalldを使用することになるので、そこは間違えないようにとにかくポチポチ設定して起動する。

設定が終わってエラーなく起動していたらよしとする。

$ sudo systemctl status fail2ban
● fail2ban.service - Fail2Ban Service
   Loaded: loaded (/usr/lib/systemd/system/fail2ban.service; enabled; vendor preset: disabled)
   Active: active (running) since 金 2021-01-29 17:54:26 JST; 9s ago
     Docs: man:fail2ban(1)
  Process: 25377 ExecStop=/usr/bin/fail2ban-client stop (code=exited, status=0/SUCCESS)
  Process: 23994 ExecReload=/usr/bin/fail2ban-client reload (code=exited, status=0/SUCCESS)
  Process: 25383 ExecStartPre=/bin/mkdir -p /run/fail2ban (code=exited, status=0/SUCCESS)
 Main PID: 25384 (f2b/server)
    Tasks: 7
   Memory: 10.6M
   CGroup: /system.slice/fail2ban.service
           mq25384 /usr/bin/python2 -s /usr/bin/fail2ban-server -xf start

ちなみに、fail2banのステータス確認時にWARNINGとか表示された場合は、jail設定ファイルに問題がある場合が多いので、設定を見直すこと。
たまにいろいろ変更したものが競合することもあるので、fail2banを再起動するとWARNINGが消えることもある。

fail2banでBANされた状況を確認するためにはfail2ban-clientコマンドやipsetコマンドを使用して確認することになる。
とはいえ確認するためにいちいちコマンド実行するのもめんどくさいので、こんな内容のbashを作成してサーバログイン時とか状況を見たいときに確認するようにしている。

geoiplookupはこんなコマンド。
techracho.bpsinc.jp

現在はGeoIPの最新のDBファイルは、アカウントを作成しないと取得できないようになっている。
とはいえ、ある程度見れればいいのでそのままにしている。

#!/usr/bin/bash
sudo fail2ban-client status sshd
echo "------------------------------------------"
sudo ipset --list
echo "------------------------------------------"
for i in `sudo ipset --list | egrep "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | awk '{print $1}'`
do
    printf "%s : %s\n" "$i" "`geoiplookup $i`"
done

このbashの実行結果としてはこんな感じ
使用している環境はfail2banのBANタイムを変更していたりするのでタイムアウトが長い。
fail2ban-clientでBANされていて、ipsetにその内容が反映されていることがわかるので見たい内容としては十分。
geoipの結果はさきに書いた通り、あくまでも参考。

$ /Local/fail2ban_check.bash
Status for the jail: sshd
|- Filter
|  |- Currently failed: 1
|  |- Total failed:     615
|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned: 5
   |- Total banned:     5
   `- Banned IP list:   178.128.59.188 159.65.13.76 111.14.216.210 142.93.185.255 216.222.148.196
------------------------------------------
Name: f2b-sshd
Type: hash:ip
Revision: 4
Header: family inet hashsize 1024 maxelem 65536 timeout 604800
Size in memory: 600
References: 2
Number of entries: 5
Members:
111.14.216.210 timeout 602958
159.65.13.76 timeout 602958
142.93.185.255 timeout 602958
216.222.148.196 timeout 602958
178.128.59.188 timeout 602958
------------------------------------------
111.14.216.210 : GeoIP Country Edition: CN, China
159.65.13.76 : GeoIP Country Edition: SG, Singapore
142.93.185.255 : GeoIP Country Edition: CA, Canada
216.222.148.196 : GeoIP Country Edition: US, United States
178.128.59.188 : GeoIP Country Edition: GR, Greece

firewalld設定

CentOS7のファイアウォール機能はiptableからfirewalldに変更になっているので、そっちの機能追加
sshdのポート変更をやるならそれを見越しつつ、使用するポートの穴あけを行うように参考を見つつ設定を行う。
qiita.com

sshd設定変更

sshdの設定変更としては、こんな感じのことを実施する。

  • rootの直接ログイン不可
  • パスワード認証を不可、鍵認証のみ許可
  • sshポート変更
rootの直接ログイン不可/パスワード認証を不可、鍵認証のみを許可

sshdのconfig編集と再起動がともに必要なので、とりあえずこのあたりを見て設定。
鍵の作成とかサーバ配置に使用方法もとりあえず参考を見つつ設定。
qiita.com

sshポート変更

これも参考を見つつ設定するだけ。
qiita.com

おまけ

パケットフィルタ

サービスによってはパケットフィルタによる穴あけもできるので、使用している場合はそっちの設定変更もしないとダメ。
firewalldを使っているならパケットフィルタをわざわざ使う必要はない気もするけどね。

SiteGuard

さくらVPSはWeb Application FirewallのSiteGuardが使えるみたいなので、こっちを使ってもいいかもね。
というか、ブルートフォースを防ぐにはこっちのほうが有効な気がする。