shared_secret_maintainer.pl 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #!/usr/bin/perl
  2. #
  3. # This is an example of Perl script maintaining dynamic shared secret
  4. # database for the REST API
  5. #
  6. use strict;
  7. use warnings;
  8. use DBI;
  9. use HTTP::Request::Common;
  10. my $DBNAME="turn";
  11. my $DBUSERNAME="turn";
  12. my $DBPWD="turn";
  13. my $DBHOST="localhost";
  14. my $webserver = 'http://example.com/';
  15. my $old_secret = "";
  16. my $current_secret="";
  17. my $INTERVAL=3600;
  18. my $dbh;
  19. $dbh = DBI->connect("DBI:mysql:$DBNAME;host=$DBHOST", $DBUSERNAME, $DBPWD)
  20. || die "Could not connect to database: $DBI::errstr";
  21. $dbh->do('CREATE TABLE IF NOT EXISTS turn_secret (value varchar(512))');
  22. my $c = $dbh->do("delete from turn_secret");
  23. print "Deleted $c rows\n";
  24. $dbh->disconnect();
  25. do {
  26. $dbh = DBI->connect("DBI:mysql:$DBNAME;host=$DBHOST", $DBUSERNAME, $DBPWD)
  27. || die "Could not connect to database: $DBI::errstr";
  28. $dbh->do('CREATE TABLE IF NOT EXISTS turn_secret (value varchar(512))');
  29. if(length($current_secret)) {
  30. if(length($old_secret)) {
  31. remove_secret($dbh, $old_secret);
  32. }
  33. $old_secret=$current_secret;
  34. }
  35. print "CURRENT SECRET TO BE (RE)GENERATED\n";
  36. $current_secret = generate_secret();
  37. insert_secret($dbh, $current_secret);
  38. $dbh->disconnect();
  39. #
  40. # Web server interaction example:
  41. # Here we can put code to submit this secret to the web server:
  42. #
  43. my $req = POST($webserver, Content => [param => $current_secret]);
  44. $req->method('PUT');
  45. print $req->as_string,"\n";
  46. #
  47. # Alternatively, you can use this link for compute-on-demand:
  48. # https://github.com/alfreddatakillen/computeengineondemand
  49. #
  50. # write your code here.
  51. #
  52. sleep($INTERVAL);
  53. } while(1);
  54. sub remove_secret {
  55. my $dbh = shift;
  56. my $secret=shift;
  57. my $c = $dbh->do("delete from turn_secret where value = '$secret'");
  58. print "Deleted $c rows\n";
  59. }
  60. sub insert_secret {
  61. my $dbh = shift;
  62. my $secret=shift;
  63. my $c = $dbh->do("insert into turn_secret values('$secret')");
  64. print "Inserted $c rows\n";
  65. }
  66. sub generate_secret {
  67. my @chars = ('0'..'9', 'A'..'F');
  68. my $len = 8;
  69. my $string;
  70. while($len--){ $string .= $chars[rand @chars] };
  71. return $string;
  72. }