导入scapy: from scapy.all import * 常用的查看命令: ls() - 不带参数则查看所有可持的layer,也可以指定一个layer名称从而查询此layer的详细详细,例如ls(TCP) lsc() - 查看当前scapy的所有功能列表 help() - 查看功能的帮助,例如help(hexdump)可以查看hexdump的作用和参数介绍 conf - 查看当前的配置信息 […]
分类: python
合并xml文件中attrib中含有相同标记的element
示例xml内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<peach> <DataModel name="test"> <String value="select" mutable="false" /> <String value=" " mutable="false" /> <String value="id" /> <String value="," mutable="false" /> <String value="name" /> <String value=" " mutable="false" /> <String value="from" mutable="false" /> <String value=" " mutable="false" /> <String value="table_for_test" /> </DataModel> </peach> |
如上这段内容,其实是peach数据模型的一段定义,今天通过脚本模拟自动建模,生成的文档含有大量的mutable="false"的内容。根据peach的描述,这一属性的意义可以让peach忽略对其进行mute操作(实际好像还是会mute),为了简洁起见,减少建模过程中的费脑,直接将数据模型定义文件中重复出现的muta […]
Python内部类通过外部类属性值传递参数一例
为了解决两个线程类通过global 变量传递数据的方法在并发情况下全局变量被覆盖的问题,不得已将两个代理类用一个class来包装,试验了许久才得出这个简单粗暴的方法,留存以备将来参考
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 |
# coding: utf-8 import threading import queue import time class MainClass: # class attribute to be used in subClass queueTest = None queueStopThread = None def __init__(self): MainClass.queueTest = queue.Queue() MainClass.queueStopThread = queue.Queue() def __del__(self): MainClass.queueTest = None MainClass.queueStopThread = None class SubClass1(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while MainClass.queueStopThread.empty(): if not MainClass.queueTest.empty(): print("{} - {}".format(threading.currentThread().ident, MainClass.queueTest.get())) print("SubClass1: queueStopThread: {}".format(MainClass.queueStopThread.get())) class SubClass2(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): for i in range(1, 10): MainClass.queueTest.put(i) time.sleep(0.1) MainClass.queueStopThread.put(True) @staticmethod def run_main(): p_subclass1 = MainClass.SubClass1() p_subclass1.daemon = True p_subclass1.start() p_subclass2 = MainClass.SubClass2() p_subclass2.daemon = True p_subclass2.start() p_subclass1.join() del p_subclass1 del p_subclass2 if __name__ == "__main__": tM1 = MainClass() tM2 = MainClass() t1 = threading.Thread(target=tM1.run_main()) t1.daemon = True t2 = threading.Thread(target=tM2.run_main()) t2.daemon = True t1.start() t2.start() main_class_test = MainClass() main_class_test.run_main() |
运行结果如下:
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 |
F:\Python\classInClass\venv\Scripts\python.exe F:/Python/classInClass/classInClass.py 14596 - 1 14596 - 2 14596 - 3 14596 - 4 14596 - 5 14596 - 6 14596 - 7 14596 - 8 14596 - 9 SubClass1: queueStopThread: True 11812 - 1 11812 - 2 11812 - 3 11812 - 4 11812 - 5 11812 - 6 11812 - 7 11812 - 8 11812 - 9 SubClass1: queueStopThread: True 11120 - 1 11120 - 2 11120 - 3 11120 - 4 11120 - 5 11120 - 6 11120 - 7 11120 - 8 11120 - 9 SubClass1: queueStopThread: True Process finished with exit code 0 |
Pyhton模拟Proxy实现MITM
参考了Python渗透测试的思路,只是修改消息传递方式为queue,固定有客户端发起链接。
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 |
# -*- coding: utf-8 -*- import socket import ssl import threading import queue import time fromCliQueue = queue.Queue() fromSrvQueue = queue.Queue() sFlag = False ## Client -- proxyServer -- proxyClient -- Server class proxyClient(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.sock = None self.ssl_context = ssl.create_default_context(cafile='RootCA.pem') self.ssl_context.load_cert_chain("Client.pem", "Client.key") self.ssl_context.protocol = ssl.PROTOCOL_TLSv1_2 self.ssl_context.check_hostname = False def run(self): global fromCliQueue global fromSrvQueue while True: #if mesg queue from client is not empty, send it to server and recv response if not fromCliQueue.empty(): if self.sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) self.sock.connect(('127.0.0.1', 9999)) else: sdata = fromCliQueue.get() print("[proxyClient]send to server: {}".format(sdata)) self.sock.send(sdata) rdata = self.sock.recv(4096) #解决recv总是收到空字符 if rdata != b'': print("[proxyClient]recv from server: {}".format(rdata)) fromSrvQueue.put(rdata) self.sslDetected(rdata) def sslDetected(self, data): if b'\x01\x00\x00\x00' in data: self.sock = self.ssl_context.wrap_socket(self.sock) print("[proxyClient]ssl neogotiation") return True else: return False class proxyServer(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('127.0.0.1',8888)) self.sock.listen(1) self.ssl_context = ssl.SSLContext() # self.ssl_context.verify_mode = ssl.CERT_REQUIRED self.ssl_context.load_verify_locations(cafile='RootCA.pem') # self.ssl_context.check_hostname = False # test this protocol with client's PROTOCOL_TLSv1_2 self.ssl_context.protocol = ssl.PROTOCOL_TLS_SERVER self.ssl_context.load_cert_chain("Server.pem", "Server.key") def run(self): global fromSrvQueue global fromCliQueue self.proxySocket, addr = self.sock.accept() while self.proxySocket: rdata = self.proxySocket.recv(4096) if rdata != b'': print("[proxyServer]recv from client: {}".format(rdata)) fromCliQueue.put(rdata) while True: if fromSrvQueue.empty(): time.sleep(1) continue else: sdata = fromSrvQueue.get() print("[proxyServer]send to client: {}".format(sdata)) self.proxySocket.send(sdata) self.sslDetected(sdata) break; def sslDetected(self, data): if b'\x01\x00\x00\x00' in data: self.proxySocket = self.ssl_context.wrap_socket(self.proxySocket, server_side=True) print("[proxyClient]ssl neogotiation") return True else: return False if __name__ == "__main__": proxyCli = proxyClient() proxyCli.daemon = True proxyCli.start() proxySrv = proxyServer() proxySrv.daemon = True proxySrv.start() proxySrv.join() |
sslDetected的作用是为了匹配某种特殊的情况: client-server先交互一些普通socket数据,然后开始ssl协商 假设已经获取server端和客户端的证书,此Proxy脚本可以伪造客户端和服务端,实现MITM的场景。 如果 […]
ssl协商过程抓包内容
Client Hello
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 |
Secure Sockets Layer TLSv1.2 Record Layer: Handshake Protocol: Client Hello Content Type: Handshake (22) Version: TLS 1.0 (0x0301) Length: 136 Handshake Protocol: Client Hello Handshake Type: Client Hello (1) Length: 132 Version: TLS 1.2 (0x0303) Random: 054b5cf0e51d0e3de9073f38cec68e4a4704059cf1e03a55... GMT Unix Time: Oct 25, 1972 09:37:52.000000000 CST Random Bytes: e51d0e3de9073f38cec68e4a4704059cf1e03a55b55ba278... Session ID Length: 0 Cipher Suites Length: 6 Cipher Suites (3 suites) Cipher Suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (0x009f) Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030) Cipher Suite: TLS_EMPTY_RENEGOTIATION_INFO_SCSV (0x00ff) Compression Methods Length: 1 Compression Methods (1 method) Compression Method: null (0) Extensions Length: 85 Extension: server_name (len=11) Type: server_name (0) Length: 11 Server Name Indication extension Server Name list length: 9 Server Name Type: host_name (0) Server Name length: 6 Server Name: Server Extension: ec_point_formats (len=4) Type: ec_point_formats (11) Length: 4 EC point formats Length: 3 Elliptic curves point formats (3) EC point format: uncompressed (0) EC point format: ansiX962_compressed_prime (1) EC point format: ansiX962_compressed_char2 (2) Extension: supported_groups (len=10) Type: supported_groups (10) Length: 10 Supported Groups List Length: 8 Supported Groups (4 groups) Supported Group: x25519 (0x001d) Supported Group: secp256r1 (0x0017) Supported Group: secp521r1 (0x0019) Supported Group: secp384r1 (0x0018) Extension: SessionTicket TLS (len=0) Type: SessionTicket TLS (35) Length: 0 Data (0 bytes) Extension: encrypt_then_mac (len=0) Type: encrypt_then_mac (22) Length: 0 Extension: extended_master_secret (len=0) Type: extended_master_secret (23) Length: 0 Extension: signature_algorithms (len=32) Type: signature_algorithms (13) Length: 32 Signature Hash Algorithms Length: 30 Signature Hash Algorithms (15 algorithms) Signature Algorithm: rsa_pkcs1_sha512 (0x0601) Signature Hash Algorithm Hash: SHA512 (6) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA512 DSA (0x0602) Signature Hash Algorithm Hash: SHA512 (6) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: ecdsa_secp521r1_sha512 (0x0603) Signature Hash Algorithm Hash: SHA512 (6) Signature Hash Algorithm Signature: ECDSA (3) Signature Algorithm: rsa_pkcs1_sha384 (0x0501) Signature Hash Algorithm Hash: SHA384 (5) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA384 DSA (0x0502) Signature Hash Algorithm Hash: SHA384 (5) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: ecdsa_secp384r1_sha384 (0x0503) Signature Hash Algorithm Hash: SHA384 (5) Signature Hash Algorithm Signature: ECDSA (3) Signature Algorithm: rsa_pkcs1_sha256 (0x0401) Signature Hash Algorithm Hash: SHA256 (4) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA256 DSA (0x0402) Signature Hash Algorithm Hash: SHA256 (4) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: ecdsa_secp256r1_sha256 (0x0403) Signature Hash Algorithm Hash: SHA256 (4) Signature Hash Algorithm Signature: ECDSA (3) Signature Algorithm: SHA224 RSA (0x0301) Signature Hash Algorithm Hash: SHA224 (3) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA224 DSA (0x0302) Signature Hash Algorithm Hash: SHA224 (3) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: SHA224 ECDSA (0x0303) Signature Hash Algorithm Hash: SHA224 (3) Signature Hash Algorithm Signature: ECDSA (3) Signature Algorithm: rsa_pkcs1_sha1 (0x0201) Signature Hash Algorithm Hash: SHA1 (2) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA1 DSA (0x0202) Signature Hash Algorithm Hash: SHA1 (2) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: ecdsa_sha1 (0x0203) Signature Hash Algorithm Hash: SHA1 (2) Signature Hash Algorithm Signature: ECDSA (3) |
Server Hello, Certificate, Server Key Exchange, Certificate Request, Server Hello Done
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 |
Secure Sockets Layer TLSv1.2 Record Layer: Handshake Protocol: Server Hello Content Type: Handshake (22) Version: TLS 1.2 (0x0303) Length: 65 Handshake Protocol: Server Hello Handshake Type: Server Hello (2) Length: 61 Version: TLS 1.2 (0x0303) Random: 9bfe3e4bc92264fdcd4c99f2357653cadb5feabc944851ec... GMT Unix Time: Dec 7, 2052 04:42:51.000000000 CST Random Bytes: c92264fdcd4c99f2357653cadb5feabc944851ec7dd42fc8... Session ID Length: 0 Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030) Compression Method: null (0) Extensions Length: 21 Extension: renegotiation_info (len=1) Type: renegotiation_info (65281) Length: 1 Renegotiation Info extension Renegotiation info extension length: 0 Extension: ec_point_formats (len=4) Type: ec_point_formats (11) Length: 4 EC point formats Length: 3 Elliptic curves point formats (3) EC point format: uncompressed (0) EC point format: ansiX962_compressed_prime (1) EC point format: ansiX962_compressed_char2 (2) Extension: SessionTicket TLS (len=0) Type: SessionTicket TLS (35) Length: 0 Data (0 bytes) Extension: extended_master_secret (len=0) Type: extended_master_secret (23) Length: 0 TLSv1.2 Record Layer: Handshake Protocol: Certificate Content Type: Handshake (22) Version: TLS 1.2 (0x0303) Length: 2010 Handshake Protocol: Certificate Handshake Type: Certificate (11) Length: 2006 Certificates Length: 2003 Certificates (2003 bytes) Certificate Length: 1009 Certificate: 308203ed308202d5a003020102020101300d06092a864886... (pkcs-9-at-emailAddress=RootCA0@lzu.cn,id-at-commonName=Server,id-at-organizationalUnitName=ETS,id-at-organizationName=LZUiversity,id-at-localityName=LZ,id-at-stateOrProvince signedCertificate version: v3 (2) serialNumber: 1 signature (sha256WithRSAEncryption) Algorithm Id: 1.2.840.113549.1.1.11 (sha256WithRSAEncryption) issuer: rdnSequence (0) rdnSequence: 7 items (pkcs-9-at-emailAddress=RootCA0@lzu.cn,id-at-commonName=RootCA0,id-at-organizationalUnitName=ETS,id-at-organizationName=LZUiversity,id-at-localityName=LZ,id-at-stateOrProvinceName=GS,id-at-countryName=CN) RDNSequence item: 1 item (id-at-countryName=CN) RelativeDistinguishedName item (id-at-countryName=CN) Id: 2.5.4.6 (id-at-countryName) CountryName: CN RDNSequence item: 1 item (id-at-stateOrProvinceName=GS) RelativeDistinguishedName item (id-at-stateOrProvinceName=GS) Id: 2.5.4.8 (id-at-stateOrProvinceName) DirectoryString: uTF8String (4) uTF8String: GS RDNSequence item: 1 item (id-at-localityName=LZ) RelativeDistinguishedName item (id-at-localityName=LZ) Id: 2.5.4.7 (id-at-localityName) DirectoryString: uTF8String (4) uTF8String: LZ RDNSequence item: 1 item (id-at-organizationName=LZUiversity) RelativeDistinguishedName item (id-at-organizationName=LZUiversity) Id: 2.5.4.10 (id-at-organizationName) DirectoryString: uTF8String (4) uTF8String: LZUiversity RDNSequence item: 1 item (id-at-organizationalUnitName=ETS) RelativeDistinguishedName item (id-at-organizationalUnitName=ETS) Id: 2.5.4.11 (id-at-organizationalUnitName) DirectoryString: uTF8String (4) uTF8String: ETS RDNSequence item: 1 item (id-at-commonName=RootCA0) RelativeDistinguishedName item (id-at-commonName=RootCA0) Id: 2.5.4.3 (id-at-commonName) DirectoryString: uTF8String (4) uTF8String: RootCA0 RDNSequence item: 1 item (pkcs-9-at-emailAddress=RootCA0@lzu.cn) RelativeDistinguishedName item (pkcs-9-at-emailAddress=RootCA0@lzu.cn) Id: 1.2.840.113549.1.9.1 (pkcs-9-at-emailAddress) IA5String: RootCA0@lzu.cn validity notBefore: utcTime (0) utcTime: 18-10-07 08:49:47 (UTC) notAfter: utcTime (0) utcTime: 19-10-07 08:49:47 (UTC) subject: rdnSequence (0) rdnSequence: 7 items (pkcs-9-at-emailAddress=RootCA0@lzu.cn,id-at-commonName=Server,id-at-organizationalUnitName=ETS,id-at-organizationName=LZUiversity,id-at-localityName=LZ,id-at-stateOrProvinceName=GS,id-at-countryName=CN) RDNSequence item: 1 item (id-at-countryName=CN) RelativeDistinguishedName item (id-at-countryName=CN) Id: 2.5.4.6 (id-at-countryName) CountryName: CN RDNSequence item: 1 item (id-at-stateOrProvinceName=GS) RelativeDistinguishedName item (id-at-stateOrProvinceName=GS) Id: 2.5.4.8 (id-at-stateOrProvinceName) DirectoryString: uTF8String (4) uTF8String: GS RDNSequence item: 1 item (id-at-localityName=LZ) RelativeDistinguishedName item (id-at-localityName=LZ) Id: 2.5.4.7 (id-at-localityName) DirectoryString: uTF8String (4) uTF8String: LZ RDNSequence item: 1 item (id-at-organizationName=LZUiversity) RelativeDistinguishedName item (id-at-organizationName=LZUiversity) Id: 2.5.4.10 (id-at-organizationName) DirectoryString: uTF8String (4) uTF8String: LZUiversity RDNSequence item: 1 item (id-at-organizationalUnitName=ETS) RelativeDistinguishedName item (id-at-organizationalUnitName=ETS) Id: 2.5.4.11 (id-at-organizationalUnitName) DirectoryString: uTF8String (4) uTF8String: ETS RDNSequence item: 1 item (id-at-commonName=Server) RelativeDistinguishedName item (id-at-commonName=Server) Id: 2.5.4.3 (id-at-commonName) DirectoryString: uTF8String (4) uTF8String: Server RDNSequence item: 1 item (pkcs-9-at-emailAddress=RootCA0@lzu.cn) RelativeDistinguishedName item (pkcs-9-at-emailAddress=RootCA0@lzu.cn) Id: 1.2.840.113549.1.9.1 (pkcs-9-at-emailAddress) IA5String: RootCA0@lzu.cn subjectPublicKeyInfo algorithm (rsaEncryption) Algorithm Id: 1.2.840.113549.1.1.1 (rsaEncryption) subjectPublicKey: 3082010a0282010100c6972db88d8274b7c532bbe0d96807... modulus: 0x00c6972db88d8274b7c532bbe0d9680796f15b8f978d4b95... publicExponent: 65537 extensions: 4 items Extension (id-ce-basicConstraints) Extension Id: 2.5.29.19 (id-ce-basicConstraints) BasicConstraintsSyntax [0 length] Extension (ns_cert_exts.comment) Extension Id: 2.16.840.1.113730.1.13 (ns_cert_exts.comment) Comment: OpenSSL Generated Certificate Extension (id-ce-subjectKeyIdentifier) Extension Id: 2.5.29.14 (id-ce-subjectKeyIdentifier) SubjectKeyIdentifier: c707aa6d554dc647f60f56a89ccd94c8a6817393 Extension (id-ce-authorityKeyIdentifier) Extension Id: 2.5.29.35 (id-ce-authorityKeyIdentifier) AuthorityKeyIdentifier keyIdentifier: d1240f1fbe9c38f59d0c73b6ddce97f2b3677aad algorithmIdentifier (sha256WithRSAEncryption) Algorithm Id: 1.2.840.113549.1.1.11 (sha256WithRSAEncryption) Padding: 0 encrypted: 51fb5e7174fd39adc6e7da030ee66cabf02d616da62a2d5a... Certificate Length: 988 Certificate: 308203d8308202c0a003020102020900ec4eb6fa4339afb8... (pkcs-9-at-emailAddress=RootCA0@lzu.cn,id-at-commonName=RootCA0,id-at-organizationalUnitName=ETS,id-at-organizationName=LZUiversity,id-at-localityName=LZ,id-at-stateOrProvinc signedCertificate version: v3 (2) serialNumber: 17027748427120357304 signature (sha256WithRSAEncryption) Algorithm Id: 1.2.840.113549.1.1.11 (sha256WithRSAEncryption) issuer: rdnSequence (0) rdnSequence: 7 items (pkcs-9-at-emailAddress=RootCA0@lzu.cn,id-at-commonName=RootCA0,id-at-organizationalUnitName=ETS,id-at-organizationName=LZUiversity,id-at-localityName=LZ,id-at-stateOrProvinceName=GS,id-at-countryName=CN) RDNSequence item: 1 item (id-at-countryName=CN) RelativeDistinguishedName item (id-at-countryName=CN) Id: 2.5.4.6 (id-at-countryName) CountryName: CN RDNSequence item: 1 item (id-at-stateOrProvinceName=GS) RelativeDistinguishedName item (id-at-stateOrProvinceName=GS) Id: 2.5.4.8 (id-at-stateOrProvinceName) DirectoryString: uTF8String (4) uTF8String: GS RDNSequence item: 1 item (id-at-localityName=LZ) RelativeDistinguishedName item (id-at-localityName=LZ) Id: 2.5.4.7 (id-at-localityName) DirectoryString: uTF8String (4) uTF8String: LZ RDNSequence item: 1 item (id-at-organizationName=LZUiversity) RelativeDistinguishedName item (id-at-organizationName=LZUiversity) Id: 2.5.4.10 (id-at-organizationName) DirectoryString: uTF8String (4) uTF8String: LZUiversity RDNSequence item: 1 item (id-at-organizationalUnitName=ETS) RelativeDistinguishedName item (id-at-organizationalUnitName=ETS) Id: 2.5.4.11 (id-at-organizationalUnitName) DirectoryString: uTF8String (4) uTF8String: ETS RDNSequence item: 1 item (id-at-commonName=RootCA0) RelativeDistinguishedName item (id-at-commonName=RootCA0) Id: 2.5.4.3 (id-at-commonName) DirectoryString: uTF8String (4) uTF8String: RootCA0 RDNSequence item: 1 item (pkcs-9-at-emailAddress=RootCA0@lzu.cn) RelativeDistinguishedName item (pkcs-9-at-emailAddress=RootCA0@lzu.cn) Id: 1.2.840.113549.1.9.1 (pkcs-9-at-emailAddress) IA5String: RootCA0@lzu.cn validity notBefore: utcTime (0) utcTime: 18-10-07 08:49:46 (UTC) notAfter: utcTime (0) utcTime: 28-10-04 08:49:46 (UTC) subject: rdnSequence (0) rdnSequence: 7 items (pkcs-9-at-emailAddress=RootCA0@lzu.cn,id-at-commonName=RootCA0,id-at-organizationalUnitName=ETS,id-at-organizationName=LZUiversity,id-at-localityName=LZ,id-at-stateOrProvinceName=GS,id-at-countryName=CN) RDNSequence item: 1 item (id-at-countryName=CN) RelativeDistinguishedName item (id-at-countryName=CN) Id: 2.5.4.6 (id-at-countryName) CountryName: CN RDNSequence item: 1 item (id-at-stateOrProvinceName=GS) RelativeDistinguishedName item (id-at-stateOrProvinceName=GS) Id: 2.5.4.8 (id-at-stateOrProvinceName) DirectoryString: uTF8String (4) uTF8String: GS RDNSequence item: 1 item (id-at-localityName=LZ) RelativeDistinguishedName item (id-at-localityName=LZ) Id: 2.5.4.7 (id-at-localityName) DirectoryString: uTF8String (4) uTF8String: LZ RDNSequence item: 1 item (id-at-organizationName=LZUiversity) RelativeDistinguishedName item (id-at-organizationName=LZUiversity) Id: 2.5.4.10 (id-at-organizationName) DirectoryString: uTF8String (4) uTF8String: LZUiversity RDNSequence item: 1 item (id-at-organizationalUnitName=ETS) RelativeDistinguishedName item (id-at-organizationalUnitName=ETS) Id: 2.5.4.11 (id-at-organizationalUnitName) DirectoryString: uTF8String (4) uTF8String: ETS RDNSequence item: 1 item (id-at-commonName=RootCA0) RelativeDistinguishedName item (id-at-commonName=RootCA0) Id: 2.5.4.3 (id-at-commonName) DirectoryString: uTF8String (4) uTF8String: RootCA0 RDNSequence item: 1 item (pkcs-9-at-emailAddress=RootCA0@lzu.cn) RelativeDistinguishedName item (pkcs-9-at-emailAddress=RootCA0@lzu.cn) Id: 1.2.840.113549.1.9.1 (pkcs-9-at-emailAddress) IA5String: RootCA0@lzu.cn subjectPublicKeyInfo algorithm (rsaEncryption) Algorithm Id: 1.2.840.113549.1.1.1 (rsaEncryption) subjectPublicKey: 3082010a02820101009e1c8e2bf1ec29bd0c2af6ec915890... modulus: 0x009e1c8e2bf1ec29bd0c2af6ec915890a94fd3dead3c7183... publicExponent: 65537 extensions: 4 items Extension (id-ce-subjectKeyIdentifier) Extension Id: 2.5.29.14 (id-ce-subjectKeyIdentifier) SubjectKeyIdentifier: d1240f1fbe9c38f59d0c73b6ddce97f2b3677aad Extension (id-ce-authorityKeyIdentifier) Extension Id: 2.5.29.35 (id-ce-authorityKeyIdentifier) AuthorityKeyIdentifier keyIdentifier: d1240f1fbe9c38f59d0c73b6ddce97f2b3677aad Extension (id-ce-basicConstraints) Extension Id: 2.5.29.19 (id-ce-basicConstraints) BasicConstraintsSyntax cA: True Extension (id-ce-keyUsage) Extension Id: 2.5.29.15 (id-ce-keyUsage) Padding: 1 KeyUsage: 06 (keyCertSign, cRLSign) 0... .... = digitalSignature: False .0.. .... = contentCommitment: False ..0. .... = keyEncipherment: False ...0 .... = dataEncipherment: False .... 0... = keyAgreement: False .... .1.. = keyCertSign: True .... ..1. = cRLSign: True .... ...0 = encipherOnly: False 0... .... = decipherOnly: False algorithmIdentifier (sha256WithRSAEncryption) Algorithm Id: 1.2.840.113549.1.1.11 (sha256WithRSAEncryption) Padding: 0 encrypted: 1c79357bc723353609353cc85b1b2933067c1177b581f1d5... TLSv1.2 Record Layer: Handshake Protocol: Server Key Exchange Content Type: Handshake (22) Version: TLS 1.2 (0x0303) Length: 300 Handshake Protocol: Server Key Exchange Handshake Type: Server Key Exchange (12) Length: 296 EC Diffie-Hellman Server Params Curve Type: named_curve (0x03) Named Curve: x25519 (0x001d) Pubkey Length: 32 Pubkey: 056ead6ebe7813f5ee386917dcde72b6de5a5cb7d36b9c61... Signature Algorithm: rsa_pkcs1_sha512 (0x0601) Signature Hash Algorithm Hash: SHA512 (6) Signature Hash Algorithm Signature: RSA (1) Signature Length: 256 Signature: 2e37e2b34349df0842c999711f6500dc74e4e4c981d11281... TLSv1.2 Record Layer: Handshake Protocol: Certificate Request Content Type: Handshake (22) Version: TLS 1.2 (0x0303) Length: 42 Handshake Protocol: Certificate Request Handshake Type: Certificate Request (13) Length: 38 Certificate types count: 3 Certificate types (3 types) Certificate type: RSA Sign (1) Certificate type: DSS Sign (2) Certificate type: ECDSA Sign (64) Signature Hash Algorithms Length: 30 Signature Hash Algorithms (15 algorithms) Signature Algorithm: rsa_pkcs1_sha512 (0x0601) Signature Hash Algorithm Hash: SHA512 (6) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA512 DSA (0x0602) Signature Hash Algorithm Hash: SHA512 (6) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: ecdsa_secp521r1_sha512 (0x0603) Signature Hash Algorithm Hash: SHA512 (6) Signature Hash Algorithm Signature: ECDSA (3) Signature Algorithm: rsa_pkcs1_sha384 (0x0501) Signature Hash Algorithm Hash: SHA384 (5) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA384 DSA (0x0502) Signature Hash Algorithm Hash: SHA384 (5) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: ecdsa_secp384r1_sha384 (0x0503) Signature Hash Algorithm Hash: SHA384 (5) Signature Hash Algorithm Signature: ECDSA (3) Signature Algorithm: rsa_pkcs1_sha256 (0x0401) Signature Hash Algorithm Hash: SHA256 (4) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA256 DSA (0x0402) Signature Hash Algorithm Hash: SHA256 (4) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: ecdsa_secp256r1_sha256 (0x0403) Signature Hash Algorithm Hash: SHA256 (4) Signature Hash Algorithm Signature: ECDSA (3) Signature Algorithm: SHA224 RSA (0x0301) Signature Hash Algorithm Hash: SHA224 (3) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA224 DSA (0x0302) Signature Hash Algorithm Hash: SHA224 (3) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: SHA224 ECDSA (0x0303) Signature Hash Algorithm Hash: SHA224 (3) Signature Hash Algorithm Signature: ECDSA (3) Signature Algorithm: rsa_pkcs1_sha1 (0x0201) Signature Hash Algorithm Hash: SHA1 (2) Signature Hash Algorithm Signature: RSA (1) Signature Algorithm: SHA1 DSA (0x0202) Signature Hash Algorithm Hash: SHA1 (2) Signature Hash Algorithm Signature: DSA (2) Signature Algorithm: ecdsa_sha1 (0x0203) Signature Hash Algorithm Hash: SHA1 (2) Signature Hash Algorithm Signature: ECDSA (3) Distinguished Names Length: 0 TLSv1.2 Record Layer: Handshake Protocol: Server Hello Done Content Type: Handshake (22) Version: TLS 1.2 (0x0303) Length: 4 Handshake Protocol: Server Hello Done Handshake Type: Server Hello Done (14) Length: 0 |
Certificate, Client Key Exchange, […]
python ssl wrap
通过python可以免去编译很快速的实现ssl socket的模拟,如下server和client的示例,作为日常学习ssl的行为模式,应该是能满足了: sslServer:
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 |
import socket import ssl import sys def sslServer(host, port): # create user defined SSLContext ssl_context = ssl.SSLContext() ssl_context.verify_mode = ssl.CERT_REQUIRED ssl_context.load_verify_locations(cafile='RootCA.pem') ssl_context.check_hostname = False # test this protocol with client's PROTOCOL_TLSv1_2 ssl_context.protocol = ssl.PROTOCOL_TLS_SERVER ssl_context.load_cert_chain("Server.pem", "Server.key") cipher_suites = 'ECDHE-RSA-AES256-GCM-SHA384:AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384' ssl_context.set_ciphers(cipher_suites) try: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) # set reuse options server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((host, port)) server.listen(1) with ssl_context.wrap_socket(server, server_side=True) as ssl_server: conn, addr = ssl_server.accept() print("accept conn from %s" % str(addr)) # get the ssl cipher info print('ssl cipher: {}'.format(conn.cipher())) while conn: recv_data = conn.recv(1024) print("recv: %s" % repr(recv_data)) if not recv_data: break conn.sendall(recv_data) except Exception as e: print(e) if __name__ == '__main__': print('ssl ver: {}'.format(ssl.OPENSSL_VERSION)) try: sslServer(sys.argv[1], int(sys.argv[2])) except KeyboardInterrupt: print('server exit') |
sslClient:
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 |
import socket import ssl import sys def sslClient(host, port): # create defauly_context ssl_context = ssl.create_default_context(cafile='RootCA.pem') ssl_context.load_cert_chain("Client.pem", "Client.key") ssl_context.protocol = ssl.PROTOCOL_TLSv1_2 # crl test # ssl_context.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF # ssl_context.load_verify_locations("Server.crl") cipher_suites = 'DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384' ssl_context.set_ciphers(cipher_suites) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) with ssl_context.wrap_socket(client, server_hostname='Server') as ssl_client: ssl_client.connect((host, port)) # get the ssl cipher info print('ssl cipher: {}'.format(ssl_client.cipher())) while True: send_data = input("send:") ssl_client.sendall(send_data.encode()) recv_data = ssl_client.recv(1024) print("recv:%s" % recv_data) if __name__ == '__main__': print('ssl ver: {}'.format(ssl.OPENSSL_VERSION)) try: sslClient(sys.argv[1], int(sys.argv[2])) except KeyboardInterrupt: print('client exit') |
参考: 官方文档: https://docs.python.org/3 […]
BaseHTTPServer
测试代码,留备参考。python3相对pyhton2的改变还是不少,比如发送/接收之前之后的编码,包的导入方式等
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 |
# -*- coding: utf-8 -*- #python3.6 from http.server import BaseHTTPRequestHandler, HTTPServer import json import socketserver import threading class myHTTPHandler(BaseHTTPRequestHandler): def _set_header(self): self.protocol = 'HTTP/1.1' self.send_response(200, 'OK') self.send_header('Content-type', 'application/json') self.end_headers() def do_GET(self): #获取线程名称,对比myHTTPServer和HTTPServer的线程差异 print(threading.current_thread().getName()) # 获取请求类型和地址(可以通过不抑制log_message来得到,一样的效果,此处只是为了留存) print(self.command, self.path, self.client_address) #显示header内容 print(self.headers) #获取header指定属性的值 print('Accept-Language', self.headers.get('Accept-Language')) #读取请求内容 #如果有Content-Length,可以通过长度来读取发送的数据内容 length = self.headers.get('Content-Length') if length is not None: rdata = self.rfile.read(int(length)) print(rdata.decode()) jsobBody = json.dumps(rdata.decode()) # 发送响应 self._set_header() # pyhton3必须添加encode()才能正常发送 self.wfile.write(json.dumps({'ret1': 'hello world'}).encode()) def do_POST(self): pass # log处理函数,通过这种方式可以抑制请求消息输出 # def log_message(self, format, *args): # pass class myHTTPServer(socketserver.ThreadingMixIn, HTTPServer): allow_reuse_address = True pass if __name__ == '__main__': server = myHTTPServer(('127.0.0.1', 9999), myHTTPHandler) try: server.serve_forever() except KeyboardInterrupt: pass server.server_close() |
通过下面的curl命令可以测试带数据的POST或者GET,否则可以直接用网页来访问测试:
1 2 3 |
curl -H "Content-Type:application/json" -X GET --data '{"test": "hello from client"}' http://127.0.0.1:9999 |
re子组和xml.etree.ElementTree写文件
关键信息临时中转╭(╯^╰)╮,
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 |
import xml.etree.ElementTree as ET import re def handle_version_str(src_str): # 获取匹配的自组数据 m = re.search(r'(.*)(V\d{3}R\d{3}C\d{2})(.*)', src_str) if m is not None: ver = m.group(2) print(ver) # 通过获取的匹配内容,将其删除 dst_str = re.sub(ver, '', src_str) else: return None return dst_str def create_result_xml(): model = '''<data><country name="China">test</country></data>''' root = ET.fromstring(model) # 添加子节点 sub_attrib = {"location": "cn", "color":"black"} root.append("sub1", sub_attrib) # 如何通过ET写入不是parse方式创建的ET到一个xml文件 tree = ET.ElementTree(root) tree.write('result.xml') if __name__ == "__main__": ver_str = "Hello_V001R002C20_Release" dst_str = handle_version_str(ver_str) print(dst_str) create_result_xml() |