Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/scapy/asn1/asn1.py: 67%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

426 statements  

1# SPDX-License-Identifier: GPL-2.0-only 

2# This file is part of Scapy 

3# See https://scapy.net/ for more information 

4# Copyright (C) Philippe Biondi <phil@secdev.org> 

5# Acknowledgment: Maxence Tury <maxence.tury@ssi.gouv.fr> 

6 

7""" 

8ASN.1 (Abstract Syntax Notation One) 

9""" 

10 

11import random 

12 

13from datetime import datetime, timedelta, tzinfo 

14from scapy.config import conf 

15from scapy.error import Scapy_Exception, warning 

16from scapy.volatile import RandField, RandIP, GeneralizedTime 

17from scapy.utils import Enum_metaclass, EnumElement, binrepr 

18from scapy.compat import plain_str, bytes_encode, chb, orb 

19 

20from typing import ( 

21 Any, 

22 AnyStr, 

23 Dict, 

24 Generic, 

25 List, 

26 Optional, 

27 Tuple, 

28 Type, 

29 Union, 

30 cast, 

31 TYPE_CHECKING, 

32) 

33from typing import ( 

34 TypeVar, 

35) 

36 

37if TYPE_CHECKING: 

38 from scapy.asn1.ber import BERcodec_Object 

39 

40try: 

41 from datetime import timezone 

42except ImportError: 

43 # Python 2 compat - don't bother typing it 

44 class UTC(tzinfo): 

45 """UTC""" 

46 

47 def utcoffset(self, dt): # type: ignore 

48 return timedelta(0) 

49 

50 def tzname(self, dt): # type: ignore 

51 return "UTC" 

52 

53 def dst(self, dt): # type: ignore 

54 return None 

55 

56 class timezone(tzinfo): # type: ignore 

57 def __init__(self, delta): # type: ignore 

58 self.delta = delta 

59 

60 def utcoffset(self, dt): # type: ignore 

61 return self.delta 

62 

63 def tzname(self, dt): # type: ignore 

64 return None 

65 

66 def dst(self, dt): # type: ignore 

67 return None 

68 

69 timezone.utc = UTC() # type: ignore 

70 

71 

72class RandASN1Object(RandField["ASN1_Object[Any]"]): 

73 def __init__(self, objlist=None): 

74 # type: (Optional[List[Type[ASN1_Object[Any]]]]) -> None 

75 if objlist: 

76 self.objlist = objlist 

77 else: 

78 self.objlist = [ 

79 x._asn1_obj 

80 for x in ASN1_Class_UNIVERSAL.__rdict__.values() # type: ignore 

81 if hasattr(x, "_asn1_obj") 

82 ] 

83 self.chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" # noqa: E501 

84 

85 def _fix(self, n=0): 

86 # type: (int) -> ASN1_Object[Any] 

87 o = random.choice(self.objlist) 

88 if issubclass(o, ASN1_INTEGER): 

89 return o(int(random.gauss(0, 1000))) 

90 elif issubclass(o, ASN1_IPADDRESS): 

91 z = RandIP()._fix() 

92 return o(z) 

93 elif issubclass(o, ASN1_GENERALIZED_TIME) or issubclass(o, ASN1_UTC_TIME): # noqa: E501 

94 z = GeneralizedTime()._fix() 

95 return o(z) 

96 elif issubclass(o, ASN1_STRING): 

97 z1 = int(random.expovariate(0.05) + 1) 

98 return o("".join(random.choice(self.chars) for _ in range(z1))) 

99 elif issubclass(o, ASN1_SEQUENCE) and (n < 10): 

100 z2 = int(random.expovariate(0.08) + 1) 

101 return o([self.__class__(objlist=self.objlist)._fix(n + 1) 

102 for _ in range(z2)]) 

103 return ASN1_INTEGER(int(random.gauss(0, 1000))) 

104 

105 

106############## 

107# ASN1 # 

108############## 

109 

110class ASN1_Error(Scapy_Exception): 

111 pass 

112 

113 

114class ASN1_Encoding_Error(ASN1_Error): 

115 pass 

116 

117 

118class ASN1_Decoding_Error(ASN1_Error): 

119 pass 

120 

121 

122class ASN1_BadTag_Decoding_Error(ASN1_Decoding_Error): 

123 pass 

124 

125 

126class ASN1Codec(EnumElement): 

