Check duplicate disk LABEL before mounting it to the system in bash script - linux

is there a way to check if there is duplicate disk LABEL before mounting it to the system?
i need to make sure that if the user have two external drives, if the two of them have the same label, prompt to the user a warning and asking it to remove the duplicated disk.
my code is in the early stages:
if mountpoint -q "${JOB_MOUNT_DIR}"; then
echo " ${JOB_MOUNT_HD_LABEL} já está montado e está pronto para uso"
else
echo "O dispositivo ""${JOB_MOUNT_HD_LABEL}"" não está montado no diretório ""${JOB_MOUNT_DIR}"""
echo "Deseja montar o diretório?"
echo -n "Qual sua opção? [s/n]: "
read -r "opcao"
if [ "$opcao" == "s" ]; then
mkdir -p "${JOB_MOUNT_DIR}/${JOB_MOUNT_HD_LABEL}"
mount -L "${JOB_MOUNT_HD_LABEL}" "${JOB_MOUNT_DIR}/${JOB_MOUNT_HD_LABEL}"
exit 0
else
echo "Disco não irá ser montado"
exit 0
fi
fi
exit 0
some parts are in pt-br i think that will not be a problem
first it checks if that the disk is already mounted, if not it asks to mount, then there is the problem to know which of the two disk with the same LABEL is to mount

You can use:
lsblk -o name,label
NAME LABEL
mmcblk0
└─mmcblk0p1 eMMC
Or you can use:
blkid
/dev/nvme0n1p1: UUID="36D7-B890" TYPE="vfat" PARTUUID="8614534f-01"
/dev/nvme0n1p5: UUID="65885781-bd9b-4c62-afb0-4a82a0e5759e" TYPE="ext4" PARTUUID="8614534f-05"
/dev/mmcblk0p1: LABEL="eMMC" UUID="79ff33b4-2add-4f2f-844e-d7d242c18578" TYPE="ext4" PARTUUID="d4b36674-ab5f-4f15-bb83-313cce242fe4"
You may need to prefix above commands with sudo
If the above commands get your labels correctly, you can pipe the output roughly as follows to list duplicates:
lsblk -o label | sort | uniq -d

Related

Destroying luks header on dm-crypt linux

