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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
|
"""Read and write PEM files and strings."""
import base64
import StringIO
from ct.crypto import error
import types
class PemError(error.EncodingError):
pass
_START_TEMPLATE = "-----BEGIN %s-----"
_END_TEMPLATE = "-----END %s-----"
class PemReader(object):
"""A reader class for iteratively reading PEM files."""
def __init__(self, fileobj, markers, skip_invalid_blobs=True):
"""Create a PemReader from a file object.
When used as a context manager, the file object is closed
upon exit.
Args:
fileobj: the file object to read from.
markers: a single string or an iterable of markers accepted by the
reader, e.g., CERTIFICATE, RSA PUBLIC KEY, etc.
skip_invalid_blobs: if False, invalid PEM blobs cause a PemError.
If True, invalid blobs are skipped. In non-skip mode, an
immediate StopIteration before any valid blocks are found, also
causes a PemError exception.
Raises:
PemError: invalid PEM contents.
"""
if type(markers) in types.StringTypes:
markers = (markers,)
self.__f = fileobj
self.__marker_dict = ({(_START_TEMPLATE % m): m for m in markers})
self.__valid_blobs_read = 0
self.__eof = False
self.__skip_invalid_blobs = skip_invalid_blobs
def __iter__(self):
"""Iterate over file contents.
Returns:
a generator function that yields decoded (blob, marker)
tuples.
"""
return self.read_blocks()
def close(self):
"""Close the underlying file object."""
self.__f.close()
def __enter__(self):
return self
def __exit__(self, unused_type, unused_value, traceback):
self.close()
@classmethod
def from_file(cls, pem_file, markers, skip_invalid_blobs=True):
"""Create a PemReader for reading a file.
Caller is responsible for closing the reader afterwards.
Args:
pem_file: the file to read from.
markers: an iterable of markers accepted by the reader,e.g.,
CERTIFICATE, RSA PUBLIC KEY, etc.
skip_invalid_blobs: if False, invalid PEM blobs cause a PemError.
If True, invalid blobs are skipped. In non-skip mode, an
immediate StopIteration before any valid blocks are found, also
causes a PemError exception.
Returns:
a PemReader object.
Raises:
IOError, ValueError: the fileobject could not be operated on.
"""
return cls(open(pem_file, "r"), markers, skip_invalid_blobs)
@classmethod
def from_string(cls, pem_string, markers, skip_invalid_blobs=True):
"""Create a PemReader for reading a string.
Args:
pem_string: the string to read from.
markers: an iterable of markers accepted by the reader, e.g.,
CERTIFICATE, RSA PUBLIC KEY, etc.
skip_invalid_blobs: if False, invalid PEM blobs cause a PemError.
If True, invalid blobs are skipped. In non-skip mode, an
immediate StopIteration before any valid blocks are found, also
causes a PemError exception.
Returns:
a PemReader object.
"""
f = StringIO.StringIO(pem_string)
return cls(f, markers, skip_invalid_blobs)
def read_blocks(self):
"""Read the next PEM blob.
Yields:
(raw_string, marker) tuples containing the decoded blob and the
marker used to detect the blob.
Raises:
PemError: a PEM block was invalid (in skip_invalid_blobs mode).
IOError, ValueError: the file object could not be operated on.
StopIteration: EOF was reached.
"""
while not self.__eof:
marker = None
for line in self.__f:
line = line.rstrip("\r\n")
# PEM (RFC 1421) allows arbitrary comments between PEM blocks
# so we skip over those
if line in self.__marker_dict:
marker = self.__marker_dict[line]
break
if not marker:
self.__eof = True
if (not self.__skip_invalid_blobs and
not self.__valid_blobs_read):
raise PemError("No PEM header")
raise StopIteration
ret = ""
footer = _END_TEMPLATE % marker
footer_found = False
for line in self.__f:
line = line.rstrip("\r\n")
if line == footer:
footer_found = True
break
ret += line
# Here, we assume that each header is exactly matched by a footer.
# TODO(ekasper): determine if this assumption is overly strict,
# i.e., whether blocks such as BEGIN RSA PUBLIC KEY...END PUBLIC KEY
# are commonly used in applications.
if not footer_found:
self.__eof = True
if not self.__skip_invalid_blobs:
raise PemError("No PEM footer line to match the header")
raise StopIteration
try:
# We don't use ret.decode('base64') here as the exceptions from
# this method are not properly documented.
yield base64.b64decode(ret), marker
self.__valid_blobs_read += 1
except TypeError:
if not self.__skip_invalid_blobs:
# We do not set EOF here so caller can resume - even though
# this can normally be transparently handled by setting
# skip_invalid_blobs to True upon init.
raise PemError("Invalid base64 encoding")
# Else just continue the loop
raise StopIteration
class PemWriter(object):
"""A class for writing PEM blobs."""
def __init__(self, fileobj, marker):
"""Create a writer.
When used as a context manager, the underlying file object is closed
upon exit.
Args:
fileobj: the file object to write to. Must be open for writing AND
reading, and must be positioned at the writing position. Rather
than initializing directly from a file object, it is recommended
to use the from_file() constructor.
marker: the marker to use in headers.
"""
self.__f = fileobj
self.__header = _START_TEMPLATE % marker
self.__footer = _END_TEMPLATE % marker
def close(self):
self.__f.close()
def __enter__(self):
return self
def __exit__(self, unused_type, unused_value, traceback):
self.close()
@classmethod
def from_file(cls, filename, marker, append=False):
"""Construct a writer for writing to a file.
Caller is responsible for closing the writer afterwards.
Args:
filename: the file to write to.
marker: the marker to use in headers/footers.
append: if True, file will be opened in append mode.
Returns:
A PemWriter object.
Raises:
IOError: the file could not be opened.
"""
mode = "a+" if append else "w+"
f = open(filename, mode)
if append:
f.seek(0, 2)
return cls(f, marker)
def write(self, blob, check_newline=True):
"""Write a single PEM blob.
Args:
blob: a binary blob.
check_newline: if True, check whether the current position is at
the beginning of a new line and add a newline if not.
Raises:
IOError: the file could not be written to.
"""
# Header must start on a new line, so we try to be helpful and add one
# if it's missing.
# Note that a file open'ed in a+ mode will report its current reading
# (rather than writing) position - we deem it the caller's
# responsibility to seek to the write position. Failing that, the worst
# that can happen is either we fail to heal it, or add an extra newline.
if check_newline:
if self.__f.tell() != 0:
self.__f.seek(-1, 1)
if self.__f.read(1) != "\n":
self.__f.write("\n")
self.__f.write(self.__header)
pem_blob = base64.b64encode(blob)
for i in range(0, len(pem_blob), 64):
self.__f.write("\n")
self.__f.write(pem_blob[i:i+64])
self.__f.write("\n")
self.__f.write(self.__footer)
self.__f.write("\n")
def write_blocks(self, blobs):
"""Write PEM blobs.
Args:
blobs: an iterable of binary blobs.
Raises:
IOError: the file could not be written to.
"""
check_newline = True
for b in blobs:
self.write(b, check_newline=check_newline)
check_newline = False
@classmethod
def pem_string(cls, blob, marker):
"""Convert a binary blob to a PEM string.
Args:
blob: a single binary blob.
marker: the marker to use in headers/footers.
Returns:
a string of concatenated PEM blobs.
"""
stringio = StringIO.StringIO()
with cls(stringio, marker) as writer:
writer.write(blob)
return stringio.getvalue()
@classmethod
def blocks_to_pem_string(cls, blobs, marker):
"""Convert a binary blob to a PEM string.
Args:
blobs: an iterable of binary blobs.
marker: the marker to use in headers/footers.
Returns:
a string of concatenated PEM blobs.
"""
stringio = StringIO.StringIO()
with cls(stringio, marker) as writer:
writer.write_blocks(blobs)
return stringio.getvalue()
def from_pem(pem_string, markers):
"""Read a single PEM blob from a string.
Ignores everything before and after the first blob with valid markers.
Args:
pem_string: the PEM string.
markers: a single marker string or an iterable containing all
accepted markers, such as CERTIFICATE, RSA PUBLIC KEY,
PUBLIC KEY, etc.
Returns:
A (raw_string, marker) tuple containing the decoded blob and the
marker used to detect the blob.
Raises:
PemError: a PEM block was invalid or no valid PEM block was found.
"""
with PemReader.from_string(pem_string, markers,
skip_invalid_blobs=False) as reader:
return iter(reader).next()
def from_pem_file(pem_file, markers):
"""Read a single PEM blob from a file.
Ignores everything before and after the first blob with valid markers.
Args:
pem_file: the PEM file.
markers: a single marker string or an iterable containing all
accepted markers, such as CERTIFICATE, RSA PUBLIC KEY,
PUBLIC KEY, etc.
Returns:
A (raw_string, marker) tuple containing the decoded blob and the
marker used to detect the blob.
Raises:
PemError: a PEM block was invalid or no valid PEM block was found.
IOError: the file could not be read.
"""
with PemReader.from_file(pem_file, markers,
skip_invalid_blobs=False) as reader:
return iter(reader).next()
def pem_blocks(pem_string, markers, skip_invalid_blobs=True):
"""Read PEM blobs from a string.
Args:
pem_string: the PEM string.
markers: a single marker string or an iterable containing all
accepted markers, such as CERTIFICATE, RSA PUBLIC KEY,
PUBLIC KEY, etc.
skip_invalid_blobs: if False, invalid PEM blobs cause a PemError.
If True, invalid blobs are skipped. In non-skip mode, an immediate
StopIteration before any valid blocks are found, also causes a
a PemError exception.
Yields:
(raw_string, marker) tuples containing the decoded blob and the marker
used to detect the blob.
Raises:
PemError: a PEM block was invalid.
"""
with PemReader.from_string(pem_string, markers,
skip_invalid_blobs=skip_invalid_blobs) as reader:
for block in reader:
yield block
def pem_blocks_from_file(pem_file, markers, skip_invalid_blobs=True):
"""Read PEM blobs from a file.
Args:
pem_file: the PEM file.
markers: a single marker string or an iterable containing all accepted
markers, such as CERTIFICATE, RSA PUBLIC KEY, PUBLIC KEY, etc.
skip_invalid_blobs: if False, invalid PEM blobs cause a PemError.
If True, invalid blobs are skipped. In non-skip mode, an immediate
StopIteration before any valid blocks are found, also causes a
PemError exception.
Yields:
(raw_string, marker) tuples containing the decoded blob and the marker
used to detect the blob.
Raises:
PemError: a PEM block was invalid.
"""
with PemReader.from_file(pem_file, markers,
skip_invalid_blobs=skip_invalid_blobs) as reader:
for block in reader:
yield block
def to_pem(blob, marker):
"""Convert a binary blob to a PEM-formatted string.
Args:
blob: a binary blob.
marker: the marker to use, e.g., CERTIFICATE.
Returns:
the PEM string.
"""
return PemWriter.pem_string(blob, marker)
def blocks_to_pem(blobs, marker):
"""Convert binary blobs to a string of concatenated PEM-formatted blocks.
Args:
blobs: an iterable of binary blobs
marker: the marker to use, e.g., CERTIFICATE
Returns:
the PEM string.
"""
return PemWriter.blocks_to_pem_string(blobs, marker)
def to_pem_file(blob, filename, marker):
"""Convert a binary blob to PEM format and write to file.
Args:
blob: a binary blob.
filename: the file to write to.
marker: the marker to use, e.g., CERTIFICATE.
Raises:
IOError: the file could not be written to.
"""
with PemWriter.from_file(filename, marker) as writer:
writer.write(blob)
def blocks_to_pem_file(blobs, filename, marker):
"""Convert binary blobs to PEM format and write to file.
Blobs must all be of one and the same type.
Args:
blobs: an iterable of binary blobs.
filename: the file to write to.
marker: the marker to use, e.g., CERTIFICATE.
Raises:
IOError: the file could not be written to.
"""
with PemWriter.from_file(filename, marker) as writer:
writer.write_blocks(blobs)
|