Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add initial start support for MS1.5 #318

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 96 additions & 25 deletions common/scripts/generate_keys.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,21 @@ output_path="/opt"

# list the available slots and check if the token label exists
token_label="secccoms"
slot_id=""
free_slot_id=""

### Check if a directory does not exist ###
if [ ! -d "$output_path" ]
then
mkdir -p "$output_path"
fi

set_openssl_env()
{
export OPENSSL_CONF=/opt/comms_openssl.cnf
echo "OPENSSL_CONF=$OPENSSL_CONF"
}

initialize_hsm()
{
#add line at the beginning of the file
Expand Down Expand Up @@ -81,12 +89,63 @@ else
pin=$(tr -dc '0-9' </dev/random | head -c 6)
fi

initialize_all()
create_and_init_token()
{
#intialize token
pkcs11-tool --module="$LIB" --init-token --label secccoms --so-pin "$pin" # --pin "$pin"
#init the pin
pkcs11-tool --init-pin --login --pin "$pin" --so-pin "$pin" --module "$LIB"
echo "pin: $pin"
pkcs11-tool --slot "$free_slot_id" --module="$LIB" --init-token --label secccoms --so-pin "$pin" # --pin "$pin"
}

get_slot_id_by_token_label()
{
slots_info=$(pkcs11-tool --module "$LIB" --list-slots)

# Loop through slot information
while IFS= read -r line; do
if [[ $line == "Slot "* ]]; then
# Extract the slot ID from the line
hex_id=$(echo "$line" | grep -o -P '\(0x[0-9a-fA-F]+\)' | sed 's/[\(\)]//g')
elif [[ $line == " token label"* ]]; then
# Extract the token label from the line
label=$(echo "$line" | awk -F ':' '{print $2}' | awk '{$1=$1;print}')

# Check if the label matches the desired token label
if [[ "$label" == "$token_label" ]]; then
slot_id="$hex_id"
break # Exit the loop if the label is found
fi
fi
done <<< "$slots_info"
echo "slot_id: $slot_id"
}

get_next_free_slot_id()
{
slots_info=$(pkcs11-tool --module "$LIB" --list-slots)

# Loop through slot information
while IFS= read -r line; do
if [[ $line == "Slot "* ]]; then
# Extract the slot ID from the line
hex_id=$(echo "$line" | grep -o -P '\(0x[0-9a-fA-F]+\)' | sed 's/[\(\)]//g')
elif [[ $line == " token state"* ]]; then
# Extract the token label from the line
state=$(echo "$line" | awk -F ':' '{print $2}' | awk '{$1=$1;print}')

# Check if the label matches the desired token label
if [[ "$state" == "uninitialized" ]]; then
free_slot_id="$hex_id"
break # Exit the loop if the label is found
fi
fi
done <<< "$slots_info"
echo "free_slot_id: $free_slot_id"
}

set_user_pin()
{
echo "Set user pin for slot $slot_id"
pkcs11-tool --slot "$slot_id" --init-pin --login --pin "$pin" --so-pin "$pin" --module "$LIB"
}

hard_delete()
Expand All @@ -97,7 +156,7 @@ if [ ${#softhsm2_output} -ne 616 ]
echo "Token exists"
# token_label=$(echo "$softhsm2_output" | grep 'Label:' | sed 's/^.*: //')
serial=$(softhsm2-util --show-slot |grep Serial |awk '{print $3}')
softhsm2-util --slot 1 --delete-token --serial "$serial"
softhsm2-util --slot "$slot_id" --delete-token --serial "$serial"
# softhsm2-util --slot 1 --delete-token --token "$token_label"
else
echo "No Token exists"
Expand All @@ -106,18 +165,18 @@ fi

soft_delete()
{
if pkcs11-tool --module="$LIB" --list-slots | grep -q "Label: $token_label"; then
if pkcs11-tool --slot "$slot_id" --module="$LIB" --list-slots | grep -q "$token_label"; then
echo "Token exists"
# delete the existing token
pkcs11-tool --module="$LIB" --login --pin "$pin" --delete-token --label "$token_label" #we need the pin from previous execution
pkcs11-tool --slot "$slot_id" --module="$LIB" --login --pin "$pin" --delete-token --label "$token_label" #we need the pin from previous execution
#delete keys
keys=$(pkcs11-tool --module="$LIB" -O --login --pin "$pin")
if [ ${#keys} -ne 0 ]
then
echo "Keys Found"
echo "Deleting old keys"
pkcs11-tool --module="$LIB" --login --pin "$pin" --delete-object --type privkey --id 01
pkcs11-tool --module="$LIB" --login --pin "$pin" --delete-object --type pubkey --id 01
pkcs11-tool --slot "$slot_id" --module="$LIB" --login --pin "$pin" --delete-object --type privkey --id 01
pkcs11-tool --slot "$slot_id" --module="$LIB" --login --pin "$pin" --delete-object --type pubkey --id 01
fi
else
echo "No Token exists"
Expand All @@ -131,9 +190,9 @@ key_generation()
#generate keys
echo "Generating new keys"
#pkcs11-tool --keypairgen --key-type="RSA:4096" --login --pin=$pin --module=$LIB --label=$LABEL --id=01
pkcs11-tool --keypairgen --key-type="EC:prime256v1" --login --pin="$pin" --module="$LIB" --label="$LABEL" --id=01 #for EC
pkcs11-tool --slot "$slot_id" --keypairgen --key-type="EC:prime256v1" --login --pin="$pin" --module="$LIB" --label="$LABEL" --id=01 #for EC
#export to der
pkcs11-tool --read-object --id 01 --type pubkey --module="$LIB" --output-file /etc/ssl/certs/mesh_cert.der
pkcs11-tool --slot "$slot_id" --read-object --id 01 --type pubkey --module="$LIB" --output-file /etc/ssl/certs/mesh_cert.der
}

export_pin()
Expand All @@ -157,24 +216,36 @@ create_csr(){

SUBJ="/C=AE/ST=Abu Dhabi/L=Abu Dhabi/O=TII/OU=SSRC/CN=*.tii.ae"


export OPENSSL_PIN="$pin"
openssl req -new -x509 -days 365 -subj "$SUBJ" -sha256 -engine pkcs11 -keyform engine -key 01 -passin env:OPENSSL_PIN -out cert.pem
echo "Certificate Signing Request (CSR)"
openssl req -new -engine pkcs11 -keyform engine -key 01 -passin env:OPENSSL_PIN -out /opt/mycsr.csr -subj "$SUBJ"
openssl x509 -req -CAkeyform engine -engine pkcs11 -in /opt/mycsr.csr -CA cert.pem -CAkey 01 -set_serial 1 -sha256 -passin env:OPENSSL_PIN -out /opt/mycert.pem # self-signed cerificate
echo "self-signed certificate"
openssl x509 -in /opt/mycert.pem -noout -text -passin env:OPENSSL_PIN
# Create "ca" certificate
openssl req -new -x509 -days 365 -subj "$SUBJ" -sha256 -engine pkcs11 -keyform engine -key "pkcs11:token=$token_label;object=$LABEL" -passin env:OPENSSL_PIN -out cert.pem

# Create CSR
echo "Certificate Signing Request (CSR)"
openssl req -new -engine pkcs11 -keyform engine -key "pkcs11:token=$token_label;object=$LABEL" -passin env:OPENSSL_PIN -out /opt/mycsr.csr -subj "$SUBJ"
# Sign the CSR with ca certificate.
openssl x509 -req -CAkeyform engine -engine pkcs11 -in /opt/mycsr.csr -CA cert.pem -CAkey "pkcs11:token=$token_label;object=$LABEL" -set_serial 1 -sha256 -passin env:OPENSSL_PIN -out /opt/mycert.pem # self-signed cerificate

echo "Self-signed certificate properties:"
openssl x509 -in /opt/mycert.pem -noout -text -passin env:OPENSSL_PIN
}


initialize_hsm
initialize_all
#hard_delete
soft_delete
key_generation
export_pin
create_csr
set_openssl_env
get_slot_id_by_token_label
if [[ -z "$slot_id" ]]; then
get_next_free_slot_id
# Create new token in case one didn't exist already
create_and_init_token
# Get slot id
get_slot_id_by_token_label
set_user_pin
key_generation
fi
if [[ -n "$slot_id" ]]; then
#hard_delete
#soft_delete
export_pin
create_csr
fi

24 changes: 24 additions & 0 deletions common/scripts/mesh-helper.sh
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,27 @@ source_configuration() {
exit 1
fi
}

install_python_packages() {
# install the python packages
MESH_FOLDER="/opt/mesh_com"
if [ -d "$MESH_FOLDER/modules/utils/package/python_packages" ]; then
echo "Directory $MESH_FOLDER/modules/utils/package/python_packages exists."
else
#!/bin/bash
tar -C $MESH_FOLDER/modules/utils/package/ -zxvf $MESH_FOLDER/modules/utils/package/python_packages.tar.gz
cd $MESH_FOLDER/modules/utils/package/python_packages || return

for f in {*.whl,*.gz};
do
name="$(echo "$f" | cut -d"-" -f1)"
if python -c 'import pkgutil; exit(not pkgutil.find_loader("$name"))'; then
echo "$name" "installed"
else
echo "$name" "not found"
echo "installing" "$name"
pip install --no-index "$f" --find-links .;
fi
done
fi
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ server:
mode: "mesh" # mesh=mesh network, ap=debug hotspot
type: "11s" # 11s or ibss
ip: 10.10.10.4 # Mesh IP address
bridge: False # Create bridge if true
meshint: 'bat0' # 'br-lan' if bridge is created, 'bat0' otherwise
bridge: True # Create bridge if true
meshint: 'br-lan' # 'br-lan' if bridge is created, 'bat0' otherwise
concurrency: "" # mode
mcc_channel: "" # mcc channel
6 changes: 3 additions & 3 deletions modules/sc-mesh-secure-deployment/src/1_5/features.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
only_mesh: false
NESS: false
continuous: false
mutual: true
continuous: true
mutual: false
secbeat: true
quarantine: false
mesh: true
mesh: false
provisioning: false
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@

mid = hashlib.blake2b(util.get_mac_by_interface('wlp1s0').encode(), digest_size=4).hexdigest()

# Dirty global:
slot = "0"


def recover_pin():
try:
with open('/opt/output.txt') as file:
Expand All @@ -58,14 +62,17 @@ def recover_pin():
def get_session():
pkcs11 = PyKCS11Lib()
pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib
slot = pkcs11.getSlotList(tokenPresent=True)[0]
try:
session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login(recover_pin())
return session
except PyKCS11Error:
print('No previous keys')
return False
slots = pkcs11.getSlotList(tokenPresent=True)
for _slot in slots:
try:
session = pkcs11.openSession(_slot, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login(recover_pin())
global slot
slot = str(_slot)
return session
except PyKCS11Error:
print('No previous keys')
return False
# get 1st slot


Expand All @@ -84,7 +91,7 @@ def derive_ecdh_secret(node_name, client_mesh_name):
pubKey_filename = f'pubKeys/{client_mesh_name}.der' # when called from cont auth, node_name = '', select public key from pubKeys/client_mesh_name.der Eg. pubKeys/10_10_10_4.der
else:
pubKey_filename = f'{node_name}.der' # when called from mutual, node_name != '', select public key from node_name.der
command = ['pkcs11-tool', '--module', LIB, '-l', '--pin', recover_pin(), '--label', myID, '--derive', '-i', pubKey_filename, '--mechanism', 'ECDH1-DERIVE']
command = ['pkcs11-tool', '--slot', slot, '--module', LIB, '-l', '--pin', recover_pin(), '--label', myID, '--derive', '-i', pubKey_filename, '--mechanism', 'ECDH1-DERIVE']
# Output of ecdh derive is the secret byte + b'Using derive algorithm 0x00001050 ECDH1-DERIVE\n'
# Extracting the secret byte
secret_byte = subprocess.check_output(command, shell=False).rstrip(b'Using derive algorithm 0x00001050 ECDH1-DERIVE\n')
Expand Down Expand Up @@ -165,7 +172,7 @@ def delete_key(node_name): # check if it is possible to delete on python (destr
aux = keys[key].to_dict()
k.append(aux)
for _ in k:
command = ['pkcs11-tool', '--module', LIB, '--delete-object', label, '--type=pubkey']
command = ['pkcs11-tool', '--slot', slot, '--module', LIB, '--delete-object', label, '--type=pubkey']
subprocess.call(command, shell=False)


Expand Down Expand Up @@ -197,7 +204,7 @@ def import_cert(client_key, node_name):
except AttributeError:
with open(filename, 'wb') as writer:
writer.write(client_key)
command = ['pkcs11-tool', '--module', LIB, '-l', '--pin', recover_pin(), '--write-object', filename, '--type',
command = ['pkcs11-tool', '--slot', slot, '--module', LIB, '-l', '--pin', recover_pin(), '--write-object', filename, '--type',
'pubkey', '--id', ID, '--label', node_name]
subprocess.call(command, shell=False)

Expand Down
7 changes: 4 additions & 3 deletions modules/sc-mesh-secure-deployment/src/1_5/main_with_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,10 @@ def CA():
os.system('clear')
print('\'Continuous Authentication\'')
sectable = pd.read_csv('auth/dev.csv')
if not mesh_utils.verify_mesh_status(): # verifying that mesh is running
print("Mesh network not established")
only_mesh()
# if not mesh_utils.verify_mesh_status(): # verifying that mesh is running
# print("Mesh network not established")
# only_mesh()
# added from only_mesh()
return only_ca(myID)


Expand Down
61 changes: 61 additions & 0 deletions modules/sc-mesh-secure-deployment/src/nats/initd/S90MS15
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: S90MS15
# Should-Start: $syslog
# Should-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start S90MS15 Mesh Shield 1.5
# Description: start S90MS15 Mesh Shield 1.5 beside other services
#
### END INIT INFO

DAEMON="main.py"
DIR="/opt/"
PIDFILE="/var/run/{$DAEMON}_ms15.pid"
LOG_FILE=/opt/mesh_shield_1.5.log

# shellcheck source=/dev/null
[ -r "/etc/default/$DAEMON" ] && . "/etc/default/$DAEMON"

start() {
printf 'Starting %s: ' "$DAEMON"
start-stop-daemon -b -m -S -q -p "$PIDFILE" -a /bin/bash -- -c "exec python $DIR$DAEMON \
$ARGS > $LOG_FILE 2>&1"
status=$?
if [ "$status" -eq 0 ]; then
echo "OK"
else
echo "FAIL"
fi
return "$status"
}
stop() {
printf 'Stopping %s: ' "$DAEMON"
start-stop-daemon -K -q -p "$PIDFILE"
status=$?
if [ "$status" -eq 0 ]; then
rm -f "$PIDFILE"
echo "OK"
else
echo "FAIL"
fi
return "$status"
}
restart() {
stop
sleep 1
start
}
case "$1" in
start|stop|restart)
"$1";;
reload)
# Restart, since there is no true "reload" feature.
restart;;
*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 1
esac

exit 0
Loading
Loading