127 def register_stem(cls, stem): 

128 # type: (Type[BERcodec_Object[Any]]) -> None 

129 cls._stem = stem 

130 

131 def dec(cls, s, context=None): 

132 # type: (bytes, Optional[Type[ASN1_Class]]) -> ASN1_Object[Any] 

133 return cls._stem.dec(s, context=context) # type: ignore 

134 

135 def safedec(cls, s, context=None): 

136 # type: (bytes, Optional[Type[ASN1_Class]]) -> ASN1_Object[Any] 

137 return cls._stem.safedec(s, context=context) # type: ignore 

138 

139 def get_stem(cls): 

140 # type: () -> type 

141 return cls._stem 

142 

143 

144class ASN1_Codecs_metaclass(Enum_metaclass): 

145 element_class = ASN1Codec 

146 

147 

148class ASN1_Codecs(metaclass=ASN1_Codecs_metaclass): 

149 BER = cast(ASN1Codec, 1) 

150 DER = cast(ASN1Codec, 2) 

151 PER = cast(ASN1Codec, 3) 

152 CER = cast(ASN1Codec, 4) 

153 LWER = cast(ASN1Codec, 5) 

154 BACnet = cast(ASN1Codec, 6) 

155 OER = cast(ASN1Codec, 7) 

156 SER = cast(ASN1Codec, 8) 

157 XER = cast(ASN1Codec, 9) 

158 

159 

160class ASN1Tag(EnumElement): 

161 def __init__(self, 

162 key, # type: str 

163 value, # type: int 

164 context=None, # type: Optional[Type[ASN1_Class]] 

165 codec=None # type: Optional[Dict[ASN1Codec, Type[BERcodec_Object[Any]]]] # noqa: E501 

166 ): 

167 # type: (...) -> None 

168 EnumElement.__init__(self, key, value) 

169 # populated by the metaclass 

170 self.context = context # type: Type[ASN1_Class] # type: ignore 

171 if codec is None: 

172 codec = {} 

173 self._codec = codec 

174 

175 def clone(self): # not a real deep copy. self.codec is shared 

176 # type: () -> ASN1Tag 

177 return self.__class__(self._key, self._value, self.context, self._codec) # noqa: E501 

178 

179 def register_asn1_object(self, asn1obj): 

180 # type: (Type[ASN1_Object[Any]]) -> None 

181 self._asn1_obj = asn1obj 

182 

183 def asn1_object(self, val): 

184 # type: (Any) -> ASN1_Object[Any] 

185 if hasattr(self, "_asn1_obj"): 

186 return self._asn1_obj(val) 

187 raise ASN1_Error("%r does not have any assigned ASN1 object" % self) 

188 

189 def register(self, codecnum, codec): 

190 # type: (ASN1Codec, Type[BERcodec_Object[Any]]) -> None 

191 self._codec[codecnum] = codec 

192 

193 def get_codec(self, codec): 

194 # type: (Any) -> Type[BERcodec_Object[Any]] 

195 try: 

196 c = self._codec[codec] 

197 except KeyError: 

198 raise ASN1_Error("Codec %r not found for tag %r" % (codec, self)) 

199 return c 

200 

201 

202class ASN1_Class_metaclass(Enum_metaclass): 

203 element_class = ASN1Tag 

204 

205 # XXX factorise a bit with Enum_metaclass.__new__() 

206 def __new__(cls, 

207 name, # type: str 

208 bases, # type: Tuple[type, ...] 

209 dct # type: Dict[str, Any] 

210 ): 

211 # type: (...) -> Type[ASN1_Class] 

212 for b in bases: 

213 for k, v in b.__dict__.items(): 

214 if k not in dct and isinstance(v, ASN1Tag): 

215 dct[k] = v.clone() 

216 

217 rdict = {} 

218 for k, v in dct.items(): 

219 if isinstance(v, int): 

220 v = ASN1Tag(k, v) 

221 dct[k] = v 

222 rdict[v] = v 

223 elif isinstance(v, ASN1Tag): 

224 rdict[v] = v 

225 dct["__rdict__"] = rdict 

226 

227 ncls = cast('Type[ASN1_Class]', 

228 type.__new__(cls, name, bases, dct)) 

229 for v in ncls.__dict__.values(): 

230 if isinstance(v, ASN1Tag): 

