// Read reads the next len(p) bytes from the SecureReader or until the // SecureReader's buffer is drained. // // In the case that the decrypted message does not fit into p, the // remainder is made available on the next call to Read. func (r *SecureReader) Read(p []byte) (n int, err error) { // Previous short read? if r.n > 0 && r.n < len(r.msg) { n = copy(p, r.msg[r.n:]) r.n += n return n, err } nr, err := io.ReadAtLeast(r.r, r.buf, nsize+minBoxSize) if nr == 0 { return 0, io.EOF } else if err == io.ErrUnexpectedEOF { return 0, ErrInvalidMessage } else if err != nil { return 0, err } // The first nsize bytes of the stream are the nonce; the box then // follows. copy(r.nonce[:], r.buf[:nsize]) var ok bool r.msg, ok = box.OpenAfterPrecomputation(r.msg[:0], r.buf[nsize:nr], &r.nonce, &r.key) n = copy(p, r.msg) if !ok { return n, ErrOpenBox } r.n += n return n, err }
// Read verifies and decrypts a ciphertext using NACL. // Wire format: // 1. nonce (24 bytes) // 2. size (2 bytes, little endian) // 3. ciphertext (number of bytes given by previous value) // Not sure if it would be worth beginning with a magic id. // This simple implementation is equivalent to a ReadFull - the supplied buffer // must be big enough to contain the entire plaintext (which is limited to 32K) // as a successful read will return the entire message. func (sr secureReader) Read(buf []byte) (int, error) { // read the 24 bytes nonce var nonce [24]byte if _, err := io.ReadFull(sr.r, nonce[:]); err != nil { return 0, errors.New("secureReader: cant read nonce: " + err.Error()) } // read the ciphertext size var size uint16 if err := binary.Read(sr.r, binary.LittleEndian, &size); err != nil { return 0, errors.New("secureReader: cant read ciphertext size: " + err.Error()) } // check if the supplied buffer is big enough to contain the plain text if uint16(len(buf)) < size-box.Overhead { return 0, fmt.Errorf("secureReader: ciphertext too long (%d, max = %d)", size, len(buf)+box.Overhead) } // read the ciphertext ctext := make([]byte, size) if _, err := io.ReadFull(sr.r, ctext); err != nil { return 0, errors.New("secureReader: cant read ciphertext: " + err.Error()) } // verify + decrypt ciphertext into buf and return size of plaintext if buf, ok := box.OpenAfterPrecomputation(buf[0:0], ctext, &nonce, &sr.shared); ok { return len(buf), nil } return 0, errors.New("secureReader: error opening box") }
func (c *Conn) readFrame() ([]byte, opcode, error) { b, err := c.conn.ReadFrame() if err != nil { return nil, 0, err } if len(b) < 17 { return nil, 0, fmt.Errorf("unexpected non-message opcode") } var nonce [24]byte if c.cfg.IsServer { c.nonceC.Next(&nonce) } else { c.nonceS.Next(&nonce) } b2, ok := box.OpenAfterPrecomputation(nil, b[1:], &nonce, &c.curveCtSt) if !ok { return nil, 0, fmt.Errorf("invalid msg box received") } if len(b2) == 0 || b2[0] != 0 { return nil, 0, fmt.Errorf("nonzero type byte in msg box") } return b2[1:], opcode(b[0]), nil }
// Read reads secured data, deciphers it and populates incoming // buffer p // The method is thread-safe func (r *secureReader) Read(p []byte) (n int, err error) { r.m.Lock() defer r.m.Unlock() // read nonce first if n, err = r.r.Read(r.nonceBuf[:]); err != nil { return } else if n != 24 { err = errors.New("could not read nonce") return } // read actual message and decipher it if n, err = r.r.Read(r.dataBuf[:]); err != nil { return } out, ok := box.OpenAfterPrecomputation([]byte{}, r.dataBuf[:n], &r.nonceBuf, r.key) if !ok { err = errors.New("could not decrypt incoming message") return } n = copy(p, out) if n < len(out) { err = fmt.Errorf("buffer is too small. Need to allocate %d bytes, got %d", len(out), n) } return }
func secureRead(r io.Reader, p []byte, sharedKey *[32]byte) (n int, err error) { if len(p) > MaxMsgLen { p = p[:MaxMsgLen] } nonce := &[24]byte{} r.Read(nonce[:]) //log.Printf("Readed nonce: %v\n", nonce) var msgLen uint16 err = binary.Read(r, binary.LittleEndian, &msgLen) if err != nil { return } //log.Printf("Readed message length: %v\n", msgLen) b := make([]byte, msgLen) n, err = r.Read(b) if err != nil { return } b = b[:n] //log.Printf("Readed box: %v\n", b) o, ok := box.OpenAfterPrecomputation(nil, b, nonce, sharedKey) n = copy(p, o) //log.Printf("Reading: %s\n", p) if ok == false { err = ErrDecrypt } return }
// Implementation of io.Reader for SecureReader // Messages are read and decrypted using the previous initialized keys func (sr SecureReader) Read(p []byte) (n int, err error) { // Get the new nonce var nonce [24]byte n, err = sr.reader.Read(nonce[:]) if err != nil { return 0, err } // Followed by length of enc message var msgLen uint64 err = binary.Read(sr.reader, binary.BigEndian, &msgLen) if err != nil { return 0, err } // grab encrypted box encBox := make([]byte, msgLen) n, err = sr.reader.Read(encBox) if err != nil { return 0, err } // Read directly into the output slice p[:0] ret, valid := box.OpenAfterPrecomputation(p[:0], encBox, &nonce, &sr.sharedKey) if !valid { return 0, errors.New("Invalid encryption") } return len(ret), nil }
func (sr *secureReader) readAndOpenMessage() error { var totalLength uint16 // read total length err := binary.Read(sr.r, binary.BigEndian, &totalLength) if err != nil { return err } // read nonce var nonce [nonceSize]byte _, err = io.ReadFull(sr.r, nonce[:]) if err != nil { return err } // read sealed message (length = total length - nonce) sealedMessage := make([]byte, totalLength-nonceSize) _, err = io.ReadFull(sr.r, sealedMessage) if err != nil { return err } // open sealed message sr.openedBuffer = sr.openedBuffer[0:0] var ok bool sr.openedBuffer, ok = box.OpenAfterPrecomputation(sr.openedBuffer, sealedMessage, &nonce, &sr.sharedKey) if !ok { return errors.New("failed to open NaCl box") } sr.openedPointer = 0 return nil }
func (s *secureReader) Read(bs []byte) (int, error) { if len(s.decrypted) > 0 { return s.readDecoded(bs), nil } // Read the next packet from the underlying reader. p := s.packet err := p.Read(s.underlying, s.buffer) if err != nil { return 0, err } // Decode the packet into bs where possible, bs[:0] will return a slice with 0 length // but reuse the underlying array's capacity when appending, avoiding memory allocations. decrypted, valid := nacl.OpenAfterPrecomputation(bs[:0], p.data, &p.nonce, &s.sharedKey) if !valid { return 0, ErrInvalidData } // If the decrypted data was smaller than the size of bs, then bs contains all the data. read := len(p.data) - nacl.Overhead if read <= len(bs) { s.decrypted = nil return read, nil } // Otherwise, the data was too large for bs, and needs to be copied into bs. s.decrypted = decrypted return s.readDecoded(bs), nil }
func (sr SecureReader) Read(p []byte) (int, error) { var nonce [24]byte _, err := io.ReadFull(sr.r, nonce[:]) if err != nil { return 0, err } var msgSize uint32 err = binary.Read(sr.r, binary.LittleEndian, &msgSize) if err != nil { return 0, err } // msg := box.SealAfterPrecomputation(nil, p, nonce, sw.sharedKey) msg := make([]byte, msgSize) _, err = io.ReadFull(sr.r, msg) if err != nil { return 0, err } decodedMsg, ok := box.OpenAfterPrecomputation(nil, msg, &nonce, sr.sharedKey) if !ok { return 0, fmt.Errorf("Failed to decode") } n := copy(p, decodedMsg) return n, nil }
func decryptWithPreShared(preSharedKey [keySize]byte, m EncryptedMessage) ([]byte, error) { if decryptedMessage, valid := box.OpenAfterPrecomputation(nil, m.data, &m.nonce, &preSharedKey); !valid { return nil, MessageDecryptionError } else { return decryptedMessage, nil } }
func (sr SecureReader) Read(decryptedMsg []byte) (n int, err error) { nonce := [24]byte{} _, err = sr.r.Read(nonce[:]) if err != nil { return 0, err } msg := [32768]byte{} l, err := sr.r.Read(msg[:]) if err != nil { return 0, err } cryptedMsg := msg[:l] // The length of the resulting message is unknown. // Passing an empty out will result in everything being passed to overlap overlap, b := box.OpenAfterPrecomputation([]byte{}, cryptedMsg, &nonce, sr.shared) if !b { return 0, errors.New("Decrypt failed") } copy(decryptedMsg, overlap) return len(overlap), nil }
// Unbox runs the unbox computation given a precomputed key. func (k PrecomputedSharedKey) Unbox(nonce *saltpack.Nonce, msg []byte) ([]byte, error) { ret, ok := box.OpenAfterPrecomputation([]byte{}, msg, (*[24]byte)(nonce), (*[32]byte)(&k)) if !ok { return nil, saltpack.ErrDecryptionFailed } return ret, nil }
// Extended Read method for reader to read secure data func (sr SecureReader) Read(p []byte) (n int, err error) { //get the nonce r := make([]byte, nonceSize) if _, err = sr.r.Read(r); err != nil { return } var nonce [nonceSize]byte copy(nonce[:], r) //fetch encrypted message enc := make([]byte, maxMessageSize) encLen, err := sr.r.Read(enc) if err != nil { return 0, nil } enc = enc[:encLen] //compute the length of decrypted message n = encLen - box.Overhead //decrypt var s bool dec := make([]byte, n) if dec, s = box.OpenAfterPrecomputation(nil, enc, &nonce, sr.SecureKeys.share); s != true { return 0, errors.New("Error opening the box") } copy(p, dec) return }
// Read encrypted data from the secure reader. // // @param p [[]byte] buffer to store decrypted message in // @return [Integer] number of decrypted bytes read // @return [Error] if error, or nil func (secureReader SecureReader) Read(p []byte) (int, error) { // Get the encrypted bytes from the internal reader data := make([]byte, maxMsgLen) n, err := secureReader.reader.Read(data) if n == 0 || (err != nil && err != io.EOF) { return 0, err } // The first set of bytes is the nonce followed by the message. var nonce [nonceLength]byte for i := 0; i < nonceLength; i++ { nonce[i] = data[i] } decryptedData, success := box.OpenAfterPrecomputation(nil, data[nonceLength:n], &nonce, secureReader.sharedKey) if success != true { return 0, errors.New("Unable to decrypt message.") } // Copy results into p msgLen := n - nonceLength - box.Overhead for i := 0; i < msgLen; i++ { p[i] = decryptedData[i] } return msgLen, nil }
// Read satisfies the io.Reader interface. It expects to find the following sequence: // 1) the fixed length nonce used during encryption of the message // 2) the length of the original message // 3) the encrytped message func (r *SecureReader) Read(p []byte) (n int, err error) { // read the nonce _, err = io.ReadFull(r.r, r.nonce[:]) if err != nil { return 0, err } // read the message length var mlen uint32 err = binary.Read(r.r, binary.BigEndian, &mlen) if err != nil { return 0, err } if mlen > MaxMessageBytes { return 0, ErrMessageTooBig } // read the encrypted message em := r.buf[0 : mlen+box.Overhead] n, err = io.ReadFull(r.r, em) if err != nil { return 0, err } // decrypt the message _, ok := box.OpenAfterPrecomputation(p[0:0], em, &r.nonce, &r.shared) if !ok { return 0, ErrUndecryptable } return int(mlen), nil }
// readPacket reads a packet from r.rd into r.buf. EOF is returned if // r.rd.Read() returns it. Nothing is appended to r.buf if err != nil. func (r *SecureReader) readPacket() error { // 1. Read the packet header hdr := &PacketHdr{} if err := binary.Read(r.rd, binary.BigEndian, hdr); err != nil { return err } // 2. Read the encrypted data encData := make([]byte, hdr.Length) if _, err := io.ReadFull(r.rd, encData); err != nil { return err } // 3. Decrypt and verify the data b, ok := box.OpenAfterPrecomputation(nil, encData, &hdr.Nonce, r.key) if !ok { return ErrFailedVerify } buf := bytes.NewReader(b) // 4. Extract the sequence number and match it to the internal counter var seq uint32 if err := binary.Read(buf, binary.BigEndian, &seq); err != nil { return err } if seq != r.seq { return ErrOutOfOrder } r.seq += 2 // Success! Note: this append will cause the reallocation of r.buf when // it grows too much, and with that the old returned data will be discarded r.buf = append(r.buf, b[len(b)-buf.Len():]...) return nil }
// Read reads and decrypts the byte stream from the underlying Reader func (r *NaClReader) Read(p []byte) (n int, err error) { buf := make([]byte, 1024*32) buflen, err := r.Reader.Read(buf) if buflen > 24 { // parse first 24 bytes as nounce nounce := new([24]byte) copy(nounce[:], buf[:24]) // open the encrypted message opened, ok := box.OpenAfterPrecomputation(nil, buf[24:buflen], nounce, r.skey) if !ok { return 0, errors.New("unable to decrypt") } if len(p) < len(opened) { return 0, errors.New("read buffer exceeded") } n = copy(p, opened) return n, nil } if err != nil { return n, err } return 0, errors.New("unable to read enough data to decrypt") }
func (r *naclReader) Read(buf []byte) (n int, err error) { if len(r.leftovers) != 0 { n = copy(buf, r.leftovers) r.leftovers = r.leftovers[n:] return n, nil } head := naclMsgHeader{} err = binRead(r.in, &head) if err != nil { return 0, err } cipherText := make([]byte, head.Length) _, err = io.ReadFull(r.in, cipherText) if err != nil { return 0, err } msg, ok := box.OpenAfterPrecomputation(nil, cipherText, &head.Nonce, r.sharedKey) if !ok { return 0, ErrBadKey } n = copy(buf, msg) if len(msg) != n { r.leftovers = msg[n:] } return n, nil }
func (b boxPrecomputedSharedKey) Unbox(nonce *Nonce, msg []byte) ([]byte, error) { out, ok := box.OpenAfterPrecomputation([]byte{}, msg, (*[24]byte)(nonce), (*[32]byte)(&b)) if !ok { return nil, errPublicKeyDecryptionFailed } return out, nil }
func (s *SecureReader) Read(p []byte) (n int, err error) { var nonce [24]byte if len(p) == 0 { return 0, nil } buf := make([]byte, 32*1024+24) m, err := s.r.Read(buf) if err != nil && err != io.EOF && m < 24 { return 0, err } copy(nonce[:], buf[:24]) msg, ok := box.OpenAfterPrecomputation([]byte{}, buf[24:m], &nonce, &s.key) if !ok { return 0, errors.New("Failed to decrypt a message") } copy(p[:len(msg)], msg) n = len(msg) return }
func (c *Conn) hcReadServerHello() error { // Receive server hello message. data, err := c.conn.ReadFrame() if err != nil { return err } // Ensure server hello message is of adequate size. if len(data) < 77 { return fmt.Errorf("undersized server hello") } if opcode(data[0]) != opServerHello { return fmt.Errorf("unexpected non-server helo op") } if binary.LittleEndian.Uint32(data[1:5]) != serverHelloMagic { return fmt.Errorf("wrong server hello magic") } // Store server nonce. copy(c.nonceS.initial[:], data[5:29]) // Open box to get St. var nonce [24]byte c.nonceS.Next(&nonce) b, ok := box.OpenAfterPrecomputation(nil, data[29:77], &nonce, &c.curveCtS) if !ok { return fmt.Errorf("malformed box in server hello") } copy(c.curveSt[:], b[0:32]) return nil }
// Decrypt uses a crypto_box_open_afternm-equivalent function to decrypt the given data. func Decrypt(encryptedData []byte, sharedKey *[SharedKeySize]byte, nonce *[NonceSize]byte) ([]byte, error) { data, success := box.OpenAfterPrecomputation(nil, encryptedData, nonce, sharedKey) if !success { return nil, errors.New("decryption failed") } return data, nil }
func (sr SecureReader) Read(p []byte) (n int, err error) { if len(p) == 0 { return 0, nil } plainbuf := make([]byte, 4) n, err = sr.r.Read(plainbuf) if err != nil { return } // Check if the message follows our "special format" for encrypted messages: // 4 bytes as follow [2 71 82 81] + 4 bytes [message length] + 24 bytes [nonce] + unknown bytes [message] if n < 4 || plainbuf[0] != 2 || plainbuf[1] != 71 || plainbuf[2] != 82 || plainbuf[3] != 81 { return 0, errors.New("Not encrypted msg") } // Length of the encrypted message lenbuf := make([]byte, 4) n, err = sr.r.Read(lenbuf) if err != nil { return } // nonce noncebuf := make([]byte, 24) n, err = sr.r.Read(noncebuf) if err != nil { return } msglen, err := binary.ReadUvarint(bytes.NewReader(lenbuf)) var nonce [24]byte copy(nonce[:], noncebuf[:]) // encrypted message msgbuf := make([]byte, msglen) n, err = sr.r.Read(msgbuf) if err != nil { return } if uint64(n) != msglen { return n, errors.New("Wrong length") } // decrypt msg, readed := box.OpenAfterPrecomputation(nil, msgbuf, &nonce, sr.shared) if !readed { return 0, errors.New("Can not be decrypted") } n = copy(p, msg[:]) return n, nil }
func (r *decryptReader) Read(p []byte) (n int, err error) { if r.err != nil { err = r.err return } // Read nonce from 24 first bytes. if !r.nonceRead { _, err = io.ReadFull(r.Reader, r.nonce[:]) r.nonceRead = true } // If unread bytes have already been decrypted // then return these bytes. if len(r.unreadBytes) != 0 { n = r.readUnreadBytes(p) return } // No bytes left unread - will have to decrypt the next block. // First, read the first byte for the length of clear data. // err may be non-nil if there was an error while reading the nonce. if err == nil { _, err = io.ReadFull(r.Reader, r.clearBlockLength[:]) } // Then allocate a slice of the correct size to read the next encrypted block eBlock := []byte(nil) if err == nil { l := int(r.clearBlockLength[0]) + 1 eBlock = r.encryptedBlockArray[:l+box.Overhead+1] _, err = io.ReadFull(r.Reader, eBlock) } // Decrypt the block and validate its size cBlock := []byte(nil) if (err == nil || err == io.EOF) && len(eBlock) != 0 { cBlock = r.clearBlockArray[:len(eBlock)-box.Overhead] cBlock, valid := box.OpenAfterPrecomputation(cBlock[:0], eBlock, &r.nonce, &r.sharedKey) r.incrementNonce() if !valid || int(cBlock[0])+2 != len(cBlock) { err = errors.New("The reader is reading corrupted data.") } } // Set unreadBytes, and return as many unread bytes as possible if (err == nil || err == io.EOF) && len(cBlock) != 0 { r.unreadBytes = cBlock[1:] n = r.readUnreadBytes(p) } r.err = err return }
// Read implements io.Reader to provide the decrypted contents of the underlying // reader. // // Upon any read error, the reader should not be used further as the stream may // be in an inconsistent state. func (sr *SecureReader) Read(p []byte) (int, error) { if len(sr.buffer) > 0 { // we've got stuff in the buffer left from a previous read n := copy(p, sr.buffer) sr.buffer = sr.buffer[n:] return n, nil } // get & check the nonce var nonce [24]byte if _, err := io.ReadFull(sr.reader, nonce[:]); err != nil { return 0, err } nonceID := binary.BigEndian.Uint64(nonce[:8]) if nonceID <= sr.lastNonceID { return 0, fmt.Errorf("invalid nonce") } // get length of cipher text ctLenBytes := make([]byte, 4) if _, err := io.ReadFull(sr.reader, ctLenBytes); err != nil { return 0, err } ctLen := binary.BigEndian.Uint32(ctLenBytes) // get cipher text ct := make([]byte, ctLen) if _, err := io.ReadFull(sr.reader, ct); err != nil { return 0, err } // decrypt ptLen := int(ctLen - box.Overhead) var buf []byte if len(p) < ptLen { buf = make([]byte, ptLen) } else { buf = p } buf, ok := box.OpenAfterPrecomputation(buf[:0], ct, &nonce, &sr.sharedKey) if !ok { return 0, fmt.Errorf("unable to decrypt message") } sr.lastNonceID = nonceID if len(p) < len(buf) || &p[len(buf)-1] != &buf[len(buf)-1] { // p wasn't big enough, and buf was reallocated // Everything after the || should not be necessary, but is there just in case // the buf was reallocated for some other reason. copy(p, buf[:len(p)]) sr.buffer = buf[len(p):] return len(p), nil } return len(buf), nil }
// handleConnection is the server side function // handles the public keys exchange as handshake and message serving func handleConnection(conn net.Conn) error { defer conn.Close() // Handshake // Generate server side keys pub, pri, err := box.GenerateKey(rand.Reader) if *pri == *pub || err != nil { return err } // cpubk is the client public key cpubk := make([]byte, 2048) n, err := conn.Read(cpubk) if err != nil { return err } // client public key cpub := &[32]byte{} copy(cpub[:], cpubk[:n]) // send server public key to client _, err = conn.Write(pub[:]) if err != nil { return err } shared := &[32]byte{} // Let's get a bit faster box.Precompute(shared, cpub, pri) // reading message msg := make([]byte, 2048) n, err = conn.Read(msg) if err != nil { fmt.Errorf("could not read message %s", err) return err } // Generate a nonc, to keep it simple we synchronize // nonces between Clietn and Server nonc := &helper.Nonce{} nv := nonc.GenerateNonce(*shared) out := make([]byte, n) // decrypt message dm, ok := box.OpenAfterPrecomputation(out, msg[:n], &nv, shared) if !ok { m := fmt.Sprintf("could not decrypt message %v", msg[:n]) return errors.New(m) } // Send back message encrypted em := box.SealAfterPrecomputation(nil, dm[n:], &nv, shared) _, err = conn.Write(em) if err != nil { return err } return nil }
// Unseals and verifies data func (c *BoxConn) unseal(b []byte) ([]byte, error) { var nonce [NonceSize]byte copy(nonce[:], b[:NonceSize]) plain, valid := box.OpenAfterPrecomputation(nil, b[NonceSize:], &nonce, c.sharedSecret) if !valid { return nil, errors.New("Recieved invalid box") } return plain, nil }
func (d *Decoder) readBlock(out []byte) ([]byte, error) { if _, err := d.reader.Read(d.block); err != nil { return nil, err } out, ok := box.OpenAfterPrecomputation(out, d.block, d.NextBytes(), &d.shared) if !ok { return nil, errors.New("could not authenticate encrypted block") } return out, nil }
func Open(onion []byte, nonce *[24]byte, sharedKeys []*[32]byte) ([]byte, bool) { var ok bool message := onion for i := 0; i < len(sharedKeys); i++ { message, ok = box.OpenAfterPrecomputation(nil, message, nonce, sharedKeys[i]) if !ok { return nil, false } } return message, true }
// Read reads up to len(p) bytes into p. Encrypted data is read // from the underlying io.Reader and decrypted with the shared key. // // The entire message must be decrypted at once, so this method // returns an error if the decrypted message is larger than len(p). // It will also return an error if the decrypted message is // larger than maxMessageSize. func (r *SecureReader) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } conn, ok := r.r.(net.Conn) if ok { conn.SetReadDeadline(time.Now().Add(timeout)) } // nonce is first 24 bytes of message nonceSlice, err := readAll(r.r, 24) if err != nil { return 0, nil } var nonce [24]byte copy(nonce[:], nonceSlice[:24]) // size of encrypted message is first 4 bytes of nonce var size uint32 buf := bytes.NewReader(nonce[0:4]) bErr := binary.Read(buf, binary.LittleEndian, &size) if bErr != nil { return 0, bErr } // find length of decrypted message messageSize := size - uint32(box.Overhead) // validate message size if messageSize == 0 { return 0, nil } else if messageSize > uint32(len(p)) { return 0, errors.New("buffer is too small") } else if messageSize > uint32(maxMessageSize) { return 0, errors.New("message is too large") } message, err := readAll(r.r, int64(size)) if err != nil { return 0, nil } // decrypt message with shared key decrypted, ok := box.OpenAfterPrecomputation(nil, message, &nonce, r.sharedKey) if !ok { return 0, errors.New("unable to open box") } copy(p, decrypted) return int(messageSize), err }