GeniCertificate.pm.in 22.1 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
#!/usr/bin/perl -wT
#
3
# GENIPUBLIC-COPYRIGHT
4
# Copyright (c) 2008-2011 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# All rights reserved.
#
package GeniCertificate;

#
# Some simple certificate stuff.
#
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
use GeniDB;
21
use GeniResponse;
22
use emutil qw(TBGetUniqueIndex);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
23
24
25
26
27
use English;
use XML::Simple;
use XML::LibXML;
use Data::Dumper;
use File::Temp qw(tempfile);
28
use overload ('""' => 'Stringify');
Leigh B. Stoller's avatar
Leigh B. Stoller committed
29
30
31
32
33
34
35
36
37
38
39
40

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
my $SIGNCRED	   = "$TB/sbin/signgenicred";
my $VERIFYCRED	   = "$TB/sbin/verifygenicred";
my $NFREE	   = "$TB/bin/nfree";
my $OPENSSL	   = "/usr/bin/openssl";
41
my $SHA1	   = "/sbin/sha1";
42
43
44
45
my $MKCERT         = "$TB/sbin/mksyscert";

# Cache of instances to avoid regenerating them.
my %certificates  = ();
46
BEGIN { use GeniUtil; GeniUtil::AddCache(\%certificates); }
47
48

