/usr/lib/python3/dist-packages/tlslite/messages.py is in python3-tlslite-ng 0.5.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 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 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 | # Authors:
# Trevor Perrin
# Google - handling CertificateRequest.certificate_types
# Google (adapted by Sam Rushing and Marcelo Fernandez) - NPN support
# Dimitris Moraitis - Anon ciphersuites
# Yngve Pettersen (ported by Paul Sokolovsky) - TLS 1.2
# Hubert Kario - 'extensions' cleanup
#
# See the LICENSE file for legal information regarding use of this file.
"""Classes representing TLS messages."""
from .utils.compat import *
from .utils.cryptomath import *
from .errors import *
from .utils.codec import *
from .constants import *
from .x509 import X509
from .x509certchain import X509CertChain
from .utils.tackwrapper import *
from .extensions import *
class RecordHeader(object):
"""Generic interface to SSLv2 and SSLv3 (and later) record headers"""
def __init__(self, ssl2):
"""define instance variables"""
self.type = 0
self.version = (0, 0)
self.length = 0
self.ssl2 = ssl2
class RecordHeader3(RecordHeader):
"""SSLv3 (and later) TLS record header"""
def __init__(self):
"""Define a SSLv3 style class"""
super(RecordHeader3, self).__init__(ssl2=False)
def create(self, version, type, length):
"""Set object values for writing (serialisation)"""
self.type = type
self.version = version
self.length = length
return self
def write(self):
"""Serialise object to bytearray"""
writer = Writer()
writer.add(self.type, 1)
writer.add(self.version[0], 1)
writer.add(self.version[1], 1)
writer.add(self.length, 2)
return writer.bytes
def parse(self, parser):
"""Deserialise object from Parser"""
self.type = parser.get(1)
self.version = (parser.get(1), parser.get(1))
self.length = parser.get(2)
self.ssl2 = False
return self
@property
def typeName(self):
matching = [x[0] for x in ContentType.__dict__.items()
if x[1] == self.type]
if len(matching) == 0:
return "unknown(" + str(self.type) + ")"
else:
return str(matching[0])
def __str__(self):
return "SSLv3 record,version({0[0]}.{0[1]}),"\
"content type({1}),length({2})".format(self.version,
self.typeName, self.length)
def __repr__(self):
return "RecordHeader3(type={0}, version=({1[0]}.{1[1]}), length={2})".\
format(self.type, self.version, self.length)
class RecordHeader2(RecordHeader):
"""SSLv2 record header (just reading)"""
def __init__(self):
"""Define a SSLv2 style class"""
super(RecordHeader2, self).__init__(ssl2=True)
def parse(self, parser):
"""Deserialise object from Parser"""
if parser.get(1) != 128:
raise SyntaxError()
self.type = ContentType.handshake
self.version = (2, 0)
#XXX We don't support 2-byte-length-headers; could be a problem
self.length = parser.get(1)
return self
class Message(object):
"""Generic TLS message"""
def __init__(self, contentType, data):
"""
Initialize object with specified contentType and data
@type contentType: int
@param contentType: TLS record layer content type of associated data
@type data: bytearray
@param data: data
"""
self.contentType = contentType
self.data = data
def write(self):
"""Return serialised object data"""
return self.data
class Alert(object):
def __init__(self):
self.contentType = ContentType.alert
self.level = 0
self.description = 0
def create(self, description, level=AlertLevel.fatal):
self.level = level
self.description = description
return self
def parse(self, p):
p.setLengthCheck(2)
self.level = p.get(1)
self.description = p.get(1)
p.stopLengthCheck()
return self
def write(self):
w = Writer()
w.add(self.level, 1)
w.add(self.description, 1)
return w.bytes
@property
def levelName(self):
matching = [x[0] for x in AlertLevel.__dict__.items()
if x[1] == self.level]
if len(matching) == 0:
return "unknown({0})".format(self.level)
else:
return str(matching[0])
@property
def descriptionName(self):
matching = [x[0] for x in AlertDescription.__dict__.items()
if x[1] == self.description]
if len(matching) == 0:
return "unknown({0})".format(self.description)
else:
return str(matching[0])
def __str__(self):
return "Alert, level:{0}, description:{1}".format(self.levelName,
self.descriptionName)
def __repr__(self):
return "Alert(level={0}, description={1})".format(self.level,
self.description)
class HandshakeMsg(object):
def __init__(self, handshakeType):
self.contentType = ContentType.handshake
self.handshakeType = handshakeType
def postWrite(self, w):
headerWriter = Writer()
headerWriter.add(self.handshakeType, 1)
headerWriter.add(len(w.bytes), 3)
return headerWriter.bytes + w.bytes
class ClientHello(HandshakeMsg):
"""
Class for handling the ClientHello TLS message, supports both the SSLv2
and SSLv3 style messages.
@type certificate_types: list
@ivar certificate_types: list of supported certificate types (deprecated)
@type srp_username: bytearray
@ivar srp_username: name of the user in SRP extension (deprecated)
@type supports_npn: boolean
@ivar supports_npn: NPN extension presence (deprecated)
@type tack: boolean
@ivar tack: TACK extension presence (deprecated)
@type server_name: bytearray
@ivar server_name: first host_name (type 0) present in SNI extension
(deprecated)
@type extensions: list of L{TLSExtension}
@ivar extensions: list of TLS extensions parsed from wire or to send, see
L{TLSExtension} and child classes for exact examples
"""
def __init__(self, ssl2=False):
HandshakeMsg.__init__(self, HandshakeType.client_hello)
self.ssl2 = ssl2
self.client_version = (0,0)
self.random = bytearray(32)
self.session_id = bytearray(0)
self.cipher_suites = [] # a list of 16-bit values
self.compression_methods = [] # a list of 8-bit values
self.extensions = None
def __str__(self):
"""
Return human readable representation of Client Hello
@rtype: str
"""
if self.session_id.count(bytearray(b'\x00')) == len(self.session_id)\
and len(self.session_id) != 0:
session = "bytearray(b'\\x00'*{0})".format(len(self.session_id))
else:
session = repr(self.session_id)
ret = "client_hello,version({0[0]}.{0[1]}),random(...),"\
"session ID({1!s}),cipher suites({2!r}),"\
"compression methods({3!r})".format(
self.client_version, session,
self.cipher_suites, self.compression_methods)
if self.extensions is not None:
ret += ",extensions({0!r})".format(self.extensions)
return ret
def __repr__(self):
"""
Return machine readable representation of Client Hello
@rtype: str
"""
return "ClientHello(ssl2={0}, client_version=({1[0]}.{1[1]}), "\
"random={2!r}, session_id={3!r}, cipher_suites={4!r}, "\
"compression_methods={5}, extensions={6})".format(\
self.ssl2, self.client_version, self.random, self.session_id,
self.cipher_suites, self.compression_methods, self.extensions)
def getExtension(self, extType):
"""
Returns extension of given type if present, None otherwise
@rtype: L{tlslite.extensions.TLSExtension}
@raise TLSInternalError: when there are multiple extensions of the
same type
"""
if self.extensions is None:
return None
exts = [ext for ext in self.extensions if ext.extType == extType]
if len(exts) > 1:
raise TLSInternalError(
"Multiple extensions of the same type present")
elif len(exts) == 1:
return exts[0]
else:
return None
def addExtension(self, ext):
"""
Adds extension to internal list of extensions
@type ext: TLSExtension
@param ext: extension object to add to list
"""
if self.extensions is None:
self.extensions = []
self.extensions.append(ext)
@property
def certificate_types(self):
"""
Returns the list of certificate types supported.
@deprecated: use extensions field to get the extension for inspection
"""
cert_type = self.getExtension(ExtensionType.cert_type)
if cert_type is None:
# XXX backwards compatibility: TLSConnection
# depends on a default value of this property
return [CertificateType.x509]
else:
return cert_type.certTypes
@certificate_types.setter
def certificate_types(self, val):
"""
Sets the list of supported types to list given in L{val} if the
cert_type extension is present. Creates the extension and places it
last in the list otherwise.
@type val: list
@param val: list of supported certificate types by client encoded as
single byte integers
"""
cert_type = self.getExtension(ExtensionType.cert_type)
if cert_type is None:
ext = ClientCertTypeExtension().create(val)
self.addExtension(ext)
else:
cert_type.certTypes = val
@property
def srp_username(self):
"""
Returns username for the SRP.
@deprecated: use extensions field to get the extension for inspection
"""
srp_ext = self.getExtension(ExtensionType.srp)
if srp_ext is None:
return None
else:
return srp_ext.identity
@srp_username.setter
def srp_username(self, name):
"""
Sets the username for SRP.
@type name: bytearray
@param name: UTF-8 encoded username
"""
srp_ext = self.getExtension(ExtensionType.srp)
if srp_ext is None:
ext = SRPExtension().create(name)
self.addExtension(ext)
else:
srp_ext.identity = name
@property
def tack(self):
"""
Returns whatever the client supports TACK
@rtype: boolean
@deprecated: use extensions field to get the extension for inspection
"""
tack_ext = self.getExtension(ExtensionType.tack)
if tack_ext is None:
return False
else:
return True
@tack.setter
def tack(self, present):
"""
Creates or deletes the TACK extension.
@type present: boolean
@param present: True will create extension while False will remove
extension from client hello
"""
if present:
tack_ext = self.getExtension(ExtensionType.tack)
if tack_ext is None:
ext = TLSExtension().create(ExtensionType.tack, bytearray(0))
self.addExtension(ext)
else:
return
else:
if self.extensions is None:
return
# remove all extensions of this type without changing reference
self.extensions[:] = [ext for ext in self.extensions if
ext.extType != ExtensionType.tack]
@property
def supports_npn(self):
"""
Returns whatever client supports NPN extension
@rtype: boolean
@deprecated: use extensions field to get the extension for inspection
"""
npn_ext = self.getExtension(ExtensionType.supports_npn)
if npn_ext is None:
return False
else:
return True
@supports_npn.setter
def supports_npn(self, present):
"""
Creates or deletes the NPN extension
@type present: boolean
@param present: selects whatever to create or remove the extension
from list of supported ones
"""
if present:
npn_ext = self.getExtension(ExtensionType.supports_npn)
if npn_ext is None:
ext = TLSExtension().create(
ExtensionType.supports_npn,
bytearray(0))
self.addExtension(ext)
else:
return
else:
if self.extensions is None:
return
#remove all extension of this type without changing reference
self.extensions[:] = [ext for ext in self.extensions if
ext.extType != ExtensionType.supports_npn]
@property
def server_name(self):
"""
Returns first host_name present in SNI extension
@rtype: bytearray
@deprecated: use extensions field to get the extension for inspection
"""
sni_ext = self.getExtension(ExtensionType.server_name)
if sni_ext is None:
return bytearray(0)
else:
if len(sni_ext.hostNames) > 0:
return sni_ext.hostNames[0]
else:
return bytearray(0)
@server_name.setter
def server_name(self, hostname):
"""
Sets the first host_name present in SNI extension
@type hostname: bytearray
@param hostname: name of the host_name to set
"""
sni_ext = self.getExtension(ExtensionType.server_name)
if sni_ext is None:
sni_ext = SNIExtension().create(hostname)
self.addExtension(sni_ext)
else:
names = list(sni_ext.hostNames)
names[0] = hostname
sni_ext.hostNames = names
def create(self, version, random, session_id, cipher_suites,
certificate_types=None, srpUsername=None,
tack=False, supports_npn=False, serverName=None,
extensions=None):
"""
Create a ClientHello message for sending.
@type version: tuple
@param version: the highest supported TLS version encoded as two int
tuple
@type random: bytearray
@param random: client provided random value, in old versions of TLS
(before 1.2) the first 32 bits should include system time
@type session_id: bytearray
@param session_id: ID of session, set when doing session resumption
@type cipher_suites: list
@param cipher_suites: list of ciphersuites advertised as supported
@type certificate_types: list
@param certificate_types: list of supported certificate types, uses
TLS extension for signalling, as such requires TLS1.0 to work
@type srpUsername: bytearray
@param srpUsername: utf-8 encoded username for SRP, TLS extension
@type tack: boolean
@param tack: whatever to advertise support for TACK, TLS extension
@type supports_npn: boolean
@param supports_npn: whatever to advertise support for NPN, TLS
extension
@type serverName: bytearray
@param serverName: the hostname to request in server name indication
extension, TLS extension. Note that SNI allows to set multiple
hostnames and values that are not hostnames, use L{SNIExtension}
together with L{extensions} to use it.
@type extensions: list of L{TLSExtension}
@param extensions: list of extensions to advertise
"""
self.client_version = version
self.random = random
self.session_id = session_id
self.cipher_suites = cipher_suites
self.compression_methods = [0]
if not extensions is None:
self.extensions = extensions
if not certificate_types is None:
self.certificate_types = certificate_types
if not srpUsername is None:
self.srp_username = bytearray(srpUsername, "utf-8")
self.tack = tack
self.supports_npn = supports_npn
if not serverName is None:
self.server_name = bytearray(serverName, "utf-8")
return self
def parse(self, p):
if self.ssl2:
self.client_version = (p.get(1), p.get(1))
cipherSpecsLength = p.get(2)
sessionIDLength = p.get(2)
randomLength = p.get(2)
self.cipher_suites = p.getFixList(3, cipherSpecsLength//3)
self.session_id = p.getFixBytes(sessionIDLength)
self.random = p.getFixBytes(randomLength)
if len(self.random) < 32:
zeroBytes = 32-len(self.random)
self.random = bytearray(zeroBytes) + self.random
self.compression_methods = [0]#Fake this value
#We're not doing a stopLengthCheck() for SSLv2, oh well..
else:
p.startLengthCheck(3)
self.client_version = (p.get(1), p.get(1))
self.random = p.getFixBytes(32)
self.session_id = p.getVarBytes(1)
self.cipher_suites = p.getVarList(2, 2)
self.compression_methods = p.getVarList(1, 1)
if not p.atLengthCheck():
self.extensions = []
totalExtLength = p.get(2)
while not p.atLengthCheck():
ext = TLSExtension().parse(p)
self.extensions += [ext]
p.stopLengthCheck()
return self
def write(self):
w = Writer()
w.add(self.client_version[0], 1)
w.add(self.client_version[1], 1)
w.addFixSeq(self.random, 1)
w.addVarSeq(self.session_id, 1, 1)
w.addVarSeq(self.cipher_suites, 2, 2)
w.addVarSeq(self.compression_methods, 1, 1)
if not self.extensions is None:
w2 = Writer()
for ext in self.extensions:
w2.bytes += ext.write()
w.add(len(w2.bytes), 2)
w.bytes += w2.bytes
return self.postWrite(w)
class ServerHello(HandshakeMsg):
"""server_hello message
@type server_version: tuple
@ivar server_version: protocol version encoded as two int tuple
@type random: bytearray
@ivar random: server random value
@type session_id: bytearray
@ivar session_id: session identifier for resumption
@type cipher_suite: int
@ivar cipher_suite: server selected cipher_suite
@type compression_method: int
@ivar compression_method: server selected compression method
@type next_protos: list of bytearray
@ivar next_protos: list of advertised protocols in NPN extension
@type next_protos_advertised: list of bytearray
@ivar next_protos_advertised: list of protocols advertised in NPN extension
@type certificate_type: int
@ivar certificate_type: certificate type selected by server
@type extensions: list
@ivar extensions: list of TLS extensions present in server_hello message,
see L{TLSExtension} and child classes for exact examples
"""
def __init__(self):
"""Initialise ServerHello object"""
HandshakeMsg.__init__(self, HandshakeType.server_hello)
self.server_version = (0,0)
self.random = bytearray(32)
self.session_id = bytearray(0)
self.cipher_suite = 0
self.compression_method = 0
self._tack_ext = None
self.extensions = None
def __str__(self):
base = "server_hello,length({0}),version({1[0]}.{1[1]}),random(...),"\
"session ID({2!r}),cipher({3:#x}),compression method({4})"\
.format(len(self.write())-4, self.server_version,
self.session_id, self.cipher_suite,
self.compression_method)
if self.extensions is None:
return base
ret = ",extensions["
ret += ",".join(repr(x) for x in self.extensions)
ret += "]"
return base + ret
def __repr__(self):
return "ServerHello(server_version=({0[0]}.{0[1]}), random={1!r}, "\
"session_id={2!r}, cipher_suite={3}, compression_method={4}, "\
"_tack_ext={5}, extensions={6!r})".format(\
self.server_version, self.random, self.session_id,
self.cipher_suite, self.compression_method, self._tack_ext,
self.extensions)
def getExtension(self, extType):
"""Return extension of a given type, None if extension of given type
is not present
@rtype: L{TLSExtension}
@raise TLSInternalError: multiple extensions of the same type present
"""
if self.extensions is None:
return None
exts = [ext for ext in self.extensions if ext.extType == extType]
if len(exts) > 1:
raise TLSInternalError(
"Multiple extensions of the same type present")
elif len(exts) == 1:
return exts[0]
else:
return None
def addExtension(self, ext):
"""
Add extension to internal list of extensions
@type ext: TLSExtension
@param ext: extension to add to list
"""
if self.extensions is None:
self.extensions = []
self.extensions.append(ext)
@property
def tackExt(self):
""" Returns the TACK extension
"""
if self._tack_ext is None:
ext = self.getExtension(ExtensionType.tack)
if ext is None or not tackpyLoaded:
return None
else:
self._tack_ext = TackExtension(ext.extData)
return self._tack_ext
@tackExt.setter
def tackExt(self, val):
""" Set the TACK extension
"""
self._tack_ext = val
# makes sure that extensions are included in the on the wire encoding
if not val is None:
if self.extensions is None:
self.extensions = []
@property
def certificate_type(self):
"""Returns the certificate type selected by server
@rtype: int
"""
cert_type = self.getExtension(ExtensionType.cert_type)
if cert_type is None:
# XXX backwards compatibility, TLSConnection expects the default
# value to be that
return CertificateType.x509
return cert_type.cert_type
@certificate_type.setter
def certificate_type(self, val):
"""Sets the certificate type supported
@type val: int
@param val: type of certificate
"""
# XXX backwards compatibility, 0 means x.509 and should not be sent
if val == 0 or val is None:
return
cert_type = self.getExtension(ExtensionType.cert_type)
if cert_type is None:
ext = ServerCertTypeExtension().create(val)
self.addExtension(ext)
else:
cert_type.cert_type = val
@property
def next_protos(self):
"""Returns the advertised protocols in NPN extension
@rtype: list of bytearrays
"""
npn_ext = self.getExtension(ExtensionType.supports_npn)
if npn_ext is None:
return None
else:
return npn_ext.protocols
@next_protos.setter
def next_protos(self, val):
"""Sets the advertised protocols in NPN extension
@type val: list
@param val: list of protocols to advertise as UTF-8 encoded names
"""
if val is None:
return
else:
# convinience function, make sure the values are properly encoded
val = [ bytearray(x) for x in val ]
npn_ext = self.getExtension(ExtensionType.supports_npn)
if npn_ext is None:
ext = NPNExtension().create(val)
self.addExtension(ext)
else:
npn_ext.protocols = val
@property
def next_protos_advertised(self):
"""Returns the advertised protocols in NPN extension
@rtype: list of bytearrays
"""
return self.next_protos
@next_protos_advertised.setter
def next_protos_advertised(self, val):
"""Sets the advertised protocols in NPN extension
@type val: list
@param val: list of protocols to advertise as UTF-8 encoded names
"""
self.next_protos = val
def create(self, version, random, session_id, cipher_suite,
certificate_type=None, tackExt=None, next_protos_advertised=None,
extensions=None):
"""Initialize the object for deserialisation"""
self.extensions = extensions
self.server_version = version
self.random = random
self.session_id = session_id
self.cipher_suite = cipher_suite
self.certificate_type = certificate_type
self.compression_method = 0
if tackExt is not None:
self.tackExt = tackExt
self.next_protos_advertised = next_protos_advertised
return self
def parse(self, p):
p.startLengthCheck(3)
self.server_version = (p.get(1), p.get(1))
self.random = p.getFixBytes(32)
self.session_id = p.getVarBytes(1)
self.cipher_suite = p.get(2)
self.compression_method = p.get(1)
if not p.atLengthCheck():
self.extensions = []
totalExtLength = p.get(2)
p2 = Parser(p.getFixBytes(totalExtLength))
while p2.getRemainingLength() > 0:
ext = TLSExtension(server=True).parse(p2)
self.extensions += [ext]
p.stopLengthCheck()
return self
def write(self):
w = Writer()
w.add(self.server_version[0], 1)
w.add(self.server_version[1], 1)
w.addFixSeq(self.random, 1)
w.addVarSeq(self.session_id, 1, 1)
w.add(self.cipher_suite, 2)
w.add(self.compression_method, 1)
if not self.extensions is None:
w2 = Writer()
for ext in self.extensions:
w2.bytes += ext.write()
if self.tackExt:
b = self.tackExt.serialize()
w2.add(ExtensionType.tack, 2)
w2.add(len(b), 2)
w2.bytes += b
w.add(len(w2.bytes), 2)
w.bytes += w2.bytes
return self.postWrite(w)
class Certificate(HandshakeMsg):
def __init__(self, certificateType):
HandshakeMsg.__init__(self, HandshakeType.certificate)
self.certificateType = certificateType
self.certChain = None
def create(self, certChain):
self.certChain = certChain
return self
def parse(self, p):
p.startLengthCheck(3)
if self.certificateType == CertificateType.x509:
chainLength = p.get(3)
index = 0
certificate_list = []
while index != chainLength:
certBytes = p.getVarBytes(3)
x509 = X509()
x509.parseBinary(certBytes)
certificate_list.append(x509)
index += len(certBytes)+3
if certificate_list:
self.certChain = X509CertChain(certificate_list)
else:
raise AssertionError()
p.stopLengthCheck()
return self
def write(self):
w = Writer()
if self.certificateType == CertificateType.x509:
chainLength = 0
if self.certChain:
certificate_list = self.certChain.x509List
else:
certificate_list = []
#determine length
for cert in certificate_list:
bytes = cert.writeBytes()
chainLength += len(bytes)+3
#add bytes
w.add(chainLength, 3)
for cert in certificate_list:
bytes = cert.writeBytes()
w.addVarSeq(bytes, 1, 3)
else:
raise AssertionError()
return self.postWrite(w)
class CertificateRequest(HandshakeMsg):
def __init__(self, version):
HandshakeMsg.__init__(self, HandshakeType.certificate_request)
self.certificate_types = []
self.certificate_authorities = []
self.version = version
self.supported_signature_algs = []
def create(self, certificate_types, certificate_authorities, sig_algs=()):
self.certificate_types = certificate_types
self.certificate_authorities = certificate_authorities
self.supported_signature_algs = sig_algs
return self
def parse(self, p):
p.startLengthCheck(3)
self.certificate_types = p.getVarList(1, 1)
if self.version >= (3,3):
self.supported_signature_algs = p.getVarTupleList(1, 2, 2)
ca_list_length = p.get(2)
index = 0
self.certificate_authorities = []
while index != ca_list_length:
ca_bytes = p.getVarBytes(2)
self.certificate_authorities.append(ca_bytes)
index += len(ca_bytes)+2
p.stopLengthCheck()
return self
def write(self):
w = Writer()
w.addVarSeq(self.certificate_types, 1, 1)
if self.version >= (3,3):
w.addVarTupleSeq(self.supported_signature_algs, 1, 2)
caLength = 0
#determine length
for ca_dn in self.certificate_authorities:
caLength += len(ca_dn)+2
w.add(caLength, 2)
#add bytes
for ca_dn in self.certificate_authorities:
w.addVarSeq(ca_dn, 1, 2)
return self.postWrite(w)
class ServerKeyExchange(HandshakeMsg):
"""
Handling TLS Handshake protocol Server Key Exchange messages
@type cipherSuite: int
@cvar cipherSuite: id of ciphersuite selected in Server Hello message
@type srp_N: int
@cvar srp_N: SRP protocol prime
@type srp_g: int
@cvar srp_g: SRP protocol generator
@type srp_s: bytearray
@cvar srp_s: SRP protocol salt value
@type srp_B: int
@cvar srp_B: SRP protocol server public value
@type dh_p: int
@cvar dh_p: FFDHE protocol prime
@type dh_g: int
@cvar dh_g: FFDHE protocol generator
@type dh_Ys: int
@cvar dh_Ys: FFDH protocol server key share
@type signature: bytearray
@cvar signature: signature performed over the parameters by server
@type hashAlg: int
@cvar hashAlg: id of hash algorithm used for signature
@type signAlg: int
@cvar signAlg: id of signature algorithm used for signature
"""
def __init__(self, cipherSuite, version):
"""
Initialise Server Key Exchange for reading or writing
@type cipherSuite: int
@param cipherSuite: id of ciphersuite selected by server
"""
HandshakeMsg.__init__(self, HandshakeType.server_key_exchange)
self.cipherSuite = cipherSuite
self.version = version
self.srp_N = 0
self.srp_g = 0
self.srp_s = bytearray(0)
self.srp_B = 0
# Anon DH params:
self.dh_p = 0
self.dh_g = 0
self.dh_Ys = 0
# signature for certificate authenticated ciphersuites
self.signature = bytearray(0)
# signature hash algorithm and signing algorithm for TLSv1.2
self.hashAlg = 0
self.signAlg = 0
def __repr__(self):
ret = "ServerKeyExchange(cipherSuite=CipherSuite.{0}, version={1}"\
"".format(CipherSuite.ietfNames[self.cipherSuite], self.version)
if self.srp_N != 0:
ret += ", srp_N={0}, srp_g={1}, srp_s={2!r}, srp_B={3}".format(\
self.srp_N, self.srp_g, self.srp_s, self.srp_B)
if self.dh_p != 0:
ret += ", dh_p={0}, dh_g={1}, dh_Ys={2}".format(\
self.dh_p, self.dh_g, self.dh_Ys)
if self.signAlg != 0:
ret += ", hashAlg={0}, signAlg={1}".format(\
self.hashAlg, self.signAlg)
if self.signature != bytearray(0):
ret += ", signature={0!r}".format(self.signature)
ret += ")"
return ret
def createSRP(self, srp_N, srp_g, srp_s, srp_B):
"""Set SRP protocol parameters"""
self.srp_N = srp_N
self.srp_g = srp_g
self.srp_s = srp_s
self.srp_B = srp_B
return self
def createDH(self, dh_p, dh_g, dh_Ys):
"""Set FFDH protocol parameters"""
self.dh_p = dh_p
self.dh_g = dh_g
self.dh_Ys = dh_Ys
return self
def parse(self, parser):
"""Deserialise message from L{Parser}
@type parser: L{Parser}
@param parser: parser to read data from
"""
parser.startLengthCheck(3)
if self.cipherSuite in CipherSuite.srpAllSuites:
self.srp_N = bytesToNumber(parser.getVarBytes(2))
self.srp_g = bytesToNumber(parser.getVarBytes(2))
self.srp_s = parser.getVarBytes(1)
self.srp_B = bytesToNumber(parser.getVarBytes(2))
elif self.cipherSuite in CipherSuite.dhAllSuites:
self.dh_p = bytesToNumber(parser.getVarBytes(2))
self.dh_g = bytesToNumber(parser.getVarBytes(2))
self.dh_Ys = bytesToNumber(parser.getVarBytes(2))
else:
raise AssertionError()
if self.cipherSuite in CipherSuite.certAllSuites:
if self.version == (3, 3):
self.hashAlg = parser.get(1)
self.signAlg = parser.get(1)
self.signature = parser.getVarBytes(2)
parser.stopLengthCheck()
return self
def writeParams(self):
"""Serialise the key exchange parameters
@rtype: bytearray
"""
writer = Writer()
if self.cipherSuite in CipherSuite.srpAllSuites:
writer.addVarSeq(numberToByteArray(self.srp_N), 1, 2)
writer.addVarSeq(numberToByteArray(self.srp_g), 1, 2)
writer.addVarSeq(self.srp_s, 1, 1)
writer.addVarSeq(numberToByteArray(self.srp_B), 1, 2)
elif self.cipherSuite in CipherSuite.dhAllSuites:
writer.addVarSeq(numberToByteArray(self.dh_p), 1, 2)
writer.addVarSeq(numberToByteArray(self.dh_g), 1, 2)
writer.addVarSeq(numberToByteArray(self.dh_Ys), 1, 2)
else:
assert(False)
return writer.bytes
def write(self):
"""
Serialise complete message
@rtype: bytearray
"""
writer = Writer()
writer.bytes += self.writeParams()
if self.cipherSuite in CipherSuite.certAllSuites:
if self.version >= (3, 3):
assert self.hashAlg != 0 and self.signAlg != 0
writer.add(self.hashAlg, 1)
writer.add(self.signAlg, 1)
writer.addVarSeq(self.signature, 1, 2)
return self.postWrite(writer)
def hash(self, clientRandom, serverRandom):
"""
Calculate hash of paramters to sign
@rtype: bytearray
"""
bytesToHash = clientRandom + serverRandom + self.writeParams()
if self.version >= (3, 3):
# TODO: Signature algorithm negotiation not supported.
return SHA1(bytesToHash)
return MD5(bytesToHash) + SHA1(bytesToHash)
class ServerHelloDone(HandshakeMsg):
def __init__(self):
HandshakeMsg.__init__(self, HandshakeType.server_hello_done)
def create(self):
return self
def parse(self, p):
p.startLengthCheck(3)
p.stopLengthCheck()
return self
def write(self):
w = Writer()
return self.postWrite(w)
class ClientKeyExchange(HandshakeMsg):
"""
Handling of TLS Handshake protocol ClientKeyExchange message
@type cipherSuite: int
@ivar cipherSuite: the cipher suite id used for the connection
@type version: tuple(int, int)
@ivar version: TLS protocol version used for the connection
@type srp_A: int
@ivar srp_A: SRP protocol client answer value
@type dh_Yc: int
@ivar dh_Yc: client Finite Field Diffie-Hellman protocol key share
@type encryptedPreMasterSecret: bytearray
@ivar encryptedPreMasterSecret: client selected PremMaster secret encrypted
with server public key (from certificate)
"""
def __init__(self, cipherSuite, version=None):
"""
Initialise ClientKeyExchange for reading or writing
@type cipherSuite: int
@param cipherSuite: id of the ciphersuite selected by server
@type version: tuple(int, int)
@param version: protocol version selected by server
"""
HandshakeMsg.__init__(self, HandshakeType.client_key_exchange)
self.cipherSuite = cipherSuite
self.version = version
self.srp_A = 0
self.dh_Yc = 0
self.encryptedPreMasterSecret = bytearray(0)
def createSRP(self, srp_A):
"""
Set the SRP client answer
returns self
@type srp_A: int
@param srp_A: client SRP answer
@rtype: L{ClientKeyExchange}
"""
self.srp_A = srp_A
return self
def createRSA(self, encryptedPreMasterSecret):
"""
Set the encrypted PreMaster Secret
returns self
@type encryptedPreMasterSecret: bytearray
@rtype: L{ClientKeyExchange}
"""
self.encryptedPreMasterSecret = encryptedPreMasterSecret
return self
def createDH(self, dh_Yc):
"""
Set the client FFDH key share
returns self
@type dh_Yc: int
@rtype: L{ClientKeyExchange}
"""
self.dh_Yc = dh_Yc
return self
def parse(self, parser):
"""
Deserialise the message from L{Parser}
returns self
@type parser: L{Parser}
@rtype: L{ClientKeyExchange}
"""
parser.startLengthCheck(3)
if self.cipherSuite in CipherSuite.srpAllSuites:
self.srp_A = bytesToNumber(parser.getVarBytes(2))
elif self.cipherSuite in CipherSuite.certSuites:
if self.version in ((3,1), (3,2), (3,3)):
self.encryptedPreMasterSecret = parser.getVarBytes(2)
elif self.version == (3,0):
self.encryptedPreMasterSecret = \
parser.getFixBytes(parser.getRemainingLength())
else:
raise AssertionError()
elif self.cipherSuite in CipherSuite.dhAllSuites:
self.dh_Yc = bytesToNumber(parser.getVarBytes(2))
else:
raise AssertionError()
parser.stopLengthCheck()
return self
def write(self):
"""
Serialise the object
@rtype: bytearray
"""
w = Writer()
if self.cipherSuite in CipherSuite.srpAllSuites:
w.addVarSeq(numberToByteArray(self.srp_A), 1, 2)
elif self.cipherSuite in CipherSuite.certSuites:
if self.version in ((3,1), (3,2), (3,3)):
w.addVarSeq(self.encryptedPreMasterSecret, 1, 2)
elif self.version == (3,0):
w.addFixSeq(self.encryptedPreMasterSecret, 1)
else:
raise AssertionError()
elif self.cipherSuite in CipherSuite.dhAllSuites:
w.addVarSeq(numberToByteArray(self.dh_Yc), 1, 2)
else:
raise AssertionError()
return self.postWrite(w)
class CertificateVerify(HandshakeMsg):
"""Serializer for TLS handshake protocol Certificate Verify message"""
def __init__(self, version):
"""Create message
@param version: TLS protocol version in use
"""
HandshakeMsg.__init__(self, HandshakeType.certificate_verify)
self.version = version
self.signatureAlgorithm = None
self.signature = bytearray(0)
def create(self, signature, signatureAlgorithm=None):
"""
Provide data for serialisation of message
@param signature: signature carried in the message
@param signatureAlgorithm: signature algorithm used to make the
signature (TLSv1.2 only)
"""
self.signatureAlgorithm = signatureAlgorithm
self.signature = signature
return self
def parse(self, parser):
"""
Deserialize message from parser
@param parser: parser with data to read
"""
parser.startLengthCheck(3)
if self.version >= (3, 3):
self.signatureAlgorithm = (parser.get(1), parser.get(1))
self.signature = parser.getVarBytes(2)
parser.stopLengthCheck()
return self
def write(self):
"""
Serialize the data to bytearray
@rtype: bytearray
"""
writer = Writer()
if self.version >= (3, 3):
writer.add(self.signatureAlgorithm[0], 1)
writer.add(self.signatureAlgorithm[1], 1)
writer.addVarSeq(self.signature, 1, 2)
return self.postWrite(writer)
class ChangeCipherSpec(object):
def __init__(self):
self.contentType = ContentType.change_cipher_spec
self.type = 1
def create(self):
self.type = 1
return self
def parse(self, p):
p.setLengthCheck(1)
self.type = p.get(1)
p.stopLengthCheck()
return self
def write(self):
w = Writer()
w.add(self.type,1)
return w.bytes
class NextProtocol(HandshakeMsg):
def __init__(self):
HandshakeMsg.__init__(self, HandshakeType.next_protocol)
self.next_proto = None
def create(self, next_proto):
self.next_proto = next_proto
return self
def parse(self, p):
p.startLengthCheck(3)
self.next_proto = p.getVarBytes(1)
_ = p.getVarBytes(1)
p.stopLengthCheck()
return self
def write(self, trial=False):
w = Writer()
w.addVarSeq(self.next_proto, 1, 1)
paddingLen = 32 - ((len(self.next_proto) + 2) % 32)
w.addVarSeq(bytearray(paddingLen), 1, 1)
return self.postWrite(w)
class Finished(HandshakeMsg):
def __init__(self, version):
HandshakeMsg.__init__(self, HandshakeType.finished)
self.version = version
self.verify_data = bytearray(0)
def create(self, verify_data):
self.verify_data = verify_data
return self
def parse(self, p):
p.startLengthCheck(3)
if self.version == (3,0):
self.verify_data = p.getFixBytes(36)
elif self.version in ((3,1), (3,2), (3,3)):
self.verify_data = p.getFixBytes(12)
else:
raise AssertionError()
p.stopLengthCheck()
return self
def write(self):
w = Writer()
w.addFixSeq(self.verify_data, 1)
return self.postWrite(w)
class ApplicationData(object):
def __init__(self):
self.contentType = ContentType.application_data
self.bytes = bytearray(0)
def create(self, bytes):
self.bytes = bytes
return self
def splitFirstByte(self):
newMsg = ApplicationData().create(self.bytes[:1])
self.bytes = self.bytes[1:]
return newMsg
def parse(self, p):
self.bytes = p.bytes
return self
def write(self):
return self.bytes
|