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
|
#!/usr/bin/perl
#
# This is an example of Perl script maintaining dynamic shared secret
# database for the REST API
#
use strict;
use warnings;
use DBI;
use HTTP::Request::Common;
my $DBNAME="turn";
my $DBUSERNAME="turn";
my $DBPWD="turn";
my $DBHOST="localhost";
my $webserver = 'http://example.com/';
my $old_secret = "";
my $current_secret="";
my $INTERVAL=3600;
my $dbh;
$dbh = DBI->connect("DBI:mysql:$DBNAME;host=$DBHOST", $DBUSERNAME, $DBPWD)
|| die "Could not connect to database: $DBI::errstr";
$dbh->do('CREATE TABLE IF NOT EXISTS turn_secret (value varchar(512))');
my $c = $dbh->do("delete from turn_secret");
print "Deleted $c rows\n";
$dbh->disconnect();
do {
$dbh = DBI->connect("DBI:mysql:$DBNAME;host=$DBHOST", $DBUSERNAME, $DBPWD)
|| die "Could not connect to database: $DBI::errstr";
$dbh->do('CREATE TABLE IF NOT EXISTS turn_secret (value varchar(512))');
if(length($current_secret)) {
if(length($old_secret)) {
remove_secret($dbh, $old_secret);
}
$old_secret=$current_secret;
}
print "CURRENT SECRET TO BE (RE)GENERATED\n";
$current_secret = generate_secret();
insert_secret($dbh, $current_secret);
$dbh->disconnect();
#
# Web server interaction example:
# Here we can put code to submit this secret to the web server:
#
my $req = POST($webserver, Content => [param => $current_secret]);
$req->method('PUT');
print $req->as_string,"\n";
#
# Alternatively, you can use this link for compute-on-demand:
# https://github.com/alfreddatakillen/computeengineondemand
#
# write your code here.
#
sleep($INTERVAL);
} while(1);
sub remove_secret {
my $dbh = shift;
my $secret=shift;
my $c = $dbh->do("delete from turn_secret where value = '$secret'");
print "Deleted $c rows\n";
}
sub insert_secret {
my $dbh = shift;
my $secret=shift;
my $c = $dbh->do("insert into turn_secret values('$secret')");
print "Inserted $c rows\n";
}
sub generate_secret {
my @chars = ('0'..'9', 'A'..'F');
my $len = 8;
my $string;
while($len--){ $string .= $chars[rand @chars] };
return $string;
}
|