#
49
# Lookup by URN (and also UUID, for compatibility).
50
51
52
53
54
#
sub Lookup($$)
{
    my ($class, $token) = @_;
    my $query_result;
55
    my $uuid;
56
57
58
59
60

    # Look in cache first
    return $certificates{"$token"}
        if (exists($certificates{"$token"}));

61
62
63
64
    if (GeniHRN::IsValid($token)) {
	$query_result =
	    DBQueryWarn("select uuid from geni_certificates ".
			"where urn='$token'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
65
66
67
68
69
70

	return undef
	    if (! ($query_result && $query_result->numrows));
	
	($uuid) = $query_result->fetchrow_array();
	
Leigh B. Stoller's avatar
Leigh B. Stoller committed
71
72
    }
    elsif ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
73
74
	$uuid = $token;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
75
76
77
    else {
	return undef;
    }
78

79
    $query_result =
80
	DBQueryWarn("select * from geni_certificates where uuid='$uuid'");
81
82
83
84
    
    return undef
	if (!$query_result || !$query_result->numrows);

85
86
87
    my $self          = {};
    $self->{'CERT'}   = $query_result->fetchrow_hashref();
    $self->{'stored'} = 1;
88
    bless($self, $class);
89
    my $cert = $self->cert();
90
91

    # Add to cache. 
92
93
94
    $certificates{$uuid} = $self;
    $certificates{$token} = $self
	if $token ne $uuid;
95
96
97
98
99
100
101
102
103
104
105
106
    
    return $self;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uuid = $self->uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
107
    my $hrn  = $self->hrn();
108

Leigh B. Stoller's avatar
Leigh B. Stoller committed
109
    return "[GeniCertificate: $uuid, $hrn]";
110
111
112
113
114
}

# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'CERT'}->{$_[1]}); }
sub uuid($)		{ return field($_[0], "uuid"); }
115
116
# This will always be undefined, but we need the method.
sub expires($)		{ return undef; }
117
118
sub created($)		{ return field($_[0], "created"); }
sub cert($)		{ return field($_[0], "cert"); }
119
sub DN($)		{ return field($_[0], "DN"); }
120
121
sub privkey($)		{ return field($_[0], "privkey"); }
sub revoked($)		{ return field($_[0], "revoked"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
122
sub certfile($)		{ return field($_[0], "certfile"); }
123
sub uri($)              { return field($_[0], "uri"); }
124
sub urn($)              { return field($_[0], "urn"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
125
sub GetCertificate($)   { return $_[0]; }
126

127
128
129
# Kludge for SFA certs.
sub setuuid($$)		{ return $_[0]->{'CERT'}->{'uuid'} = $_[1]; }

130
131
132
133
134
135
136
137
138
139
140
#
# The fields are buried inside the DN.
#
sub hrn($)
{
    my ($self) = @_;

    if ($self->DN() =~ /\/OU=([-\w\.]+)\//) {
	return $1
	    if ($1 ne "");
    }
141
142
143
    # GENI AM compatibility with PlanetLab
    # Use the URN from the Subject Alt Name to create the HRN
    my ($authority, $type, $name) = GeniHRN::Parse($self->urn());
144
145
146
147
    # Substitute dots for colons
    $authority =~ s/:/\./g;
    my $hrn = $authority . "." . $name;
    return $hrn;
148
149
150
151
152
}
sub email($)
{
    my ($self) = @_;

153
154
    if ($self->DN() =~ /\/emailAddress=(.*)/ ||
	$self->DN() =~ /^emailAddress=(.*),/) {
155
156
157
158
159
160
161
	return $1
	    if ($1 ne "");
    }
    print STDERR "Cannot find email inside DN: '" . $self->DN() . "'\n";
    return "unknown";
}

162
163
164
#
# Create a certificate pair, which gives us a uuid to use for an object.
#
165
sub Create($$;$)
166
{
167
168
169
170
171
172
173
    my ($class, $argref, $error) = @_;
    my $urn   = (exists($argref->{'urn'})   ? $argref->{'urn'}   : undef);
    my $hrn   = (exists($argref->{'hrn'})   ? $argref->{'hrn'}   : undef);
    my $email = (exists($argref->{'email'}) ? $argref->{'email'} : undef);
    my $uuid  = (exists($argref->{'uuid'})  ? $argref->{'uuid'}  : undef);
    my $url   = (exists($argref->{'url'})   ? $argref->{'url'}   : undef);

174
175
176
    # Let mkcert generate a new one.
    $uuid = ""
	if (!defined($uuid));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
177
    $url  = (defined($url) ? "-u $url" : "");
178

179
    if (! open(CERT, "$MKCERT -i \"$urn\" $url -e \"$email\" $hrn $uuid |")) {
180
181
182
183
184
185
186
187
	print STDERR "Could not start $MKCERT\n";
	return undef;
    }
    my @certlines = ();
    while (<CERT>) {
	push(@certlines, $_);
    }
    if (!close(CERT)) {
188
	print STDERR "$MKCERT failed!\n";
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
	return undef;
    }
    my $cert;
    my $privkey;
    my $string;
    foreach my $line (@certlines) {
	if ($line =~ /^-----BEGIN CERT/ ||
	    $line =~ /^-----BEGIN RSA/) {
	    $string = "";
	    next;
	}
	if ($line =~ /^-----END CERT/) {
	    $cert = $string;
	    $string = undef;
	    next;
	}
	if ($line =~ /^-----END RSA/) {
	    $privkey = $string;
	    $string = undef;
	    next;
	}
	$string .= $line
	    if (defined($string));
    }
    if (! (defined($privkey) && defined($cert))) {
	print STDERR "Could not generate a new certificate with $MKCERT\n";
215
216
217
	foreach my $line (@certlines) {
	    print STDERR $line;
	}
218
219
220
221
	return undef;
    }
    if (! ($cert =~ /^[\012\015\040-\176]*$/)) {
	print STDERR "Improper chars in certificate string\n";
222
223
224
	foreach my $line (@certlines) {
	    print STDERR $line;
	}
225
226
	return undef;
    }
227
228

    my $certificate = GeniCertificate->LoadFromString($cert);
229
    return undef
230
	if (!defined($certificate));
231

232
    $certificate->{'CERT'}->{'privkey'} = $privkey;
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    #
    # We need to be sure this certificate is unique, so do a table
    # lock and check before calling Store.
    #
    DBQueryWarn("lock tables geni_certificates write")
	or return undef;
    $uuid = $certificate->uuid();
    my $query_result =
	DBQueryWarn("select urn from geni_certificates where uuid='$uuid'");
    goto bad
	if (!$query_result);
    if ($query_result->numrows) {
	my ($ourn) = $query_result->fetchrow_array();
	print STDERR "*** Duplicate uuid in geni_certificates table\n";
	print STDERR "*** $uuid,$urn : $ourn\n";
248
249
250
251
252
253
254
255
256
257
258
259
260
261
	$$error = GENIRESPONSE_UNAVAILABLE
	    if (defined($error));
	goto bad;
    }
    $query_result =
	DBQueryWarn("select uuid from geni_certificates where urn='$urn'");
    goto bad
	if (!$query_result);
    if ($query_result->numrows) {
	my ($ouuid) = $query_result->fetchrow_array();
	print STDERR "*** Duplicate urn in geni_certificates table\n";
	print STDERR "*** $uuid,$urn : $ouuid\n";
	$$error = GENIRESPONSE_UNAVAILABLE
	    if (defined($error));
262
	goto bad;
263
    }
264
265
    if ($certificate->Store() != 0) {
	print STDERR "Could not write new certificate to DB\n";
266
	goto bad;
267
    }
268
    DBQueryWarn("unlock tables");
269
    return $certificate;
270
271
272
  bad:
    DBQueryWarn("unlock tables");
    return undef;
273
274
275
276
277
278
279
280
281
282
283
}

#
# Delete ...
#
sub Delete($)
{
    my ($self) = @_;
    my $uuid = $self->uuid();

    return -1
284
285
	if ($self->{'stored'} &&
	    !DBQueryWarn("delete from geni_certificates where uuid='$uuid'"));
286

287
288
289
    # Delete from cache. 
    delete($certificates{$uuid});

290
291
292
    return 0;
}

293
294
295
296
297
298
299
#
# Flush from our little cache.
#
sub Flush($)
{
    my ($self) = @_;

Leigh B Stoller's avatar
Leigh B Stoller committed
300
301
302
303
    # Just in case we get something else.
    $self->GetCertificate()->Flush()
	if (ref($self) ne "GeniCertificate");

304
305
306
    delete($certificates{$self->uuid()});
}

307
308
309
310
311
312
313
314
315
316
#
# Compare two certs.
#
sub SameCert($$)
{
    my ($self, $other) = @_;

    return $self->GetCertificate()->cert() eq $other->GetCertificate()->cert();
}

317
#
318
319
# Load a certificate from a string. This creates an object, but does
# not store it in the DB.
320
#
321
sub LoadFromString($$)
322
{
323
    my ($class, $string) = @_;
324

325
    if (! ($string =~ /^[\012\015\040-\176]*$/)) {
326
327
328
	print STDERR "Improper chars in certificate string\n";
	return undef;
    }
329
330
331
332
333
334
    require Socket;
    import Socket qw(:DEFAULT);
    require IO::Handle;     # thousands of lines just for autoflush :-(
    
    if (! socketpair(CHILD, PARENT, AF_UNIX(), SOCK_STREAM(), PF_UNSPEC())) {
	print STDERR "LoadFromString: Could not create socketpair\n";
335
336
	return undef;
    }
337
338
339
340
341
342
    CHILD->autoflush(1);
    PARENT->autoflush(1);

    my $childpid = fork();
    if (! $childpid) {
	close CHILD;
343

344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
	#
	# Dup our descriptors to the parent, and exec the program.
	# The parent then talks to it read/write.
	#
	open(STDIN,  "<&PARENT") || die "Cannot redirect stdin";
	open(STDOUT, ">&PARENT") || die "Cannot redirect stdout";
	open(STDERR, ">&PARENT") || die "Cannot redirect stderr";

	exec("$OPENSSL x509 -subject -text");
	die("*** $0:\n".
	    "    exec openssl x509 failed: $!\n");
    }
    close PARENT;

    #
    # Write the certificate to the child.
    #
361
362
    # The certificate might already have the header and footer
    # so only add them if needed.
363
    #
364
    if ($string =~ /^-----BEGIN CERTIFICATE-----/) {
365
        print CHILD $string;
366
    }
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
    else {
        print CHILD "-----BEGIN CERTIFICATE-----\n";
        print CHILD $string;
        print CHILD "\n" if $string !~ /\n$/;
        print CHILD "-----END CERTIFICATE-----\n";
    }
    # Tell the process we are done writing. ie: Send it an EOF.
    shutdown(CHILD,1);
    
    my @certlines = ();
    while (<CHILD>) {
	push(@certlines, $_);
    }
    close(CHILD);
    waitpid($childpid, 0);
    if ($? || !@certlines) {
	print STDERR "openssl x509 failed to parse certificate\n";
	return undef;
    }
    my $certificate = GeniCertificate->LoadFromArray(@certlines);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
387
388
389
    return undef
	if (!defined($certificate));
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
390
    $certificate->{'CERT'}->{'certfile'} = undef;
391
    return $certificate;
392
393
394
}

#
395
396
# Load a certificate from a file. This creates an object, but does
# not store it in the DB.
397
#
398
sub LoadFromFile($$)
399
{
400
    my ($class, $filename) = @_;
401

402
    if (! open(X509, "$OPENSSL x509 -in $filename -subject -text |")) {
403
404
	print STDERR "Could not start $OPENSSL on $filename\n";
	return undef;
405
    }
406
407
408
409
410
411
412
413
    my @certlines = ();
    while (<X509>) {
	push(@certlines, $_);
    }
    if (!close(X509) || !@certlines) {
	print STDERR "Could not load certificate from $filename\n";
	return undef;
    }
414
415
416
417
418
419
420
    my $certificate = GeniCertificate->LoadFromArray(@certlines);
    return undef
	if (!defined($certificate));
    
    $certificate->{'CERT'}->{'certfile'} = $filename;
    return $certificate;
}
421

422
423
424
425
426
427
428
sub LoadFromArray($@)
{
    my $class = shift();
    my @certlines = @_;
    my $url;
    my $urn;
    
429
430
431
432
433
434
435
    #
    # The first line is the DN (subject).
    #
    my $DN = shift(@certlines);
    chomp($DN);

    #
436
437
438
    # The text output is next. Look for the URL in the extensions. Stop
    # when we get to the certificate line.
    #
439
440
441
    my ($alturi,$accessuri);
    my $altname = 0;
    my $accessinfo = 0;
442
443
444
445
446
    while (@certlines) {
	my $line = shift(@certlines);
	last
	    if ($line =~ /^-----BEGIN CERT/);

447
448
449
450
451
	if( $line =~ /^\s+X509v3 Subject Alternative Name:\s*$/ ) {
	    $altname = 1;
	} elsif( $line =~ /^\s+Authority Information Access:\s*$/ ) {
	    $accessinfo = 1;
	} elsif( $altname ) {
452
	    m'^\s*URI:(urn:publicid:[-!#$%()*+,./0-9:;=?@A-Z_a-z~]+)\s*$' and $alturi = $1
453
454
455
456
457
458
		foreach split( /, /, $line );
	    $altname = 0;
	} elsif( $accessinfo ) {
	    m'^\s*[0-9.]+ - URI:([-!#$%()*+,./0-9:;=?@A-Z_a-z~]+)\s*$' 
		and $accessuri = $1 foreach split( /, /, $line );
	    $accessinfo = 0;
459
460
461
	}
    }
    if (!@certlines) {
462
	print STDERR "Could not parse certificate!\n";
463
464
465
	return undef;
    }

466
467
468
469
470
471
472
473
474
475
    if( defined( $alturi ) && $alturi =~ /^urn:/ ) {
	$urn = $alturi;
    }

    if( defined( $accessuri ) ) {
	$url = $accessuri;
    } elsif( defined( $alturi ) && $alturi !~ /^urn:/ ) {
	$url = $alturi;
    }

476
477
    #
    # Throw away last line; the cert is rest.
478
479
480
    #
    pop(@certlines);
    my $cert = join("", @certlines);
481

482
    # Dig out the uuid.
483
484
485
486
487
    #
    # The uuid that PLC puts in the certificate is not associated with the
    # underlying object, so it is not useful to us. We end up generating
    # one below.
    #
488
489
490
    my $uuid;
    if ($DN =~ /\/CN=([-\w]*)/) {
	$uuid = $1;
491
492
    }
    else {
493
494
	print STDERR "Could not find uuid in 'DN'\n";
	return undef;
495
    }
496
    
497
498
499
500
501
502
    # GENI AM: CN might not be a UUID, so check it.
    # If it is not a UUID, make one up.
    if ($uuid !~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
        $uuid = GeniUtil::NewUUID();
    }

503
504
505
506
507
508
509
510
511
512
513
    my $self          = {};
    $self->{'CERT'}   = {};
    $self->{'stored'} = 0;
    bless($self, $class);

    $self->{'CERT'}->{'uuid'}      = $uuid;
    $self->{'CERT'}->{'cert'}      = $cert;
    $self->{'CERT'}->{'DN'}        = $DN;
    $self->{'CERT'}->{'privkey'}   = undef;
    $self->{'CERT'}->{'revoked'}   = undef;
    $self->{'CERT'}->{'created'}   = undef;
514
    $self->{'CERT'}->{'uri'}       = $url;
515
    $self->{'CERT'}->{'urn'}       = $urn;
516
    return $self;
517
518
}

519
520
521
522
523
524
525
526
#
# Pipe a certificate (and maybe key) to a command and read back results
# for the caller. 
#
sub PipeTo($$$)
{
    my ($self, $withkey, $string) = @_;

Leigh B Stoller's avatar
Leigh B Stoller committed
527
#    print STDERR "PipeTo: $self, '$string'\n";
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584

    require Socket;
    import Socket qw(:DEFAULT);
    require IO::Handle;     # thousands of lines just for autoflush :-(
    
    if (! socketpair(CHILD, PARENT, AF_UNIX(), SOCK_STREAM(), PF_UNSPEC())) {
	print STDERR "*** PipeTo: Could not create socketpair\n";
	return undef;
    }
    CHILD->autoflush(1);
    PARENT->autoflush(1);

    my $childpid = fork();
    if (! $childpid) {
	close CHILD;

	#
	# Dup our descriptors to the parent, and exec the program.
	# The parent then talks to it read/write.
	#
	open(STDIN,  "<&PARENT") || die "Cannot redirect stdin";
	open(STDOUT, ">&PARENT") || die "Cannot redirect stdout";
	open(STDERR, ">&PARENT") || die "Cannot redirect stderr";

	exec($string);
	die("*** $0:\n".
	    "    exec '$string' failed: $!\n");
    }
    close PARENT;

    #
    # Write the certificate to the child.
    #
    print CHILD "-----BEGIN CERTIFICATE-----\n";
    print CHILD $self->cert();
    print CHILD "-----END CERTIFICATE-----\n";
    if ($withkey && $self->privkey()) {
	print CHILD "-----BEGIN RSA PRIVATE KEY-----\n";
	print CHILD $self->privkey();
	print CHILD "-----END RSA PRIVATE KEY-----\n";
    }
    # Tell the process we are done writing. ie: Send it an EOF.
    shutdown(CHILD,1);
    
    my @certlines = ();
    while (<CHILD>) {
	push(@certlines, $_);
    }
    close(CHILD);
    waitpid($childpid, 0);
    if ($? || !@certlines) {
	print STDERR "*** Failed to parse certificate: '$string'\n";
	return undef;
    }
    return @certlines;
}

585
#
586
# Store a certificate that was loaded from a string/file.
587
#
588
sub Store($)
589
{
590
    my ($self) = @_;
591
592

    return 0
593
594
595
596
597
598
599
600
601
	if ($self->{'stored'});

    my @inserts = ();
    push(@inserts, "created=now()");
    push(@inserts, "uuid=" . DBQuoteSpecial($self->uuid()));
    push(@inserts, "cert=" . DBQuoteSpecial($self->cert()));
    push(@inserts, "DN=" . DBQuoteSpecial($self->DN()));
    push(@inserts, "privkey=" . DBQuoteSpecial($self->privkey()))
	if (defined($self->privkey()));
602
603
    push(@inserts, "uri=" . DBQuoteSpecial($self->uri()))
	if (defined($self->uri()));
604
605
    push(@inserts, "urn=" . DBQuoteSpecial($self->urn()))
	if (defined($self->urn()));
606
607
608
609

    return -1
	if (!DBQueryWarn("replace into geni_certificates set ".
			 join(",", @inserts)));
610
    
611
    $self->{'stored'} = 1;
612
613
614
    return 0;
}

615
616
617
#
# Write a certificate and private key to a tempfile, as for signing with it.
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
618
sub WriteToFile($;$)
619
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
620
621
622
623
    my ($self, $withkey) = @_;

    $withkey = 0
	if (!defined($withkey));
624
625
626
627
628
629
    
    # We want this file to be passed back. 
    my ($tempfile, $filename) = tempfile(UNLINK => 1);
    print $tempfile "-----BEGIN CERTIFICATE-----\n";
    print $tempfile $self->cert();
    print $tempfile "-----END CERTIFICATE-----\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
630
    if ($withkey && $self->privkey()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
631
632
633
634
	print $tempfile "-----BEGIN RSA PRIVATE KEY-----\n";
	print $tempfile $self->privkey();
	print $tempfile "-----END RSA PRIVATE KEY-----\n";
    }
635
636
637
    return $filename;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
638
639
640
641
642
643
#
# The URL is buried in an extension so we have to parse the text output.
#
sub URL($)
{
    my ($self) = @_;
644
    my $url    = $self->{'URL'};
645
646
647

    return $url
	if (defined($url));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
648

649
650
651
    my @certlines = $self->PipeTo(0, "$OPENSSL x509 -text -noout");
    if (! @certlines) {
	print STDERR "Could not get text from $self\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
652
653
	return undef;
    }
654

655
656
657
658
659
    # Note that we really want to put only URNs in the subjectAltName,
    # and all URLs in the subjectInfoAccess.  However, old certificates
    # used subjectAltName for URLs, so for temporary backward compatibility
    # we'll look in both places.
    my ($alturl,$accessurl);
660
    my $altname = 0;
661
    my $accessinfo = 0;
662
    for (@certlines) {
663
	if( /^\s+X509v3 Subject Alternative Name:\s*$/ ) {
664
	    $altname = 1;
665
666
	} elsif( /^\s+Authority Information Access:\s*$/ ) {
	    $accessinfo = 1;
667
668
669
670
671
672
673
674
	} elsif( $altname ) {
	    # Gah!  OpenSSL is horrible.  Apparently the text output format
	    # for the subject alternative name is fixed, and neither
	    # -nameopt nor -certopt will help us.  Worse still, the
	    # directory entries (e.g. URI, email) are comma separated...
	    # but commas are legal characters in URIs (see RFC 3986, section
	    # 2.2)!  We'll have to assume the delimiter is the ", " (comma,
	    # space) pair...
675
	    m'^\s*URI:([-!#$%()*+,./0-9:;=?@A-Z_a-z~]+)\s*$' and $alturl = $1
676
677
		foreach split( /, / );
	    $altname = 0;
678
679
680
681
	} elsif( $accessinfo ) {
	    m'^\s*[0-9.]+ - URI:([-!#$%()*+,./0-9:;=?@A-Z_a-z~]+)\s*$' and $accessurl = $1
		foreach split( /, / );
	    $accessinfo = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
682
683
	}
    }
684
685
    $url = defined( $accessurl ) ? $accessurl : 
	defined( $alturl ) ? $alturl : undef;
686
687
    if (!defined($url)) {
	print STDERR "Could not find url in $self\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
688
689
	return undef;
    }
690
691
692
693
694
    # Make sure its really a URL!
    if (! ($url =~ /^http/)) {
	print STDERR "Not a valid url in $self: $url\n";
	return undef;
    }
695
    $self->{'CERT'}->{'uri'} = $url;
696
    $self->{'URL'} = $url;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
697
698
    return $url;
}
699
700
# So a certificate looks like other things (authorities).
sub url($) { return $_[0]->URL(); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
701

702
703
704
705
706
707
708
709
710
711
712
#
# The URN is slightly easier, since it is always in the same place.
#
sub URN($)
{
    my ($self) = @_;
    my $urn    = $self->{'URN'};

    return $urn
	if (defined($urn));

713
714
715
    my @certlines = $self->PipeTo(0, "$OPENSSL x509 -text -noout");
    if (! @certlines) {
	print STDERR "Could not get text from $self\n";
716
717
718
	return undef;
    }
    my $altname = 0;
719
    for (@certlines) {
720
721
	if( /^\s+X509v3 Subject Alternative Name:\s*$/ ) {
	    $altname = 1;
722
723
	}
	elsif ($altname) {
724
	    m'^\s*URI:(urn:publicid:[-!#$%()*+,./0-9:;=?@A-Z_a-z~]+)\s*$' and $urn = $1
725
726
727
728
		foreach split( /, / );
	    $altname = 0;
	}
    }
729
730
    if (!defined($urn)) {
	print STDERR "Could not find URN in $self\n";
731
732
733
734
735
736
	return undef;
    }
    $self->{'URN'} = $urn;
    return $urn;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
737
738
739
740
sub asText($)
{
    my ($self) = @_;

741
742
743
    my @certlines = $self->PipeTo(0, "$OPENSSL x509 -text");
    if (! @certlines) {
	print STDERR "Could not convert $self to text\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
744
745
	return undef;
    }
746
    return join("", @certlines);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
747
748
}

749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
sub sha1($)
{
    my ($self) = @_;

    my @result = $self->PipeTo(0, "$SHA1");
    if (! @result) {
	print STDERR "Could not convert $self to sha1 hash\n";
	return undef;
    }
    my $hash = $result[0];
    if ($hash =~ /^(\w*)$/) {
	return $1;
    }
    print STDERR "Bad sha1 value for $self\n";
    return undef;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
#
# Load a CRL and store it.
#
sub StoreCRL($$$)
{
    my ($class, $authority, $string) = @_;

    my ($tempfile, $filename) = tempfile(UNLINK => 1);
    print $tempfile $string;

    my $uuid    = $authority->uuid();
    my $expires = `$OPENSSL crl -noout -nextupdate -in $filename`;
    chomp($expires);
    if (! (defined($expires) && ($expires =~ /^nextupdate/i))) {
	print STDERR "Could not get nextupdate from CRL\n";
	return -1;
    }
    $expires =~ s/^nextupdate=//i;
784
785
786
787
788
789
790
    my $issuer = `$OPENSSL crl -noout -issuer -in $filename`;
    chomp($issuer);
    if (! (defined($issuer) && ($issuer =~ /^issuer/i))) {
	print STDERR "Could not get issuer from CRL\n";
	return -1;
    }
    $issuer =~ s/^issuer=//i;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
791
792
    my $safe_cert    = DBQuoteSpecial($string);
    my $safe_expires = DBQuoteSpecial($expires);
793
    my $safe_issuer  = DBQuoteSpecial($issuer);
794
795
    my $dateconvert  = "DATE_SUB(STR_TO_DATE($safe_expires, ".
	"'%b %e %T %Y'), INTERVAL 1 DAY)";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
796
797

    DBQueryWarn("replace into geni_crls set ".
798
		"  uuid='$uuid', created=now(), expires=$dateconvert, ".
799
		"  cert=$safe_cert, DN=$safe_issuer")
Leigh B. Stoller's avatar
Leigh B. Stoller committed
800
	or return -1;
801
    unlink($filename);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
802
803
804
    return 0;
}

805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
#
# Remove a CRL.
#
sub DeleteCRL($$)
{
    my ($class, $authority) = @_;

    my $uuid = $authority->uuid();
    
    DBQueryWarn("delete from geni_crls where uuid='$uuid'")
	or return -1;

    return 0;
}

820
821
822
823
824
############################################################################
#
# Wrapper for local users.
#
package GeniCertificate::LocalUser;
825
use GeniHRN;
826
use English;
827
use emdb;
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844

#
# Create a wrapper, with the same access names.
#
sub Create($$)
{
    my ($class, $user) = @_;
    my $uid_idx = $user->uid_idx();

    my $query_result =
	DBQueryWarn("select * from user_sslcerts ".
		    "where uid_idx='$uid_idx' and encrypted=1 and ".
		    "      revoked is null");
		    
    return undef
	if (!defined($query_result) || !$query_result->numrows);

845
846
    my $self           = {};
    $self->{'CERT'}    = $query_result->fetchrow_hashref();
847
    $self->{'CERT'}->{'urn'} = GeniHRN::Generate( $OURDOMAIN, "user",
848
						  $self->{'CERT'}->{'uid'} );
849
    $self->{'stored'}  = 1;
850
    bless($self, $class);
851

852
853
854
855
856
857
858
859
860
    return $self;
}

sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'CERT'}->{$_[1]}); }
sub uuid($)		{ return field($_[0], "uuid"); }
sub created($)		{ return field($_[0], "created"); }
sub cert($)		{ return field($_[0], "cert"); }
sub privkey($)		{ return field($_[0], "privkey"); }
sub revoked($)		{ return field($_[0], "revoked"); }
861
862
sub uri($)              { return undef; }
sub urn($)              { return field($_[0], "urn"); }
863
sub URL($)              { return undef; }
864
sub URN($)              { return field($_[0], "urn"); }
865
sub GetCertificate($)   { return $_[0]; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
866

867
868
869
870
871
872
873
874
875
876
#
# Need to add DN to the emulab table.
#
sub DN($)
{
    my ($self) = @_;

    return $self->{'CERT'}->{'DN'}
        if (exists($self->{'CERT'}->{'DN'}));

877
878
879
880
    my @certlines =
	GeniCertificate::PipeTo($self, 0, "$OPENSSL x509 -noout -subject");
    if (!@certlines) {
	print STDERR "Failed to get DN from $self!\n";
881
882
	return undef;
    }
883
    my ($dn) = @certlines;
884
885
886
887
888
    chomp($dn);
    $self->{'CERT'}->{'DN'} = $dn;
    return $dn;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
889
890
# _Always_ make sure that this 1 is at the end of the file...
1;