package main import ( "bufio" "crypto/aes" "crypto/rand" "crypto/sha256" "crypto/sha512" "crypto/tls" "fmt" "log" "net" "github.com/andreburgaud/crypt2go/ecb" ) func main() { var key0 [32]byte var key1 [32]byte var zero_value = [16]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // Generate key0 _, err := rand.Read(key0[:]) if err != nil { fmt.Println("error:", err) return } // I'm lazy, so I generate key1 from key0. key1 = SHA256( AES_ECB_ENC(0, SHA512(key0)[16:32]) ) tmp_value := sha512.Sum512(key0[:]) key0_ticket_encryption_aes_key := tmp_value[16:32] block, err := aes.NewCipher(key0_ticket_encryption_aes_key) if err != nil { panic(err) } ecb_mode := ecb.NewECBEncrypter(block) ecb_mode.CryptBlocks(key1[:16], zero_value[:]) key1 = sha256.Sum256(key1[:16]) cert, err := tls.LoadX509KeyPair("./secret/cert.pem", "./secret/key.pem") if err != nil { log.Fatal(err) } cfg := &tls.Config{ Certificates: []tls.Certificate{cert}, } cfg.SetSessionTicketKeys([][32]byte{ key0, key1, }) listener, err := tls.Listen("tcp", ":8000", cfg) if err != nil { log.Fatal(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { log.Println(err) continue } go handleConnection(conn) } } func handleConnection(conn net.Conn) { defer conn.Close() r := bufio.NewReader(conn) for { msg, err := r.ReadString('\n') if err != nil { log.Println(err) return } println(msg) n, err := conn.Write([]byte("")) if err != nil { log.Println(n, err) return } } }
//This patch is provided under the 3-Clause BSD License, the original license of Golang. /* Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This code was created based on src/crypto/tls/ticket.go (L131-L200) in Go1.7.1. // original: https://github.com/golang/go/blob/go1.7.1/src/crypto/tls/ticket.go#L132-L200 // If you want to experiment with this patch, please use a virtual environment that you can throw away, such as Docker. // e.g. https://hub.docker.com/layers/golang/library/golang/1.17.1/images/sha256-8f4773d3be4e83da2198ae437191f8d9dffb30507714f0b727d0daf222377886 const FLAG string = "LINECTF{...}" func (c *Conn) encryptTicket(state []byte) ([]byte, error) { fmt.Println("called custom encryptTicket function!") if len(c.ticketKeys) == 0 { return nil, errors.New("tls: internal error: session ticket keys unavailable") } // write FLAG in certicicate new_state := make([]byte, len(state)+len([]byte(FLAG))) sessionState := new(sessionStateTLS13) if ok := sessionState.unmarshal(state); !ok { return nil, errors.New("tls: failed to unmarshal ticket data") } sessionState.certificate.Certificate = append(sessionState.certificate.Certificate, []byte(FLAG)) new_state = sessionState.marshal() // allocate memory encrypted := make([]byte, ticketKeyNameLen+aes.BlockSize+len(new_state)+sha256.Size) keyName := encrypted[:ticketKeyNameLen] iv := make([]byte, aes.BlockSize) // Select Session Ticket Encryption Key (STEK). // aesKey is generated with following formula // aesKey = SHA512(STEK)[16:32] // ref: https://github.com/golang/go/blob/go1.17.1/src/crypto/tls/common.go#L758-L764 rand.Seed(time.Now().UnixNano()) index := rand.Intn(2) key := c.ticketKeys[index] copy(keyName, key.keyName[:]) block, err := aes.NewCipher(key.aesKey[:]) if err != nil { return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error()) } // I'm lazy, so I generate IV from aesKey. h := sha256.New() h.Write(key.aesKey[:]) iv = h.Sum(nil)[:16] if 0 == index { copy(iv[12:], []byte{0xaa, 0xaa, 0xaa, 0xaa}) } else { copy(iv[12:], []byte{0xbb, 0xbb, 0xbb, 0xbb}) } copy(encrypted[ticketKeyNameLen:ticketKeyNameLen+aes.BlockSize], iv[:16]) aesgcm, err := cipher.NewGCM(block) if err != nil { return nil, errors.New("tls: failed to create cipher while GCM session for encrypting ticket: " + err.Error()) } // AES-128-GCM_ENC(nonce=iv[:12](12-octet), plaintext=raw_ticket, aad=keyName(16-octet)+iv(16-octet)) ciphertext := aesgcm.Seal(nil, iv[:12], new_state, encrypted[:ticketKeyNameLen+aes.BlockSize]) copy(encrypted[ticketKeyNameLen+aes.BlockSize:], ciphertext) return encrypted, nil } func (c *Conn) decryptTicket(encrypted []byte) (plaintext []byte, usedOldKey bool) { if len(encrypted) < ticketKeyNameLen+aes.BlockSize+sha256.Size { return nil, false } tagsize := 16 keyName := encrypted[:ticketKeyNameLen] iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize] ciphertext := encrypted[ticketKeyNameLen+aes.BlockSize : len(encrypted)-sha256.Size+tagsize] keyIndex := -1 for i, candidateKey := range c.ticketKeys { if bytes.Equal(keyName, candidateKey.keyName[:]) { keyIndex = i break } } if keyIndex == -1 { return nil, false } key := &c.ticketKeys[keyIndex] block, err := aes.NewCipher(key.aesKey[:]) if err != nil { return nil, false } aesgcm, err := cipher.NewGCM(block) if err != nil { return nil, false } pt, err := aesgcm.Open(nil, iv[:12], ciphertext, encrypted[:ticketKeyNameLen+aes.BlockSize]) if err != nil { return nil, false } return pt, keyIndex > 0 }
同じkey, nonceで暗号化されているペアから
H = AES.new(key=sha512(key0)[16:32]).encrypt(b'\0'*16)
を求めてkey1 = sha256(H)
を計算する
from ptrlib import chunks from Crypto.Cipher import AES from hashlib import sha256, sha512 c1 = bytes.fromhex("e875cec70f64aac0de67af2caaaaaaaa450abecfee723cdbe4393bbcf56add91e283615eaa6a5899906a138ce3dbe632ab778328029499c12eceefa0589945f7f3801748be3daa06ace2e682a77649da535f7235aa7ecb60bf0e3d6b7c1012e192411e29e6494c2fa05ce2c5d08d4698a05ffb5fa9ad2b2550737cea3b19ccacfdd93e7d3c3f6e641d5f8793b17261047b160c9acaf891577ef7") c2 = bytes.fromhex("e875cec70f64aac0de67af2caaaaaaaa450abecfee723cdbe4393bbce26a50c35bd4b250c5395150b62c27d76e20535dea6a129d08c1c31e89475b79d36e45f7f3801748be3daa06ace2e682a77649da535f7235aa7ecb60bf0e3d6b7c1012e192411e29e6494c2fa05ce2c5d08d4698a05ffb5fa9ad2b2550737cea3b19ccacfdd93e7d3c3f6e641d5f1f668e1af6844a40e4cbdb6132cbd395") c3 = bytes.fromhex("c336d16a10aac82969a59560bbbbbbbb6fe550ba6db4b6a2af74f6f0454d82d959daa387f694685dec4c1ff7c36e40d3b9fe6e4fd41596035a594f8b599b89c47c84aa66d6d63ef3999de5041f0c3b7598b1811012399575a0c442c1c364f669ecf7fd5dfbb06bc37fd830c03e3dde20c98bc747d74d0ac196936f364c2e81338fca4bdb193d52e19f23295fc9e7546288a7464baa258fcd5542") iv1, c1, t1 = c1[:16], c1[16:-16], c1[-16:] iv2, c2, t2 = c2[:16], c2[16:-16], c2[-16:] iv3, c3, t3 = c3[:16], c3[16:-16], c3[-16:] F.<a> = GF(2**128, modulus=x**128 + x**7 + x**2 + x + 1) PR.<x> = PolynomialRing(F) def to_poly(x): bs = Integer(int.from_bytes(x, "big")).bits()[::-1] return F([0] * (128 - len(bs)) + bs) def to_bytes(poly): return int(bin(poly.integer_representation())[2:].zfill(128)[::-1], 2).to_bytes(16, "big") b1 = [to_poly(block) for block in chunks(c1, 16)][::-1] b2 = [to_poly(block) for block in chunks(c2, 16)][::-1] f = sum((a + b)*x**(i + 2) for i, (a, b) in enumerate(zip(b1, b2))) + to_poly(t1) + to_poly(t2) for r, _ in f.roots(): # r == AES.new(key=sha512(key0)[16:32]).encrypt(b"\0" * 16) key1 = sha256(to_bytes(r)).digest() aesKey = sha512(key1).digest()[16:32] if sha256(aesKey).digest()[:12] == iv3[:12]: print("!!", sha256(aesKey).hexdigest()) aesgcm = AES.new(key=aesKey, mode=AES.MODE_GCM, nonce=iv3[:12]) print(aesgcm.decrypt(c3)) break else: print(":thinking_face:")