231 # overwrite ASN1Tag contexts, even cloned ones 

232 v.context = ncls 

233 return ncls 

234 

235 

236class ASN1_Class(metaclass=ASN1_Class_metaclass): 

237 pass 

238 

239 

240class ASN1_Class_UNIVERSAL(ASN1_Class): 

241 name = "UNIVERSAL" 

242 # Those casts are made so that MyPy understands what the 

243 # metaclass does in the background. 

244 ERROR = cast(ASN1Tag, -3) 

245 RAW = cast(ASN1Tag, -2) 

246 NONE = cast(ASN1Tag, -1) 

247 ANY = cast(ASN1Tag, 0) 

248 BOOLEAN = cast(ASN1Tag, 1) 

249 INTEGER = cast(ASN1Tag, 2) 

250 BIT_STRING = cast(ASN1Tag, 3) 

251 STRING = cast(ASN1Tag, 4) 

252 NULL = cast(ASN1Tag, 5) 

253 OID = cast(ASN1Tag, 6) 

254 OBJECT_DESCRIPTOR = cast(ASN1Tag, 7) 

255 EXTERNAL = cast(ASN1Tag, 8) 

256 REAL = cast(ASN1Tag, 9) 

257 ENUMERATED = cast(ASN1Tag, 10) 

258 EMBEDDED_PDF = cast(ASN1Tag, 11) 

259 UTF8_STRING = cast(ASN1Tag, 12) 

260 RELATIVE_OID = cast(ASN1Tag, 13) 

261 SEQUENCE = cast(ASN1Tag, 16 | 0x20) # constructed encoding 

262 SET = cast(ASN1Tag, 17 | 0x20) # constructed encoding 

263 NUMERIC_STRING = cast(ASN1Tag, 18) 

264 PRINTABLE_STRING = cast(ASN1Tag, 19) 

265 T61_STRING = cast(ASN1Tag, 20) # aka TELETEX_STRING 

266 VIDEOTEX_STRING = cast(ASN1Tag, 21) 

267 IA5_STRING = cast(ASN1Tag, 22) 

268 UTC_TIME = cast(ASN1Tag, 23) 

269 GENERALIZED_TIME = cast(ASN1Tag, 24) 

270 GRAPHIC_STRING = cast(ASN1Tag, 25) 

271 ISO646_STRING = cast(ASN1Tag, 26) # aka VISIBLE_STRING 

272 GENERAL_STRING = cast(ASN1Tag, 27) 

273 UNIVERSAL_STRING = cast(ASN1Tag, 28) 

274 CHAR_STRING = cast(ASN1Tag, 29) 

275 BMP_STRING = cast(ASN1Tag, 30) 

276 IPADDRESS = cast(ASN1Tag, 0 | 0x40) # application-specific encoding 

277 COUNTER32 = cast(ASN1Tag, 1 | 0x40) # application-specific encoding 

278 COUNTER64 = cast(ASN1Tag, 6 | 0x40) # application-specific encoding 

279 GAUGE32 = cast(ASN1Tag, 2 | 0x40) # application-specific encoding 

280 TIME_TICKS = cast(ASN1Tag, 3 | 0x40) # application-specific encoding 

281 

282 

283class ASN1_Object_metaclass(type): 

284 def __new__(cls, 

285 name, # type: str 

286 bases, # type: Tuple[type, ...] 

287 dct # type: Dict[str, Any] 

288 ): 

289 # type: (...) -> Type[ASN1_Object[Any]] 

290 c = cast( 

291 'Type[ASN1_Object[Any]]', 

292 super(ASN1_Object_metaclass, cls).__new__(cls, name, bases, dct) 

293 ) 

294 try: 

295 c.tag.register_asn1_object(c) 

296 except Exception: 

297 warning("Error registering %r" % c.tag) 

298 return c 

299 

300 

301_K = TypeVar('_K') 

302 

303 

304class ASN1_Object(Generic[_K], metaclass=ASN1_Object_metaclass): 

305 tag = ASN1_Class_UNIVERSAL.ANY 

306 

307 def __init__(self, val): 

308 # type: (_K) -> None 

309 self.val = val 

310 

311 def enc(self, codec): 

312 # type: (Any) -> bytes 

313 return self.tag.get_codec(codec).enc(self.val) 

314 

315 def __repr__(self): 

316 # type: () -> str 

317 return "<%s[%r]>" % (self.__dict__.get("name", self.__class__.__name__), self.val) # noqa: E501 

318 

319 def __str__(self): 

320 # type: () -> str 

321 return plain_str(self.enc(conf.ASN1_default_codec)) 

322 

323 def __bytes__(self): 

324 # type: () -> bytes 

325 return self.enc(conf.ASN1_default_codec) 

326 

327 def strshow(self, lvl=0): 

328 # type: (int) -> str 

329 return (" " * lvl) + repr(self) + "\n" 

330 

331 def show(self, lvl=0): 

332 # type: (int) -> None 

333 print(self.strshow(lvl)) 

334 

335 def __eq__(self, other): 

336 # type: (Any) -> bool 

337 return bool(self.val == other) 

338 

339 def __lt__(self, other): 

340 # type: (Any) -> bool 

341 return bool(self.val < other) 

342 

343 def __le__(self, other): 

344 # type: (Any) -> bool 

345 return bool(self.val <= other) 

346 

347 def __gt__(self, other): 

348 # type: (Any) -> bool 

349 return bool(self.val > other) 

350 

351 def __ge__(self, other): 

352 # type: (Any) -> bool 

353 return bool(self.val >= other) 

354 

355 def __ne__(self, other): 

356 # type: (Any) -> bool 

357 return bool(self.val != other) 

358 

359 def command(self, json=False): 

360 # type: (bool) -> Union[Dict[str, str], str] 

361 if json: 

362 if isinstance(self.val, bytes): 

363 val = self.val.decode("utf-8", errors="backslashreplace") 

364 else: 

365 val = repr(self.val) 

366 return {"type": self.__class__.__name__, "value": val} 

367 else: 

368 return "%s(%s)" % (self.__class__.__name__, repr(self.val)) 

369 

370 

371####################### 

372# ASN1 objects # 

373####################### 

374 

375# on the whole, we order the classes by ASN1_Class_UNIVERSAL tag value 

376 

377class _ASN1_ERROR(ASN1_Object[Union[bytes, ASN1_Object[Any]]]): 

378 pass 

379 

380 

381class ASN1_DECODING_ERROR(_ASN1_ERROR): 

382 tag = ASN1_Class_UNIVERSAL.ERROR 

383 

384 def __init__(self, val, exc=None): 

385 # type: (Union[bytes, ASN1_Object[Any]], Optional[Exception]) -> None 

386 ASN1_Object.__init__(self, val) 

387 self.exc = exc 

388 

389 def __repr__(self): 

390 # type: () -> str 

391 return "<%s[%r]{{%r}}>" % ( 

392 self.__dict__.get("name", self.__class__.__name__), 

393 self.val, 

394 self.exc and self.exc.args[0] or "" 

395 ) 

396 

397 def enc(self, codec): 

398 # type: (Any) -> bytes 

399 if isinstance(self.val, ASN1_Object): 

400 return self.val.enc(codec) 

401 return self.val 

402 

403 

404class ASN1_force(_ASN1_ERROR): 

405 tag = ASN1_Class_UNIVERSAL.RAW 

406 

407 def enc(self, codec): 

408 # type: (Any) -> bytes 

409 if isinstance(self.val, ASN1_Object): 

410 return self.val.enc(codec) 

411 return self.val 

412 

413 

414class ASN1_BADTAG(ASN1_force): 

415 pass 

416 

417 

418class ASN1_INTEGER(ASN1_Object[int]): 

419 tag = ASN1_Class_UNIVERSAL.INTEGER 

420 

421 def __repr__(self): 

422 # type: () -> str 

423 h = hex(self.val) 

424 if h[-1] == "L": 

425 h = h[:-1] 

426 # cut at 22 because with leading '0x', x509 serials should be < 23 

427 if len(h) > 22: 

428 h = h[:12] + "..." + h[-10:] 

429 r = repr(self.val) 

430 if len(r) > 20: 

431 r = r[:10] + "..." + r[-10:] 

432 return h + " <%s[%s]>" % (self.__dict__.get("name", self.__class__.__name__), r) # noqa: E501 

433 

434 

435class ASN1_BOOLEAN(ASN1_INTEGER): 

436 tag = ASN1_Class_UNIVERSAL.BOOLEAN 

437 # BER: 0 means False, anything else means True 

438 

