Skip to content

Instantly share code, notes, and snippets.

@lo48576
Last active December 16, 2015 00:59
Show Gist options
  • Select an option

  • Save lo48576/5351372 to your computer and use it in GitHub Desktop.

Select an option

Save lo48576/5351372 to your computer and use it in GitHub Desktop.
sshへの攻撃(正確にはログイン失敗)を検出し、twitterへ報告を上げる。twish( https://github.com/L1048576/hikikomorish/blob/master/twish.sh )必須。
#!/bin/sh
IFS=":"
EXE_DIR="`dirname "$0"`"
TEMP_ATTACK_LOG="${EXE_DIR}/.ssh_attack.log"
DATETIME_CACHE="${EXE_DIR}/.ssh_attack_datetime_cache"
NOW="$(date '+%Y-%m-%d %H:%M:%S' --date="@$(( `date '+%s'` - 1 ))")"
if [ ! -r "${DATETIME_CACHE}" ] ; then
echo "${NOW}" >"${DATETIME_CACHE}"
fi
# max total number of login failures
MAX_ACCEPT_TOTAL=7
# max number of login failure per host
MAX_ACCEPT_IP=7
DATETIME_LAST_CHECKED="`cat "${DATETIME_CACHE}"`"
:>"${TEMP_ATTACK_LOG}"
journalctl --no-pager -u sshd --since="${DATETIME_LAST_CHECKED}" \
| sed \
-e '/^[^ ]* [0-9]* [0-9:]* .* sshd\[[0-9]*\]: /!d' \
-e 's/^\([^ ]* *[0-9]* [0-9:]*\) .* sshd\[[0-9]*\]: SSH: Server;Ltype: Authname;Remote: \([0-9.]*\)-[0-9]*;Name: root \[preauth\]/-root:\2:\1/' \
-e 's/^\([^ ]* *[0-9]* [0-9:]*\) .* sshd\[[0-9]*\]: Invalid user \(.*\) from \([0-9.]*\)/-\2:\3:\1/' \
-e '/^-/!d' -e 's/^-//' \
| while read host ipaddr datetime ; do
echo "$host:$ipaddr:`date +'%Y%m%d-%H%M%S' -d "$datetime"`"
done >>"${TEMP_ATTACK_LOG}"
ATTACKS="`wc -l "${TEMP_ATTACK_LOG}" | awk '{print $1}'`"
if [ "${ATTACKS}" -le "${MAX_ACCEPT_TOTAL}" ] ; then
# no attacks detected.
exit 0
fi
IPADDR_LIST="`awk -F':' '{print $2}' "${TEMP_ATTACK_LOG}" | sort | uniq -c | awk '{if($1 >= '"${MAX_ACCEPT_IP}"'){print $2 " (" $1 ")"}}'`"
# FIXME: 長い文字列を分割ツイートしたい
MESSAGE="${ATTACKS} ssh attacks detected from:
${IPADDR_LIST} (${DATETIME_LAST_CHECKED})"
"${EXE_DIR}/twish.sh" update "${MESSAGE}" >/dev/null
"${EXE_DIR}/twish.sh" update "@nu11p0_6477 ふぇぇ…sshが攻撃されてるよぉ…
${IPADDR_LIST} (${DATETIME_LAST_CHECKED}以降)" >/dev/null
echo "${NOW}" >"${DATETIME_CACHE}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment