martes, 21 de diciembre de 2021

Automatización de backups al salir de sesión en FortiOS 7 (fortigate) con fecha y hora

 En "Security Frabric" -> Automation:


Crear una nueva "Action" de tipo CLI Script:



Cambiar IPQUESEA por la IP de nuestro servidor TFTP, y el nombre si se quiere.



Crear un Trigger de tipo "Configuration Change"


Crear Stich






martes, 14 de diciembre de 2021

Sicnronizar DC con NTP

 

1. Sincronizar con hora.roa.es (u otro que se quiera)

w32tm /config /manualpeerlist:hora.roa.es,0x8 /syncfromflags:manual /reliable:yes /update

si fuesen más de uno añadir a la lista como:

w32tm /config /manualpeerlist:hora.roa.es,0x8 servidor2,0x8 ...

2. Verificar

w32tm /query /status


3. Forzar otros DC a redescubrir la config

 Configurarlos a la jerarquía de domino:
w32tm /config /syncfromflags:DOMHIER /update
w32tm /resync /nowait
net stop w32time && net start w32time 

Verificar:

w32tm /query /status
w32tm /monitor


lunes, 4 de octubre de 2021

Proxmox backup con iSCSI

En este caso usaremos una cabina synology a la que denominaremos NAS01  y con IP 10.10.10.10:


Configuración inicial:

Discovery y login:

# iscsiadm -m discovery -t st -p 10.10.10.10

10.10.10.10:3260,1 iqn.2000-01.com.synology:NAS01.default-target.669579eed99

# iscsiadm -m node --login

Logging in to [iface: default, target: iqn.2000-01.com.synology:NAS01.default-target.669579eed99, portal: 10.10.10.10,3260]

Login to [iface: default, target: iqn.2000-01.com.synology:NAS01.default-target.669579eed99, portal: 10.10.10.10,3260] successful.

# iscsiadm -m session -o show
tcp: [2] 10.10.10.10:3260,1 iqn.2000-01.com.synology:NAS01.default-target.669579eed99 (non-flash)

#

Localizamos el disco:

# fdisk -l
Disk /dev/sda: xxxxx GiB, xxxx bytes, xxx sectors
Disk model: MODELO
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 370...

Device       Start       End   Sectors   Size Type
/dev/sda1      XXX      XXX   

[...]

Disk /dev/sdb: [...]

[...]

Disk /dev/sdc: 10 TiB, 10995116277760 bytes, 21474836480 sectors
Disk model: Storage
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
#

Creamos el pool ZFS:

# zpool create -f NAS01LUNBCK01 /dev/sdc


# zpool list
NAME            SIZE  ALLOC   FREE  CKPOINT  EXPANDSZ   FRAG    CAP  DEDUP    HEALTH  ALTROOT
NAS01LUNBCK01  9.98T   106K  9.98T        -         -     0%     0%  1.00x    ONLINE  -
#

Configurar el inicio


ISCSI

# iscsiadm --mode session
tcp: [2] 10.10.10.10:3260,1 iqn.2000-01.com.synology:NAS01.default-target.669579eed99 (non-flash)
# iscsiadm --mode node -T iqn.2000-01.com.synology:NAS01.default-target.669579eed99 -p 10.10.10.10 -o update -n node.startup -v automatic
# iscsiadm --mode node -T iqn.2000-01.com.synology:NAS01.default-target.669579eed99 -p 10.10.10.10 -o update -n node.conn[0].startup -v automatic

ir a /etc/iscsi/iscsid.conf y cambiar manual a automatic:

# To request that the iscsi initd scripts startup a session set to "automatic".
node.startup = automatic
#
# To manually startup the session set to "manual". The default is manual.
#node.startup = manual


ZFS

Localizar path
# systemctl list-units --all --full | grep disk | grep 10.10.10.10 | egrep -v "*part*"
  dev-disk-by\x2dpath-ip\x2d10.10.10.10:3260\x2discsi\x2diqn.2000\x2d01.com.synology:NAS01.default\x2dtarget.669579eed99\x2dlun\x2d1.device          loaded    active   plugged   Storage

crear en /etc/systemd/system la unit zpooliscsi.service y añadir al inicio:

# cat zpooliscsi.service
[Unit]
After=dev-disk-by\x2dpath-ip\x2d10.10.10.10:3260\x2discsi\x2diqn.2000\x2d01.com.synology:NAS01.default\x2dtarget.669579eed99\x2dlun\x2d1.device

[Service]
ExecStart=/usr/sbin/zpool import NAS01LUNBCK01
ExecStartPost=/usr/bin/logger "Inciaiado el Pool ZFS NAS01LUNBCK01"

[Install]
WantedBy=dev-disk-by\x2dpath-ip\x2d10.10.10.10:3260\x2discsi\x2diqn.2000\x2d01.com.synology:NAS01.default\x2dtarget.669579eed99\x2dlun\x2d1.device

#systemctl daemon-reload
# systemctl enable zpooliscsi
Created symlink /etc/systemd/system/dev-disk-by\x2dpath-ip\x2d172.16.250.201:3260\x2discsi\x2diqn.2000\x2d01.com.synology:NAS01.default\x2dtarget.669579eed99\x2dlun\x2d1.device.wants/zpooliscsi.service → /etc/systemd/system/zpooliscsi.service.
# systemctl restart zpooliscsi

Si queremos podemos probar a reiniciar  y comprobar que todo funciona ;)


Comandos útiles tipo linux en PowerShell

Tail

tail -f fichero.log
Get-Content "fichero.log" -Wait

tail -f fichero1.log fichero.log
Get-Content "fichero1.log","fichero2.log" -Wait

Get-Content "*.log" -Wait
Get-Content "*.logs" -Exclude "TS*.log","x.log","*202001*" -Wait

tail -n 10 fichero.log
Get-Content fichero.log -Tail 10

head -n 10 fichero.log
Get-Content "c:\important.log" -Head 10

Find

find . -name *.txt
 Get-ChildItem -Path "." -Recurse -Filter "*.txt" | Format-Table FullName

Para parámetros de tipo -d en find añadir -Directory, en caso de fichero (-f en find) añadir -File
Para que incluya ficheros ocultos -Force
Profundidad de directorios -Depth

Abreviaturas

 Get-ChildItem -> gci
 Get-Content -> gc
 Select-String -> sls
 Format-Table -> ft

Forti vpn con openfortivpn en Linux

apt-get install openfortivpn

Crear fichero de configuracion /etc/openfortivpn/config

# config file for openfortivpn, see man openfortivpn(1)
host = hostquesea.tld
port =443
username = usuario
password = clave
persistent = 30

persistent indica que la conexión es permanente y en caso de caida debe reconectarse cada 30 segundos en este caso.

Si usamos un certificado autogenerado nos dará error, pero este mismo error lo aprovechamos para añadir el certificado como seguro a nuestra configuración.

 openfortivpn -c /etc/openfortivpn/config
ERROR:  Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:
ERROR:      --trusted-cert aaaaaabbbbbcccccccdddddeeeeffffaaaaaa0000111122233334445556a7bcd
ERROR:  or add this line to your config file:
ERROR:      trusted-cert = aaaaaabbbbbcccccccdddddeeeeffffaaaaaa0000111122233334445556a7bcd
ERROR:  Gateway certificate:
ERROR:      subject:
ERROR:          O=Fortinet Ltd.
ERROR:          CN=FortiGate
ERROR:      issuer:
ERROR:          O=Fortinet Ltd.
ERROR:          CN=FortiGate
ERROR:      sha256 digest:
ERROR:          aaaaaabbbbbcccccccdddddeeeeffffaaaaaa0000111122233334445556a7bcd
INFO:   Closed connection to gateway.
ERROR:  Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:
ERROR:      --trusted-cert aaaaaaabbbbbcccccccdddddeeeeffffaaaaaa0000111122233334445556a7bcd
ERROR:  or add this line to your config file:
ERROR:      trusted-cert = aaaaaabbbbbcccccccdddddeeeeffffaaaaaa0000111122233334445556a7bcd
ERROR:  Gateway certificate:
ERROR:      subject:
ERROR:          O=Fortinet Ltd.
ERROR:          CN=FortiGate
ERROR:      issuer:
ERROR:          O=Fortinet Ltd.
ERROR:          CN=FortiGate
ERROR:      sha256 digest:
ERROR:          aaaaaabbbbbcccccccdddddeeeeffffaaaaaa0000111122233334445556a7bcd
INFO:   Could not log out.

añadimos la  línea para el certificado en el fichero de config

# config file for openfortivpn, see man openfortivpn(1)
host = hostquesea.tld
port =443
username = usuario
password = clave
persistent = 30
trusted-cert = aaaaaabbbbbcccccccdddddeeeeffffaaaaaa0000111122233334445556a7bcd

Para que auto arranque y nos de la salida en el tty7 creamos un fichero de unit para el systemd en lib/systemd/system, en este caso llamado openfortivpn.service

cat openfortivpn.service
[Unit]
Description=Cliente OpenForti VPN 
Wants=network-online.target
After=network.target

[Service]
Type=simple
Environment=EMAIL_ADDR=root
ExecStart=/usr/bin/openfortivpn -c /etc/openfortivpn/config
User=root
Group=root
StandardInput=tty
StandardOutput=tty
TTYPath=/dev/tty7

[Install]
WantedBy=multi-user.target

Recargamos la configuración del gestor systemd activamos y arrancamos el servicio:

systemctl daemon-reload
systemctl enable openfortivpn
systemctl start openfortivpn



jueves, 30 de septiembre de 2021

iSCSI eliminar Linux


Ver interfaces, cerrar sesión y eliminar

iscsiadm -m node --print --interface

iscsiadm -m node -T <iqn> -p <IP>:<PUERTO> -u

iscsiadm -m node -o delete -T <iqn>

Verificar:

iscsiadm -m session


martes, 20 de julio de 2021

Cambiar la URL de aplicación ClickOnce

Partimos de que tenemos dos URL de los sitios donde se va a descargar la aplicación:

  • URL antigua: Dirección URL donde se publica actualmente la aplicación y sus actualizaciones
  • URL nueva: Dirección URL donde queremos que se publiquen las nuevas versiones.
Vamos a hacer dos publicaciones en el siguiente orden, cada una de ellas con su correspondiente incremento de revisión, modificando las propiedades de publicación según el siguiente esquema
  • Publicación 1 (en ubicación vieja):
    • URL de publicación: URL de publicación antigua
    • URL de instalación: URL antigua
    • URL de actualización: URL nueva
  • Publicación 2 (en ubicación nueva):
    • URL de publicación: URL de publicación nueva
    • URL de instalación: URL nueva
    • URL de actualización: URL nueva


miércoles, 14 de julio de 2021

Proxmox vm backup status

For comment: Zabbix Share - Proxmox VMs Backup Status Template


The comment is still in  pending status, I paste it here:

Hi,
I have modified the status script to process several backup storages for different jobs. If you have only a job backup the script works as original.

I have added an 8th status: 8 => At least a VM backup OK, but not all. Thus, we know that at least a backup is ok, but not all our jobs were successfully executed.

[....]

The definition of the 8th state trigger prototype:
Name: At least a VM backup for VM {#VM_NUMBER} OK, but not all
Expression: {Template App Proxmox VMs Backup Status:proxmox-vms-backup-status[{#VM_NUMBER},{$BACKUP_PERIOD}].last()}=8
Add value mapping description 8 mapped to "At least a VM backup is OK, but not all"


Modified script:

#!/bin/bash

# Script for checking ProxMox virtual machines backup. For use in Zabbix. Skygge@2016
# Modified: MR_Andrew, 2018. Fran Couñago, 2021
# Special thanks: Max Dark, Marinero from cyberforum.ru

#Variables

backupconfig='/etc/pve/vzdump.cron'
storageconfig='/etc/pve/storage.cfg'
configdir='/etc/pve/local/qemu-server'

# Check every VM for existing backup files and check if they're newer than 7 days

mapfile -t bckstorarray < <( awk  -v vm=$1 '$0 ~ vm {for(i=1;i<NF;i++) {if( $i ~ /--storage/) print $(i+1)}}'  $backupconfig|sort|uniq)
# read physical backup path from storage configuration file for VM $1
if [ ${#bckstorarray[@]} = 0 ]; then
	#echo "Invalid VM number, or backup for VM $1 is not configured."
	echo 0
else
	#Array with multiple errors
	ONEBAD=0
	ONEGOOD=0
	for backupstorage in "${bckstorarray[@]}"
	do		
		backupdirectory=`cat $storageconfig|grep -w -A 1 $backupstorage|grep path|rev|cut -d " " -f 1|rev`		
		#echo BCKDIR=$backupdirectory
		if [ -d $backupdirectory/dump ]; then
				# check if backup file(s) exists on backup path for VM $1
				backup=`ls $backupdirectory/dump/|grep "$1" |grep -v -E "log|tmp|dat"|wc -l`
				if [ "$backup" = "0" ]; then
					#echo "VM $1 has no backup file."
					ONEBAD=2					
				else
					# check if backup file is newer than $2 day(s) for VM $1
					newbackup=`find $backupdirectory/dump/ -type f -name "*$1*" -not -name "*.log" -not -name "*.tmp" -not -name "*.dat" -mtime -$2 | sort -nr | head -1|wc -l`
						if [ "$newbackup" = "0" ]; then
							#echo "VM $1 backup is older than $2 day(s)."
							ONEBAD=3
						else
								#check last log file for errors
								backuplastlog=`ls $backupdirectory/dump/ | grep "$1" | grep log | tail -1`
								backupresult=`cat $backupdirectory/dump/$backuplastlog | grep -i -E "ERROR|FAILED"`
										if [ "$backupresult" = "" ];then
												#echo "VM $1 backup is OK, no errors found."
												ONEGOOD=1												
										else
												#echo "VM $1 backup finished with errors. Please, check logs."
												ONEBAD=0
										fi
						fi
				fi			
		else
			#echo "Backup directory for VM $1 does not exists."
			ONEBAD=1
		fi		
	done
	if [ $ONEGOOD = 1 ]; then
		if [ $ONEBAD != 0 ] ; then
			echo 8
		else
			echo 7
		fi
	else
		echo $ONEBAD
	fi
fi

Add Trigger Prototype:


Add Value Mapping



lunes, 31 de mayo de 2021

Seleccionar monitores en cliente de escritorio remoto (Remote Desktop Connection)

El fichero de configuración de RDP (una vez salvado) se puede editar con un fichero de texto, en este fichero si hemos puesto la opción de usar todos los monitores para la sesión remota nos aparecerá una línea que pone:

use multimon:i:1

para seleccionar los monitores en concreto que queremos utilizar debemos añadir la línea:

selectedmonitors:s:1,2

donde 1 y 2 son los identificadores de los monitores, estos identificadores pueden obtenerse ejecutando

mstsc /l


 


Fuentes:

Supported Remote Desktop RDP file settings | Microsoft Docs

How to remote desktop fullscreen RDP with just SOME of your multiple monitors - Scott Hanselman's Blog

miércoles, 27 de enero de 2021

Instalar aplicaciones de la MS Store vía powershell (.appx)

Usar Add-ApxPackage

Para todos los usuarios usar Add-ProvisionedAppPackage 

Por ejemplo para añadir un paquete en la imagen de sistema operativo que estamos usando (ene este casno no requiere fichero de licnecia) se usa:

Add-ProvisionedAppPackage  -Online -Skiplicense -PackagePath paquete.Appx

Para ver los links de descarga fácimente https://store.rg-adguard.net/

Si tiene dependencias habría que ponerlas de la siguiente forma:

Add-ProvisionedAppPackage   -Online -SkipLicense -PackagePath paquete.AppxBundle  -DependencyPackagePath paquete1.Appx,paquete2.Appx,paqueten.Appx

L2TP Ipsec Windows to Mikrotik eror 789

 Add this to registry REG ADD HKLM\SYSTEM\CurrentControlSet\Services\PolicyAgent /v AssumeUDPEncapsulationContextOnSendRule /t REG_DWORD /d...