439 def __repr__(self): 

440 # type: () -> str 

441 return '%s %s' % (not (self.val == 0), ASN1_Object.__repr__(self)) 

442 

443 

444class ASN1_BIT_STRING(ASN1_Object[str]): 

445 """ 

446 ASN1_BIT_STRING values are bit strings like "011101". 

447 A zero-bit padded readable string is provided nonetheless, 

448 which is stored in val_readable 

449 """ 

450 tag = ASN1_Class_UNIVERSAL.BIT_STRING 

451 

452 def __init__(self, val, readable=False): 

453 # type: (AnyStr, bool) -> None 

454 if not readable: 

455 self.val = cast(str, val) # type: ignore 

456 else: 

457 self.val_readable = cast(bytes, val) # type: ignore 

458 

459 def __setattr__(self, name, value): 

460 # type: (str, Any) -> None 

461 if name == "val_readable": 

462 if isinstance(value, (str, bytes)): 

463 val = "".join(binrepr(orb(x)).zfill(8) for x in value) 

464 else: 

465 warning("Invalid val: should be bytes") 

466 val = "<invalid val_readable>" 

467 object.__setattr__(self, "val", val) 

468 object.__setattr__(self, name, bytes_encode(value)) 

469 object.__setattr__(self, "unused_bits", 0) 

470 elif name == "val": 

471 value = plain_str(value) 

472 if isinstance(value, str): 

473 if any(c for c in value if c not in ["0", "1"]): 

474 warning("Invalid operation: 'val' is not a valid bit string.") # noqa: E501 

475 return 

476 else: 

477 if len(value) % 8 == 0: 

478 unused_bits = 0 

479 else: 

480 unused_bits = 8 - (len(value) % 8) 

481 padded_value = value + ("0" * unused_bits) 

482 bytes_arr = zip(*[iter(padded_value)] * 8) 

483 val_readable = b"".join(chb(int("".join(x), 2)) for x in bytes_arr) # noqa: E501 

484 else: 

485 warning("Invalid val: should be str") 

486 val_readable = b"<invalid val>" 

487 unused_bits = 0 

488 object.__setattr__(self, "val_readable", val_readable) 

489 object.__setattr__(self, name, value) 

490 object.__setattr__(self, "unused_bits", unused_bits) 

491 elif name == "unused_bits": 

492 warning("Invalid operation: unused_bits rewriting " 

493 "is not supported.") 

494 else: 

495 object.__setattr__(self, name, value) 

496 

497 def set(self, i, val): 

498 # type: (int, str) -> None 

499 """ 

500 Sets bit 'i' to value 'val' (starting from 0) 

501 """ 

502 val = str(val) 

503 assert val in ['0', '1'] 

504 self.val = self.val[:i] + val + self.val[i + 1:] 

505 

506 def __repr__(self): 

507 # type: () -> str 

508 s = self.val_readable 

509 if len(s) > 16: 

510 s = s[:10] + b"..." + s[-10:] 

511 v = self.val 

512 if len(v) > 20: 

513 v = v[:10] + "..." + v[-10:] 

514 return "<%s[%s]=%r (%d unused bit%s)>" % ( 

515 self.__dict__.get("name", self.__class__.__name__), 

516 v, 

517 s, 

518 self.unused_bits, # type: ignore 

519 "s" if self.unused_bits > 1 else "" # type: ignore 

520 ) 

521 

522 

523class ASN1_STRING(ASN1_Object[str]): 

524 tag = ASN1_Class_UNIVERSAL.STRING 

525 

526 

527class ASN1_NULL(ASN1_Object[None]): 

528 tag = ASN1_Class_UNIVERSAL.NULL 

529 

530 def __repr__(self): 

531 # type: () -> str 

532 return ASN1_Object.__repr__(self) 

533 

534 

535class ASN1_OID(ASN1_Object[str]): 

536 tag = ASN1_Class_UNIVERSAL.OID 

537 

538 def __init__(self, val): 

539 # type: (str) -> None 

540 val = plain_str(val) 

541 val = conf.mib._oid(val) 

542 ASN1_Object.__init__(self, val) 

543 self.oidname = conf.mib._oidname(val) 

544 

545 def __repr__(self): 

546 # type: () -> str 

547 return "<%s[%r]>" % (self.__dict__.get("name", self.__class__.__name__), self.oidname) # noqa: E501 

548 

549 

550class ASN1_ENUMERATED(ASN1_INTEGER): 

551 tag = ASN1_Class_UNIVERSAL.ENUMERATED 

552 

553 

554class ASN1_UTF8_STRING(ASN1_STRING): 

555 tag = ASN1_Class_UNIVERSAL.UTF8_STRING 

556 

557 

558class ASN1_NUMERIC_STRING(ASN1_STRING): 

559 tag = ASN1_Class_UNIVERSAL.NUMERIC_STRING 

560 

561 

562class ASN1_PRINTABLE_STRING(ASN1_STRING): 

563 tag = ASN1_Class_UNIVERSAL.PRINTABLE_STRING 

564 

565 

566class ASN1_T61_STRING(ASN1_STRING): 

567 tag = ASN1_Class_UNIVERSAL.T61_STRING 

568 

569 

570class ASN1_VIDEOTEX_STRING(ASN1_STRING): 

571 tag = ASN1_Class_UNIVERSAL.VIDEOTEX_STRING 

572 

573 

574class ASN1_IA5_STRING(ASN1_STRING): 

575 tag = ASN1_Class_UNIVERSAL.IA5_STRING 

576 

577 

578class ASN1_GENERAL_STRING(ASN1_STRING): 

579 tag = ASN1_Class_UNIVERSAL.GENERAL_STRING 

580 

581 

582class ASN1_GENERALIZED_TIME(ASN1_STRING): 

583 """ 

584 Improved version of ASN1_GENERALIZED_TIME, properly handling time zones and 

585 all string representation formats defined by ASN.1. These are: 

586 

587 1. Local time only: YYYYMMDDHH[MM[SS[.fff]]] 

588 2. Universal time (UTC time) only: YYYYMMDDHH[MM[SS[.fff]]]Z 

589 3. Difference between local and UTC times: YYYYMMDDHH[MM[SS[.fff]]]+-HHMM 

590 

591 It also handles ASN1_UTC_TIME, which allows: 

592 

593 1. Universal time (UTC time) only: YYMMDDHHMM[SS[.fff]]Z 

594 2. Difference between local and UTC times: YYMMDDHHMM[SS[.fff]]+-HHMM 

595 

596 Note the differences: Year is only two digits, minutes are not optional and 

597 there is no milliseconds. 

598 """ 

599 tag = ASN1_Class_UNIVERSAL.GENERALIZED_TIME 

600 pretty_time = None 

601 

602 def __init__(self, val): 

603 # type: (Union[str, datetime]) -> None 

604 if isinstance(val, datetime): 

605 self.__setattr__("datetime", val) 

606 else: 

607 super(ASN1_GENERALIZED_TIME, self).__init__(val) 

608 

609 def __setattr__(self, name, value): 

610 # type: (str, Any) -> None 

611 if isinstance(value, bytes): 

612 value = plain_str(value) 

613 

614 if name == "val": 

615 formats = { 

616 10: "%Y%m%d%H", 

617 12: "%Y%m%d%H%M", 

618 14: "%Y%m%d%H%M%S" 

619 } 

620 dt = None # type: Optional[datetime] 

621 try: 

622 if value[-1] == "Z": 

623 str, ofs = value[:-1], value[-1:] 

624 elif value[-5] in ("+", "-"): 

625 str, ofs = value[:-5], value[-5:] 

626 elif isinstance(self, ASN1_UTC_TIME): 

627 raise ValueError() 

628 else: 

629 str, ofs = value, "" 

630 

631 if isinstance(self, ASN1_UTC_TIME) and len(str) >= 10: 

632 fmt = "%y" + formats[len(str) + 2][2:] 

633 elif str[-4] == ".": 

634 fmt = formats[len(str) - 4] + ".%f" 

635 else: 

636 fmt = formats[len(str)] 

637 

638 dt = datetime.strptime(str, fmt) 

639 if ofs == 'Z': 

640 dt = dt.replace(tzinfo=timezone.utc) 

641 elif ofs: 

642 sign = -1 if ofs[0] == "-" else 1 

643 ofs = datetime.strptime(ofs[1:], "%H%M") 

644 delta = timedelta(hours=ofs.hour * sign, 

645 minutes=ofs.minute * sign) 

646 dt = dt.replace(tzinfo=timezone(delta)) 

647 except Exception: 

648 dt = None 

649 

650 pretty_time = None 

651 if dt is None: 

652 _nam = self.tag._asn1_obj.__name__[5:] 

653 _nam = _nam.lower().replace("_", " ") 

654 pretty_time = "%s [invalid %s]" % (value, _nam) 

655 else: 

656 pretty_time = dt.strftime("%Y-%m-%d %H:%M:%S") 

657 if dt.microsecond: 

658 pretty_time += dt.strftime(".%f")[:4] 

659 if dt.tzinfo == timezone.utc: 

660 pretty_time += dt.strftime(" UTC") 

661 elif dt.tzinfo is not None: 

662 if dt.tzinfo.utcoffset(dt) is not None: 

663 pretty_time += dt.strftime(" %z") 

664 

665 ASN1_STRING.__setattr__(self, "pretty_time", pretty_time) 

666 ASN1_STRING.__setattr__(self, "datetime", dt) 

667 ASN1_STRING.__setattr__(self, name, value) 

668 elif name == "pretty_time": 

669 print("Invalid operation: pretty_time rewriting is not supported.") 

670 elif name == "datetime": 

671 ASN1_STRING.__setattr__(self, name, value) 

672 if isinstance(value, datetime): 

673 yfmt = "%y" if isinstance(self, ASN1_UTC_TIME) else "%Y" 

674 if value.microsecond: 

675 str = value.strftime(yfmt + "%m%d%H%M%S.%f")[:-3] 

676 else: 

677 str = value.strftime(yfmt + "%m%d%H%M%S") 

678 

679 if value.tzinfo == timezone.utc: 

680 str = str + "Z" 

681 else: 

682 str = str + value.strftime("%z") # empty if naive 

683 

684 ASN1_STRING.__setattr__(self, "val", str) 

685 else: 

686 ASN1_STRING.__setattr__(self, "val", None) 

687 else: 

688 ASN1_STRING.__setattr__(self, name, value) 

689 

690 def __repr__(self): 

691 # type: () -> str 

692 return "%s %s" % ( 

693 self.pretty_time, 

694 super(ASN1_GENERALIZED_TIME, self).__repr__() 

695 ) 

696 

697 

698class ASN1_UTC_TIME(ASN1_GENERALIZED_TIME): 

699 tag = ASN1_Class_UNIVERSAL.UTC_TIME 

700 

701 

702class ASN1_ISO646_STRING(ASN1_STRING): 

703 tag = ASN1_Class_UNIVERSAL.ISO646_STRING 

704 

705 

706class ASN1_UNIVERSAL_STRING(ASN1_STRING): 

707 tag = ASN1_Class_UNIVERSAL.UNIVERSAL_STRING 

708 

709 

710class ASN1_BMP_STRING(ASN1_STRING): 

711 tag = ASN1_Class_UNIVERSAL.BMP_STRING 

712 

713 

714class ASN1_SEQUENCE(ASN1_Object[List[Any]]): 

715 tag = ASN1_Class_UNIVERSAL.SEQUENCE 

716 

717 def strshow(self, lvl=0): 

718 # type: (int) -> str 

719 s = (" " * lvl) + ("# %s:" % self.__class__.__name__) + "\n" 

720 for o in self.val: 

721 s += o.strshow(lvl=lvl + 1) 

722 return s 

723 

724 

725class ASN1_SET(ASN1_SEQUENCE): 

726 tag = ASN1_Class_UNIVERSAL.SET 

727 

728 

729class ASN1_IPADDRESS(ASN1_STRING): 

730 tag = ASN1_Class_UNIVERSAL.IPADDRESS 

731 

732 

733class ASN1_COUNTER32(ASN1_INTEGER): 

734 tag = ASN1_Class_UNIVERSAL.COUNTER32 

735 

736 

737class ASN1_COUNTER64(ASN1_INTEGER): 

738 tag = ASN1_Class_UNIVERSAL.COUNTER64 

739 

740 

741class ASN1_GAUGE32(ASN1_INTEGER): 

742 tag = ASN1_Class_UNIVERSAL.GAUGE32 

743 

744 

745class ASN1_TIME_TICKS(ASN1_INTEGER): 

746 tag = ASN1_Class_UNIVERSAL.TIME_TICKS 

747 

748 

749conf.ASN1_default_codec = ASN1_Codecs.BER