I am trying to destroy the luks header on one of my logical volume data1, I am still able to read the file inside data1 after I delete the luks header. I suppose it should not be the case right? Can someone help me in understanding this case?
lsblk output
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 894.2G 0 disk
├─sda1 8:1 0 500M 0 part /boot
└─sda2 8:2 0 893.8G 0 part
├─vg0-root 251:0 0 758.7G 0 lvm
│ └─luks-45f803e5-3c17-4aaf-a9ad-d66c8b5458de 251:2 0 758.7G 0 crypt /
├─vg0-swap 251:1 0 75G 0 lvm [SWAP]
├─vg0-data3 251:3 0 20G 0 lvm
│ └─luks-6e168d35-26dc-429c-a3d6-8cb4f1c1d39e 251:7 0 20G 0 crypt /data3
├─vg0-data2 251:4 0 20G 0 lvm
│ └─luks-75727dd1-a332-423d-8c37-4cedf9cbe83c 251:8 0 20G 0 crypt /data2
└─vg0-data1 251:5 0 20G 0 lvm
└─luks-cf2d9729-2d1b-48b8-8502-dea937ef602f 251:6 0 20G 0 crypt /data1
Luksdump output to check if the luks header is exists:
-130-sapam#test-host:~ $ sudo cryptsetup luksDump /dev/mapper/vg0-data1
LUKS header information for /dev/mapper/vg0-data1
Version: 1
Cipher name: aes
Cipher mode: xts-plain64
Hash spec: sha256
Payload offset: 4096
MK bits: 256
MK digest: 9f e7 1a b3 0e fb 4e bc 6d 1b 9e 46 f8 bd 15 22 ea 04 6e c3
MK salt: 83 5e 90 5b b3 a1 c5 a5 d4 22 a0 3e 23 25 51 50
fc cd a8 ac db 9f d0 a8 8b 81 6e 9a 92 1f d8 d3
MK iterations: 43750
UUID: cf2d9729-2d1b-48b8-8502-dea937ef602f
Key Slot 0: ENABLED
Iterations: 439102
Salt: f1 6d 23 b0 b7 ee fc 09 8c 6b 92 ef b2 17 ef d9
0c 83 64 29 bf bc 98 3f f6 93 4b 45 06 49 a9 21
Key material offset: 8
AF stripes: 4000
Key Slot 1: DISABLED
Key Slot 2: DISABLED
Key Slot 3: DISABLED
Key Slot 4: DISABLED
Key Slot 5: DISABLED
Key Slot 6: DISABLED
Key Slot 7: DISABLED
Destroying the luks header:
-130-sapam#test-host:~ $ sudo dd bs=512 count=4096 if=/dev/zero of=/dev/mapper/vg0-data1
4096+0 records in
4096+0 records out
2097152 bytes (2.1 MB) copied, 0.00444235 s, 472 MB/s
-0-sapam#test-host:~ $ sudo cryptsetup luksDump /dev/mapper/vg0-data1
-1-sapam#test-host:~ $
I still able to read the file inside /data1/
-1-sapam#test-host:~ $ cat /data1/foo
james
-0-sapam#test-host:~ $
From my understanding is once the header is destroyed, the /data1 should not be able to read right?
It seems you are destroying already mounted partition.
Encryption/decryption keys are hold in the memory while the partition is mounted. You should unmout your LUKS partition first:
# umount /data1
and then erase the LUKS header. You won't be able to mount it again.
Please note cryptsetup utility has a command to erase LUKS header:
# cryptsetup luksErase /dev/mapper/vg0-data1
The advantage of this operation is that you can restore LUKS header from the backup if you done it before.
from cryptsetup(8):
erase <device>
luksErase <device>
Erase all keyslots and make the LUKS container permanently inac‐
cessible. You do not need to provide any password for this op‐
eration.
WARNING: This operation is irreversible.
While luksErase is nice to wipe the keyslots area, note that it doesn't actually destroy the entire LUKS Header. It leaves the metadata intact.
I submitted a feature request asking for the luksErase command to have the ability to wipe the plaintext metadata in the header as well, but the developer rejected & closed it :(
LUKS Header Shredder
You can use the following BASH script to find every LUKS device on the system, wipe the headers, and shutdown the machine.
Disclaimer
The script below contains experimental software that may or may not lead to corruption or total permanent deletion of some or all of your data. I cannot be responsible for any data loss that has occurred as a result of following this guide.
The contents of this answer is provided openly and is licensed under the CC-BY-SA license. The software included in this guide is licensed under the GNU GPLv3 license. All content here is consistent with the limitations of liabilities outlined in its respective licenses.
I highly recommend that any experiments with the script included in this answer is used exclusively on a disposable machine containing no valuable data.
If data loss is a concern for you, then leave now and do not proceed. You have been warned.
#!/bin/bash
#set -x
################################################################################
# File: buskill-selfdestruct.sh
# Purpose: Self-destruct trigger script for BusKill Kill Cord
# For more info, see: https://buskill.in/
# WARNING: THIS IS EXPERIMENTAL SOFTWARE THAT IS DESIGNED TO CAUSE PERMANENT,
# COMPLETE AND IRREVERSIBLE DATA LOSS!
# Note : This script will *not* execute unless it's passed the '--yes'
# argument. Be sure to test this trigger before depending on it!
# Authors: Michael Altfield <michael#buskill.in>
# Created: 2020-03-11
# Updated: 2020-03-11
# Version: 0.1
################################################################################
############
# SETTINGS #
############
BUSKILL_LOCK='/usr/local/bin/buskill-lock.sh'
[ -f ${BUSKILL_LOCK} ] || echo "ERROR: Unable to find buskill-lock.sh"
CRYPTSETUP=`which cryptsetup` || echo "ERROR: Unable to find cryptsetup"
LS=`which ls` || echo "ERROR: Unable to find ls"
CAT=`which cat` || echo "ERROR: Unable to find cat"
GREP=`which grep` || echo "ERROR: Unable to find grep"
ECHO=`which echo` || echo "ERROR: Unable to find echo"
AWK=`which awk` || echo "ERROR: Unable to find awk"
HEAD=`which head` || echo "ERROR: Unable to find head"
LSBLK=`which lsblk` || echo "ERROR: Unable to find lsblk"
OD=`which od` || echo "ERROR: Unable to find od"
##############
# ROOT CHECK #
##############
# re-run as root
if [[ $EUID -ne 0 ]]; then
exec sudo /bin/bash "$0" "$#"
fi
###########
# CONFIRM #
###########
# for safety, exit if this script is executed without a '--yes' argument
${ECHO} "${#}" | ${GREP} '\--yes' &> /dev/null
if [ $? -ne 0 ]; then
${ECHO} "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING"
${ECHO} "================================================================================"
${ECHO} "WARNING: THIS IS EXPERIMENTAL SOFTWARE THAT IS DESIGNED TO CAUSE PERMANENT, COMPLETE AND IRREVERSIBLE DATA LOSS!"
${ECHO} "================================================================================"
${ECHO} "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING"
${ECHO}
${ECHO} "cowardly refusing to execute without the '--yes' argument for your protection. If really you want to proceed with damaging your system, retry with the '--yes' argument"
exit 1
fi
###########################
# (DELAYED) HARD SHUTDOWN #
###########################
# The most secure encrypted computer is an encrypted computer that is *off*
# This is our highest priority; initiate a hard-shutdown to occur in 5 minutes regardless
# of what happens later in this script
nohup sleep 60 && echo o > /proc/sysrq-trigger &
nohup sleep 61 && shutdown -h now &
nohup sleep 62 && poweroff --force --no-sync &
###############
# LOCK SCREEN #
###############
# first action: lock the screen!
${BUSKILL_LOCK} &
#####################
# WIPE LUKS VOLUMES #
#####################
# overwrite luks headers
${ECHO} "INFO: shredding LUKS header (plaintext metadata and keyslots with encrypted master decryption key)"
writes=''
IFS=$'\n'
for line in $( ${LSBLK} --list --output 'PATH,FSTYPE' | ${GREP} 'crypt' ); do
device="`${ECHO} \"${line}\" | ${AWK} '{print \$1}'`"
${ECHO} -e "\t${device}"
###########################
# OVERWRITE LUKS KEYSLOTS #
###########################
# erases all keyslots, making the LUKS container "permanently inaccessible"
${CRYPTSETUP} luksErase --batch-mode "${device}" || ${HEAD} --bytes 20M /dev/urandom > ${device} &
# store the pid of the above write tasks so we can try to wait for it to
# flush to disk later -- before triggering a brutal hard-shutdown
writes="${writes} $!"
#####################################
# OVERWRITE LUKS PLAINTEXT METADATA #
#####################################
luksVersion=`${OD} --skip-bytes 6 --read-bytes 2 --format d2 --endian=big --address-radix "n" "${device}"`
# get the end byte to overwrite. For more info, see:
# https://security.stackexchange.com/questions/227359/how-to-determine-start-and-end-bytes-of-luks-header
if [[ $luksVersion -eq 1 ]]; then
# LUKS1: https://gitlab.com/cryptsetup/cryptsetup/-/wikis/LUKS-standard/on-disk-format.pdf
# in LUKS1, the whole header ends at 512 * the `payload-offset`
# this is actually more than we need (includes keyslots), but
# it's the fastest/easiest to bound to fetch in LUKS1
payloadOffset=`${OD} --skip-bytes 104 --read-bytes 4 --format d4 --endian=big --address-radix "n" "${device}"`
luksEndByte=$(( 512 * ${payloadOffset} ))
elif [[ $luksVersion -eq 2 ]]; then
# LUKS2: https://gitlab.com/cryptsetup/LUKS2-docs/blob/master/luks2_doc_wip.pdf
# in LUKS2, the end of the plaintext metadata area is twice the
# size of the `hdr_size` field
hdr_size=`${OD} --skip-bytes 8 --read-bytes 8 --format d8 --endian=big --address-radix "n" "${device}"`
luksEndByte=$(( 2 * ${hdr_size} ))
else
# version unclear; just overwrite 20 MiB
luksEndByte=20971520
fi
# finally, shred that plaintext metadata; we do this in a new file descriptor
# to prevent bash from truncating if ${device} is a file
exec 5<> "${device}"
${HEAD} --bytes "${luksEndByte}" /dev/urandom >&5 &
writes="${writes} $!"
exec 5>&-
done
#######################
# WAIT ON DISK WRITES #
#######################
# wait until all the write tasks above have completed
# note: do *not* put quotes around this arg or the whitespace will break wait
wait ${writes}
# clear write buffer to ensure headers overwrites are actually synced to disks
sync; echo 3 > /proc/sys/vm/drop_caches
#################################
# WIPE DECRYPTION KEYS FROM RAM #
#################################
# suspend each currently-decrypted LUKS volume
${ECHO} "INFO: removing decryption keys from memory"
for device in $( ${LS} -1 "/dev/mapper" ); do
${ECHO} -e "\t${device}";
${CRYPTSETUP} luksSuspend "${device}" &
# clear page caches in memory (again)
sync; echo 3 > /proc/sys/vm/drop_caches
done
#############################
# (IMMEDIATE) HARD SHUTDOWN #
#############################
# do whatever works; this is important.
echo o > /proc/sysrq-trigger &
sleep 1
shutdown -h now &
sleep 1
poweroff --force --no-sync &
# exit cleanly (lol)
exit 0
Sources
LUKS Header Shredder (BusKill Self-Destruct Trigger)
https://github.com/BusKill/buskill-linux/blob/master/triggers/buskill-selfdestruct.sh

Bash Script for find a Script in a path and launch that another script

Look , i have this script , its for find , a Script inside a "path" , and launch the another script called ".Iniciar"
#!/bin/sh
# La Funcion de este Script es encontrar el directorio
# Real donde se encuentra el programa
# La Version Original es de :
# 17 de Febrero del 2000 - Sam Lantinga, Loki Entertainment Software
# Esta Version Ha sido Traducida por
# Inukaze De Venezuela
# Sitio : http://inukaze.wordpress.com
Encontrar_Ruta()
{
ruta_completa="`echo $1 | grep /`"
if [ "$ruta_completa" = "" ]; then
oIFS="$IFS"
IFS=:
for path in $PATH
do if [ -x "$path/$1" ]; then
if [ "$path" = "" ]; then
path="."
fi
ruta_completa="$path/$1"
break
fi
done
IFS="$oIFS"
fi
if [ "$ruta_completa" = "" ]; then
ruta_completa="$1"
fi
if [ -L "$ruta_completa" ]; then
ruta_completa=`ls -l "$ruta_completa" |sed -e 's/.* -> //' |sed -e 's/\*//'`
fi
dirname $ruta_completa
}
if [ "${RUTA_DEL_SOFTWARE}" = "" ]; then
RUTA_DEL_SOFTWARE="`Encontrar_Ruta $0`"
fi
LD_LIBRARY_PATH=.:${RUTA_DEL_SOFTWARE}:${LD_LIBRARY_PATH}
export LD_LIBRARY_PATH
if [ -x "${RUTA_DEL_SOFTWARE}/.Iniciar" ]
then
cd "${RUTA_DEL_SOFTWARE}/"
exec "./.Iniciar" $*
fi
echo "No Puedo ejecutar este Software. Esta bien escrito el Script de Inicio?"
exit 1
Ok , the thing its this works with path without spaces , well , im trying to run from
path "/media/Compartido/Juegos/Emuladores & Roms/MS-D.O.S/Aladdin"
for example when my terminal is in the folder "Desktop"
$ cd $HOME/Desktop
$ sh "/media/Compartido/Juegos/Emuladores & Roms/MS-D.O.S/Aladdin"/Iniciar
No Puedo ejecutar este Software. Esta bien escrito el Script de Inicio?
I can't launch it
But if i copy the folder to "/media/Shared/Games/MS-D.O.S/Aladdin"
[ inukaze | 23-09-2014 | 08:55 pm ]
[Desktop]$ sh "/media/Shared/Games/MS-D.O.S/Aladdin"/Iniciar
Encontrado el Archivo de Configuracion para : Aladdin
DOSBox version 0.74
Copyright 2002-2010 DOSBox Team, published under GNU GPL.
---
CONFIG:Loading primary settings from config file Aladdin.conf
MIXER:Got different values from SDL: freq 22050, blocksize 256
ALSA:Can't subscribe to MIDI port (65:0) nor (17:0)
MIDI:Opened device:none
Two or more joysticks reported, initializing with 2axis
Using joystick USB Gamepad with 2 axes, 10 buttons and 0 hat(s)
Using joystick Xbox Gamepad (userspace driver) with 6 axes, 11 buttons and 1 hat(s)
and trying with "zsh" from original location
[ inukaze | 23-09-2014 | 08:58 pm ]
[Desktop]$ zsh "/media/Compartido/Juegos/Emuladores & Roms/MS-D.O.S/Aladdin"/Iniciar
Encontrado el Archivo de Configuracion para : Aladdin
DOSBox version 0.74
Copyright 2002-2010 DOSBox Team, published under GNU GPL.
---
CONFIG:Loading primary settings from config file Aladdin.conf
MIXER:Got different values from SDL: freq 22050, blocksize 256
ALSA:Can't subscribe to MIDI port (65:0) nor (17:0)
MIDI:Opened device:none
Two or more joysticks reported, initializing with 2axis
Using joystick USB Gamepad with 2 axes, 10 buttons and 0 hat(s)
Using joystick Xbox Gamepad (userspace driver) with 6 axes, 11 buttons and 1 hat(s)
this works too , but i wanna ran from bash / sh
Thank you for any help.
If paths with spaces cause problems that always means you haven't used enough quoting.
Specifically you are using variables that can contain spaces without "quoting" them.
For example in the following line.
RUTA_DEL_SOFTWARE="`Encontrar_Ruta $0`"
You don't quote $0. So when you run sh "/media/Compartido/Juegos/Emuladores & Roms/MS-D.O.S/Aladdin"/Iniciar despite quoting the path as the argument there when you use that path (as $0) in the line above what the shell sees is:
RUTA_DEL_SOFTWARE="`Encontrar_Ruta '/media/Compartido/Juegos/Emuladores' '&' 'Roms/MS-D.O.S/Aladdin/Iniciar'`"
which then doesn't set $1 correctly in your function.
So to sum up: Use more quotes.

How to delete the data in Character device

I have written some data into my character device in /dev/my_char.
What should I do to delete the data without removing the device from the kernel ? .
The method which I follow to delete the contents is to
1) rm /dev/my_char and
2) rmmod My_Char.
But by using this method, I have to insert the module again into the kernel and create the device in dev folder which is a lengthy process.
Using only rm /dev/my_char doesn't delete its contents.
I would like to know if there is any other method other than this.
You could implement an ioctl to reset the input buffer.
Add an ioctl handler to the driver.
Add the entry point to the file_operations structure. .unlocked_ioctl =(your function name)
For the case of the correct ioctl command, reset the buffer pointer(s), clear the count, or whatever is needed to make the device look empty.
Or you could write a script to remove the driver and reload it. Here is what I use (I call it reload):
#!/bin/bash
if [ -d /device/my_device ]; then
sudo rmmod my_device.ko
fi
VERBOSE=0
MESSAGES=0
VENDOR=
DEVICEID=
while (( $# > 0 ))
do
arg="$1"
shift
case $arg in
v=* | ve=* | ver=* | verb=* | verbo=* | verbos=* | verbose=*)
VERBOSE=${arg#*=}
;;
v | ve | ver | verb | verbo | verbos | verbose)
VERBOSE=1
;;
t | tt | tty)
MESSAGES=1
;;
ven=* | vend=* | vendo=* | vendor=*)
VENDOR="opt_vendor_id=${arg#*=}"
;;
ven | vend | vendo | vendor)
VENDOR="opt_vendor_id=$1"
shift
;;
d=* | de=* | dev=* | devi=* | devic=* | device=*)
DEVICEID="opt_device_id=${arg#*=}"
;;
d | de | dev | devi | devic | device)
DEVICEID="opt_device_id=$1"
shift
;;
*)
echo "Invalid option '$arg':"
echo "Options are 'verbose', 'tty', 'vendor='<vendor number>, and 'deviceid='<device id>"
exit 1
;;
esac
done
echo "insmod my_device.ko opt_verbose=$VERBOSE opt_tty_msgs=$MESSAGES $VENDOR $DEVICEID"
sudo insmod my_device.ko opt_verbose=$VERBOSE opt_tty_msgs=$MESSAGES $VENDOR $DEVICEID
This has a lot of extra complexity to handle parameters which are passed to the module when it is loaded. If you don't have any module parameters, the above can be simplified to:
#!/bin/bash
if [ -d /device/my_device ]; then
sudo rmmod my_device.ko
fi
sudo insmod my_device.ko
You can work with your character device as if it is a generic file
cat /dev/null > /dev/my_char
Its possible to delete the data in the device by just removing the module from the kernel and then loading the module again to the kernel.ie "rmmod My_Char" and again "insmod My_Char".By this method we need not create the device again in the /dev/my_char as it will be automatically loaded with no data.

