9.19.2007

write/retrieve from shmem, encrypt/decrypt string

# Here's the code to create a shmem seg, and write to it.
A -r switch deletes the segment:


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

#include <sys/ipc.h>
#include <sys/shm.h>

int main(int argc, char* argv[]) {

key_t key ;
int shmid ;
int rtrn ;

/* create a key, using ftok, and this file :) */

key = ftok(argv[0], '0');
if (argc > 1) {

while ((argc > 1) && (argv[1][0] == '-')) {

if (argv[1][0] == '-') {

switch (argv[1][1]) {
case 'r':
/*connect to the shared mem seg, 1k, mode 0600*/

shmid = shmget(key, 1024, 0600);
rtrn = shmctl(shmid, IPC_RMID , (struct shmid_ds *) NULL);

exit(rtrn);
break;
default:
perror("unknown option");

exit(1);
}
}
else {

perror("unknown argument");
exit(1);
}

++argv;
--argc;
}

}

else {
char *data, *s;

/*create the shared mem seg, 1k, mode 0600*/

if ((shmid=shmget(key, 1024, 0600 | IPC_CREAT)) < 0) {

perror("shmget");
exit(1);
}

/* Attach the segment to our data space */
if ((data = shmat(shmid, (void *)0, 0)) == (char *) -1) {

perror("shmat");
exit(1);
}

char *cmd= "/usr/local/bin/md5 /bin/sh | cut -d= -f2 |cut -d' ' -f2";
char buf[BUFSIZ];

FILE *ptr;
if ((ptr = popen(cmd, "r")) != NULL) {
fgets(buf, BUFSIZ, ptr);

(void) pclose(ptr);
}

strncpy(data, buf, 1024);
if (shmdt(data) == -1) {

perror("shmdt");
exit(1);
}

return 0;
}
}


# Here's the code to attach to the segment and read the data:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main(){
key_t key ;

/* get the key, using ftok, and a readable file */
key = ftok("/opt/scripts/seed_shmem", '0');
/*connect to the shared mem seg, 1k, mode 0600*/

int shmid ;
shmid = shmget(key, 1024, 0600);

/* Attach the segment to our data space */
char *data ;
if ((data = shmat(shmid, (void *)0, 0)) == (char *) -1) {

perror("shmat");
exit(1);
}

printf("%s", data);
}

# Here's a perl script to encrypt a string using the seed:


use Crypt::CBC;
my
$keystring;
chomp($keystring=`/opt/scripts/script_data/.read_rnd`);

$keylength = length $keystring ;

my
$template = "H" . $keylength ;
my
$cipher = new Crypt::CBC ({
key =>
pack($template, $keystring),
cipher =>
'DES', });

my
$string = $ARGV[0] ;
my
$ciphertext = $cipher->encrypt($string);

open (TMP, ">/opt/scripts/script_data/account_delete.pl/.data");
print TMP $ciphertext ;
close TMP;
`
chmod 400 /tmp/crypto`

# And, here's a perl script to decrypt the string

use Crypt::CBC;
my
$keystring;
chomp($keystring=`/opt/scripts/script_data/.read_rnd`);

$keylength = length $keystring ;
my
$template = "H" . $keylength ;
my
$cipher = new Crypt::CBC ({
key =>
pack($template, $keystring),
cipher =>
'DES', });

my
$cleartext;
open (TMP, "</opt/scripts/script_data/account_delete.pl/.data");
while
(<TMP>) {
$cleartext = $cipher->decrypt($_);
}
close TMP;
print $cleartext, "\n";
`
/opt/scripts/seed_shmem -r`;