Segmentation fault while using bash script to generate mobility file

I am using a bash script to generate mobility files (setdest) in ns2 for various seeds. But I am running into this troublesome segmentation fault. Any help would be appreciated. The setdest.cc has been modified, so its not the standard ns2 file.
I will walk you through the problem.
This code in a shell script returns the segmentation fault.
#! /bin/sh
setdest="/root/ns-allinone-2.1b9a/ns-2.1b9a/indep-utils/cmu-scen-gen/setdest/setdest_mesh_seed_mod"
let nn="70" #Number of nodes in the simulation
let time="900" #Simulation time
let x="1000" #Horizontal dimensions
let y="1000" #Vertical dimensions
for speed in 5
do
for pause in 10
do
for seed in 1 5
do
echo -e "\n"
echo Seed = $seed Speed = $speed Pause Time = $pause
chmod 700 $setdest
setdest -n $nn -p $pause -s $speed -t $time -x $x -y $y -l 1 -m 50 > scen-mesh-n$nn-seed$seed-p$pause-s$speed-t$time-x$x-y$y
done
done
done
error is
scengen_mesh: line 21: 14144 Segmentation fault $setdest -n $nn -p $pause -s $speed -t $time -x $x -y $y -l 1 -m 50 >scen-mesh-n$nn-seed$seed-p$pause-s$speed-t$time-x$x-y$y
line 21 is the last line of the shell script (done)
The strange thing is If i run the same setdest command on the terminal, there is no problem! like
$setdest -n 70 -p 10 -s 5 -t 900 -x 1000 -y 1000 -l 1 -m 50
I have made out where the problem is exactly. Its with the argument -l. If i remove the argument in the shell script, there is no problem. Now i will walk you through the modified setdest.cc where this argument is coming from.
This modified setdest file uses a text file initpos to read XY coordinates of static nodes for a wireless mesh topology. the relevant lines of code are
FILE *fp_loc;
int locinit;
fp_loc = fopen("initpos","r");
while ((ch = getopt(argc, argv, "r:m:l:n:p:s:t:x:y:i:o")) != EOF) {
switch (ch) {
case 'l':
locinit = atoi(optarg);
break;
default:
usage(argv);
exit(1);
if(locinit)
fscanf(fp_loc,"%lf %lf",&position.X, &position.Y);
if (position.X == -1 && position.Y == -1){
position.X = uniform() * MAXX;
position.Y = uniform() * MAXY;
}
What i dont get is...
In Shell script..
-option -l if supplied by 0 returns no error,
-but if supplied by any other value (i used 1 mostly) returns this segmentation fault.
In Terminal..
-no segmentation fault with any value. 0 or 1
something to do with the shell script surely. I am amazed what is going wrong where!
Your help will be highly appreciated.
Cheers

Integrity Measurement Architecture(IMA) & Linux Extended Verification Module (EVM)

I am trying to activate IMA appraisal & EVM modules.
After compiling linux kernel 3.10.2 on my bt5R3 and setting kernel boot option in a first time like this:
GRUB_CMDLINE_LINUX="rootflags=i_version ima_tcb ima_appraise=fix ima_appraise_tcb evm=fix"
and after running this command to generate xattr security.ima and security.evm
find / \( -fstype rootfs -o -fstype ext4 \) -type f -uid 0 -exec head -c 1 '{}' \;
like this:
GRUB_CMDLINE_LINUX="rootflags=i_version ima_tcb ima_appraise=enforce ima_appraise_tcb evm=enforce"
I try to create digital signature of xattr like it's recommended on this tutorial
Tutorial to IMA & EVM
Every steps have been followed, creating RSA keys, loading them early at boot in initramfs with keyctl.
Session Keyring
-3 --alswrv 0 65534 keyring: _uid_ses.0
977514165 --alswrv 0 65534 \_ keyring: _uid.0
572301790 --alswrv 0 0 \_ user: kmk-user
126316032 --alswrv 0 0 \_ encrypted: evm-key
570886575 --alswrv 0 0 \_ keyring: _ima
304346597 --alswrv 0 0 \_ keyring: _evm
However as soon as I reboot my OS when I try to read a signed and hashed file I get the error "Permission Denied"
Running dmesg tells me :
[ 5461.175996] type=1800 audit(1375262160.913:57): pid=1756 uid=0 auid=4294967295 ses=4294967295 op="appraise_data" cause="**invalid-HMAC**" comm="sh" name="/root/Desktop/new.sh" dev="sda1" ino=546526 res=0
Have you any idea why i get invalid HMAC ?
They keys are loaded like the tutorial says...
#!/bin/sh -e
PREREQ=""
# Output pre-requisites
prereqs()
{
echo "$PREREQ"
}
case "$1" in
prereqs)
prereqs
exit 0
;;
esac
grep -q "ima=off" /proc/cmdline && exit 1
mount -n -t securityfs securityfs /sys/kernel/security
IMA_POLICY=/sys/kernel/security/ima/policy
LSM_POLICY=/etc/ima_policy
grep -v "^#" $LSM_POLICY >$IMA_POLICY
# import EVM HMAC key
keyctl show |grep -q kmk || keyctl add user kmk "testing123" #u
keyctl add encrypted evm-key "load `cat /etc/keys/evm-key`" #u
#keyctl revoke kmk
# import Module public key
mod_id=`keyctl newring _module #u`
evmctl import /etc/keys/pubkey_evm.pem $mod_id
# import IMA public key
ima_id=`keyctl newring _ima #u`
evmctl import /etc/keys/pubkey_evm.pem $ima_id
# import EVM public key
evm_id=`keyctl newring _evm #u`
evmctl import /etc/keys/pubkey_evm.pem $evm_id
# enable EVM
echo "1" > /sys/kernel/security/evm
# enable module checking
#echo "1" > /sys/kernel/security/module_check
Thanks for your help
Solved, new kernel use HMAC v2 and you have to activate asymmetric key when you compile kernel.
cat .config should have this entries:
CONFIG_EVM_HMAC_VERSION=2
CONFIG_ASYMMETRIC_KEY_TYPE=y
Then when you hash or sign a file use
evmctl -u - -x --imasig/--imahash $file
As well you should have create the asymetric keys and load them in _evm and _ima keyring with keyctl with initramfs.

Resources