func TestKeyEntryECDHE25519(t *testing.T) { var ke uid.KeyEntry if err := ke.InitDHKey(cipher.RandReader); err != nil { t.Fatal(err) } jsn, err := json.Marshal(ke) if err != nil { t.Fatal(err) } if len(jsn) != KeyEntryECDHE25519 { t.Error("len(jsn) != KeyEntryECDHE25519") } }
func decrypt(sender, recipient *uid.Message, r io.Reader, recipientTemp *uid.KeyEntry, privateKey string, sign bool, chkMsg bool) error { // decrypt var res bytes.Buffer identities := []*uid.Message{recipient} input := base64.NewDecoder(r) version, preHeader, err := ReadFirstOuterHeader(input) if err != nil { return err } if version != Version { return errors.New("wrong version") } ms := memstore.New() if err := recipientTemp.SetPrivateKey(privateKey); err != nil { return err } ms.AddPrivateKeyEntry(recipientTemp) args := &DecryptArgs{ Writer: &res, Identities: identities, PreHeader: preHeader, Reader: input, Rand: cipher.RandReader, KeyStore: ms, } _, sig, err := Decrypt(args) if err != nil { return err } // do not compare messages when fuzzing, because messages have to be different! if chkMsg && res.String() != msgs.Message1 { return errors.New("messages differ") } if sign { contentHash := cipher.SHA512(res.Bytes()) decSig, err := base64.Decode(sig) if err != nil { return err } if len(decSig) != ed25519.SignatureSize { return errors.New("signature has wrong length") } var sigBuf [ed25519.SignatureSize]byte copy(sigBuf[:], decSig) if !ed25519.Verify(sender.PublicSigKey32(), contentHash, &sigBuf) { return errors.New("signature verification failed") } } return nil }
func setNextSenderSessionPub( keyStore session.Store, sessionState *session.State, sessionStateKey string, rand io.Reader, ) (*uid.KeyEntry, error) { // create next session key var nextSenderSession uid.KeyEntry if err := nextSenderSession.InitDHKey(rand); err != nil { return nil, err } // store next session key if err := addSessionKey(keyStore, &nextSenderSession); err != nil { return nil, err } // update session state sessionState.NextSenderSessionPub = &nextSenderSession err := keyStore.SetSessionState(sessionStateKey, sessionState) if err != nil { return nil, err } return &nextSenderSession, nil }
func TestSessionStates(t *testing.T) { tmpdir, keyDB, err := createDB() if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) defer keyDB.Close() var ( rt uid.KeyEntry ssp uid.KeyEntry nssp uid.KeyEntry nrsps uid.KeyEntry ) if err := rt.InitDHKey(cipher.RandReader); err != nil { t.Fatal(err) } if err := ssp.InitDHKey(cipher.RandReader); err != nil { t.Fatal(err) } if err := nssp.InitDHKey(cipher.RandReader); err != nil { t.Fatal(err) } if err := nrsps.InitDHKey(cipher.RandReader); err != nil { t.Fatal(err) } sessionStateKey1 := base64.Encode(cipher.SHA512([]byte("key1"))) sessionStateKey2 := base64.Encode(cipher.SHA512([]byte("key2"))) ss1 := &session.State{ SenderSessionCount: 1, SenderMessageCount: 2, MaxRecipientCount: 3, RecipientTemp: rt, SenderSessionPub: ssp, NextSenderSessionPub: &nssp, NextRecipientSessionPubSeen: &nrsps, NymAddress: "NYMADDRESS", KeyInitSession: true, } ss2 := &session.State{ RecipientTemp: rt, SenderSessionPub: ssp, NymAddress: "NYMADDRESS", } if err := keyDB.SetSessionState(sessionStateKey1, ss1); err != nil { t.Fatal(err) } if err := keyDB.SetSessionState(sessionStateKey2, ss2); err != nil { t.Fatal(err) } ss1db, err := keyDB.GetSessionState(sessionStateKey1) if err != nil { t.Fatal(err) } ss2db, err := keyDB.GetSessionState(sessionStateKey2) if err != nil { t.Fatal(err) } if !session.StateEqual(ss1, ss1db) { t.Error("ss1 and ss1db differ") } if !session.StateEqual(ss2, ss2db) { t.Error("ss2 and ss2db differ") } if err := keyDB.SetSessionState(sessionStateKey1, ss2); err != nil { t.Fatal(err) } ss1db, err = keyDB.GetSessionState(sessionStateKey1) if err != nil { t.Fatal(err) } if !session.StateEqual(ss2, ss1db) { t.Error("ss2 and ss1db differ") } }
func rootKeyAgreementRecipient( senderHeaderPub *[32]byte, senderIdentity, recipientIdentity string, senderSession, senderID, recipientKI, recipientID *uid.KeyEntry, previousRootKeyHash *[64]byte, numOfKeys uint64, keyStore session.Store, ) error { recipientIdentityPub := recipientID.PublicKey32() recipientIdentityPriv := recipientID.PrivateKey32() recipientKeyInitPub := recipientKI.PublicKey32() recipientKeyInitPriv := recipientKI.PrivateKey32() // sender cannot cause panic here, because keys have been validated in header senderSessionPub := senderSession.PublicKey32() senderIdentityPub := senderID.PublicKey32() log.Debugf("senderIdentityPub: %s", base64.Encode(senderIdentityPub[:])) log.Debugf("senderSessionPub: %s", base64.Encode(senderSessionPub[:])) log.Debugf("recipientIdentityPub: %s", base64.Encode(recipientIdentityPub[:])) log.Debugf("recipientKeyInitPub: %s", base64.Encode(recipientKeyInitPub[:])) // check keys to prevent reflection attacks and replays err := checkKeys(senderHeaderPub, senderIdentityPub, senderSessionPub, recipientIdentityPub, recipientKeyInitPub) if err != nil { return err } // compute t1 t1, err := cipher.ECDH(recipientKeyInitPriv, senderIdentityPub, recipientKeyInitPub) if err != nil { return err } // compute t2 t2, err := cipher.ECDH(recipientKeyInitPriv, senderSessionPub, recipientKeyInitPub) if err != nil { return err } // compute t3 t3, err := cipher.ECDH(recipientIdentityPriv, senderSessionPub, recipientIdentityPub) if err != nil { return err } // derive root key rootKey, err := deriveRootKey(t1, t2, t3, previousRootKeyHash) if err != nil { return err } // generate message keys err = generateMessageKeys(senderIdentity, recipientIdentity, senderID.HASH, recipientID.HASH, rootKey, true, senderSessionPub, recipientKeyInitPub, numOfKeys, keyStore) if err != nil { return err } return nil }
// Decrypt decrypts a message with the argument given in args. // The senderID is returned. // If the message was signed and the signature could be verified successfully // the base64 encoded signature is returned. If the message was signed and the // signature could not be verfied an error is returned. func Decrypt(args *DecryptArgs) (senderID, sig string, err error) { log.Debug("msg.Decrypt()") // set default if args.NumOfKeys == 0 { args.NumOfKeys = NumOfFutureKeys } // read pre-header ph, err := readPreHeader(bytes.NewBuffer(args.PreHeader)) if err != nil { return "", "", err } if ph.LengthSenderHeaderPub != 32 { return "", "", log.Errorf("msg: ph.LengthSenderHeaderPub != 32") } var senderHeaderPub [32]byte copy(senderHeaderPub[:], ph.SenderHeaderPub) // read header packet oh, err := readOuterHeader(args.Reader) if err != nil { return "", "", err } if oh.Type != encryptedHeader { return "", "", log.Error(ErrNotEncryptedHeader) } count := uint32(1) if oh.PacketCount != count { return "", "", log.Error(ErrWrongCount) } count++ identity, h, err := readHeader(&senderHeaderPub, args.Identities, bytes.NewBuffer(oh.inner)) if err != nil { return "", "", err } senderID = h.SenderIdentity recipientID := identity.PubKey() log.Debugf("senderID: %s", h.SenderIdentityPub.HASH) log.Debugf("recipientID: %s", recipientID.HASH) log.Debugf("h.SenderSessionCount: %d", h.SenderSessionCount) log.Debugf("h.SenderMessageCount: %d", h.SenderMessageCount) log.Debugf("h.SenderSessionPub: %s", h.SenderSessionPub.HASH) if h.NextSenderSessionPub != nil { log.Debugf("h.NextSenderSessionPub: %s", h.NextSenderSessionPub.HASH) } if h.NextRecipientSessionPubSeen != nil { log.Debugf("h.NextRecipientSessionPubSeen: %s", h.NextRecipientSessionPubSeen.HASH) } // proc sender UID in parallel res := make(chan *procUIDResult, 1) go procUID(h.SenderUID, res) // get session state sender := h.SenderIdentity recipient := identity.Identity() log.Debugf("%s -> %s", sender, recipient) sessionStateKey := session.CalcStateKey(recipientID.PublicKey32(), h.SenderIdentityPub.PublicKey32()) ss, err := args.KeyStore.GetSessionState(sessionStateKey) if err != nil { return "", "", err } sessionKey := session.CalcKey(recipientID.HASH, h.SenderIdentityPub.HASH, h.RecipientTempHash, h.SenderSessionPub.HASH) if !args.KeyStore.HasSession(sessionKey) { // session unknown // try to start session from KeyInit message recipientKI, err := args.KeyStore.GetPrivateKeyEntry(h.RecipientTempHash) if err != nil && err != session.ErrNoKeyEntry { return "", "", err } if err != session.ErrNoKeyEntry { // KeyInit message found // root key agreement err = rootKeyAgreementRecipient(&senderHeaderPub, sender, recipient, &h.SenderSessionPub, &h.SenderIdentityPub, recipientKI, recipientID, nil, args.NumOfKeys, args.KeyStore) if err != nil { return "", "", err } // TODO: delete single-use KeyInit message // use the 'smaller' session as the definite one // TODO: h.SenderSessionPub.HASH < ss.SenderSessionPub.HASH if ss == nil || (ss.KeyInitSession && sender < recipient) { // create next session key var nextSenderSession uid.KeyEntry if err := nextSenderSession.InitDHKey(args.Rand); err != nil { return "", "", err } // store next session key err := addSessionKey(args.KeyStore, &nextSenderSession) if err != nil { return "", "", err } // if we already got h.NextSenderSessionPub prepare next session if h.NextSenderSessionPub != nil { previousRootKeyHash, err := args.KeyStore.GetRootKeyHash(sessionKey) if err != nil { return "", "", err } // root key agreement err = rootKeyAgreementSender(&senderHeaderPub, recipient, sender, &nextSenderSession, recipientID, h.NextSenderSessionPub, &h.SenderIdentityPub, previousRootKeyHash, args.NumOfKeys, args.KeyStore) if err != nil { return "", "", err } } // set session state ss = &session.State{ SenderSessionCount: 0, SenderMessageCount: 0, MaxRecipientCount: 0, RecipientTemp: h.SenderSessionPub, SenderSessionPub: *recipientKI, NextSenderSessionPub: &nextSenderSession, NextRecipientSessionPubSeen: h.NextSenderSessionPub, NymAddress: h.NymAddress, KeyInitSession: false, } err = args.KeyStore.SetSessionState(sessionStateKey, ss) if err != nil { return "", "", err } } } else { // no KeyInit message found // TODO: ??? } } else { // session known log.Debug("session known") // check if session state reflects that session if h.RecipientTempHash == ss.SenderSessionPub.HASH && h.SenderSessionPub.HASH == ss.RecipientTemp.HASH { log.Debug("session state reflects that session") if h.NextSenderSessionPub != nil { log.Debug("h.NextSenderSessionPub is defined") } if h.NextRecipientSessionPubSeen != nil { log.Debug("h.NextRecipientSessionPubSeen is defined") } if h.NextSenderSessionPub != nil { // if other side has set its NextSenderSessionPubKey we set // ours immediately if ss.NextSenderSessionPub == nil { // prepare upcoming session, but do not switch to it yet nextSenderSession, err := setNextSenderSessionPub(args.KeyStore, ss, sessionStateKey, args.Rand) if err != nil { return "", "", err } previousRootKeyHash, err := args.KeyStore.GetRootKeyHash(sessionKey) if err != nil { return "", "", err } // root key agreement err = rootKeyAgreementSender(&senderHeaderPub, recipient, sender, nextSenderSession, recipientID, h.NextSenderSessionPub, &h.SenderIdentityPub, previousRootKeyHash, args.NumOfKeys, args.KeyStore) if err != nil { return "", "", err } if ss.NextRecipientSessionPubSeen == nil { // save h.NextSenderSessionPub, if necessary ss.NextRecipientSessionPubSeen = h.NextSenderSessionPub err := args.KeyStore.SetSessionState(sessionStateKey, ss) if err != nil { return "", "", err } } } else if h.NextRecipientSessionPubSeen != nil && h.NextRecipientSessionPubSeen.HASH == ss.NextSenderSessionPub.HASH { // switch to next session nextSenderSession, err := getSessionKey(args.KeyStore, ss.NextSenderSessionPub.HASH) if err != nil { return "", "", err } previousRootKeyHash, err := args.KeyStore.GetRootKeyHash(sessionKey) if err != nil { return "", "", err } // root key agreement err = rootKeyAgreementRecipient(&senderHeaderPub, sender, recipient, h.NextSenderSessionPub, &h.SenderIdentityPub, nextSenderSession, recipientID, previousRootKeyHash, args.NumOfKeys, args.KeyStore) if err != nil { return "", "", err } // store new session state ss = &session.State{ SenderSessionCount: ss.SenderSessionCount + ss.SenderMessageCount, SenderMessageCount: 0, MaxRecipientCount: 0, RecipientTemp: *h.NextSenderSessionPub, SenderSessionPub: *nextSenderSession, NextSenderSessionPub: nil, NextRecipientSessionPubSeen: nil, NymAddress: h.NymAddress, KeyInitSession: false, } err = args.KeyStore.SetSessionState(sessionStateKey, ss) if err != nil { return "", "", err } } } } else { // check if session matches next session if ss.NextSenderSessionPub != nil && ss.NextRecipientSessionPubSeen != nil && ss.NextSenderSessionPub.HASH == h.RecipientTempHash && ss.NextRecipientSessionPubSeen.HASH == h.SenderSessionPub.HASH { // switch session ss = &session.State{ SenderSessionCount: ss.SenderSessionCount + ss.SenderMessageCount, SenderMessageCount: 0, MaxRecipientCount: 0, RecipientTemp: h.SenderSessionPub, SenderSessionPub: *ss.NextSenderSessionPub, NextSenderSessionPub: nil, NextRecipientSessionPubSeen: nil, NymAddress: h.NymAddress, KeyInitSession: false, } err = args.KeyStore.SetSessionState(sessionStateKey, ss) if err != nil { return "", "", err } } } // a message with this session key has been decrypted -> delete key if err := args.KeyStore.DelPrivSessionKey(h.RecipientTempHash); err != nil { return "", "", err } } // make sure we got enough message keys n, err := args.KeyStore.NumMessageKeys(sessionKey) if err != nil { return "", "", err } if h.SenderMessageCount >= n { // generate more message keys log.Debugf("generate more message keys (h.SenderMessageCount=%d, n=%d)", h.SenderMessageCount, n) chainKey, err := args.KeyStore.GetChainKey(sessionKey) if err != nil { return "", "", err } // prevent denial of service attack by very large h.SenderMessageCount numOfKeys := h.SenderMessageCount / args.NumOfKeys if h.SenderMessageCount%args.NumOfKeys > 0 { numOfKeys++ } numOfKeys *= args.NumOfKeys if numOfKeys > mime.MaxMsgSize/MaxContentLength+NumOfFutureKeys { return "", "", log.Errorf("msg: requested number of message keys too large") } log.Debugf("numOfKeys=%d", numOfKeys) var recipientPub *[32]byte if h.RecipientTempHash == ss.SenderSessionPub.HASH { recipientPub = ss.SenderSessionPub.PublicKey32() } else { log.Debug("different session") recipientKI, err := args.KeyStore.GetPrivateKeyEntry(h.RecipientTempHash) if err != nil && err != session.ErrNoKeyEntry { return "", "", err } if err != session.ErrNoKeyEntry { recipientPub = recipientKI.PublicKey32() } else { recipientKE, err := getSessionKey(args.KeyStore, h.RecipientTempHash) if err != nil { return "", "", err } recipientPub = recipientKE.PublicKey32() } } err = generateMessageKeys(sender, recipient, h.SenderIdentityPub.HASH, recipientID.HASH, chainKey, true, h.SenderSessionPub.PublicKey32(), recipientPub, numOfKeys, args.KeyStore) if err != nil { return "", "", err } } // get message key messageKey, err := args.KeyStore.GetMessageKey(sessionKey, false, h.SenderMessageCount) if err != nil { return "", "", err } // derive symmetric keys cryptoKey, hmacKey, err := deriveSymmetricKeys(messageKey) if err != nil { return "", "", err } // read crypto setup packet oh, err = readOuterHeader(args.Reader) if err != nil { return "", "", err } if oh.Type != cryptoSetup { return "", "", log.Error(ErrNotCryptoSetup) } if oh.PacketCount != count { return "", "", log.Error(ErrWrongCount) } count++ if oh.PLen != aes.BlockSize { return "", "", log.Error(ErrWrongCryptoSetup) } iv := oh.inner // start HMAC calculation mac := hmac.New(sha512.New, hmacKey) if err := oh.write(mac, true); err != nil { return "", "", err } // actual decryption oh, err = readOuterHeader(args.Reader) if err != nil { return "", "", err } if oh.Type != encryptedPacket { return "", "", log.Error(ErrNotEncryptedPacket) } if oh.PacketCount != count { return "", "", log.Error(ErrWrongCount) } count++ ciphertext := oh.inner plaintext := make([]byte, len(ciphertext)) stream := cipher.AES256CTRStream(cryptoKey, iv) stream.XORKeyStream(plaintext, ciphertext) ih, err := readInnerHeader(bytes.NewBuffer(plaintext)) if err != nil { return "", "", err } if ih.Type&dataType == 0 { return "", "", log.Error(ErrNotData) } var contentHash []byte if ih.Type&signType != 0 { // create signature hash contentHash = cipher.SHA512(ih.content) } if _, err := args.Writer.Write(ih.content); err != nil { return "", "", log.Error(err) } // continue HMAC calculation if err := oh.write(mac, true); err != nil { return "", "", err } // verify signature var sigBuf [ed25519.SignatureSize]byte if contentHash != nil { oh, err = readOuterHeader(args.Reader) if err != nil { return "", "", err } if oh.Type != encryptedPacket { return "", "", log.Error(ErrNotEncryptedPacket) } if oh.PacketCount != count { return "", "", log.Error(ErrWrongCount) } count++ // continue HMAC calculation if err := oh.write(mac, true); err != nil { return "", "", err } ciphertext = oh.inner plaintext = make([]byte, len(ciphertext)) stream.XORKeyStream(plaintext, ciphertext) ih, err = readInnerHeader(bytes.NewBuffer(plaintext)) if err != nil { return "", "", err } if ih.Type&signatureType == 0 { return "", "", log.Error(ErrNotSignaturePacket) } if len(ih.content) != ed25519.SignatureSize { return "", "", log.Error(ErrWrongSignatureLength) } copy(sigBuf[:], ih.content) } else { oh, err = readOuterHeader(args.Reader) if err != nil { return "", "", err } if oh.Type != encryptedPacket { return "", "", log.Error(ErrNotEncryptedPacket) } if oh.PacketCount != count { return "", "", log.Error(ErrWrongCount) } count++ // continue HMAC calculation if err := oh.write(mac, true); err != nil { return "", "", err } ciphertext = oh.inner plaintext = make([]byte, len(ciphertext)) stream.XORKeyStream(plaintext, ciphertext) ih, err = readInnerHeader(bytes.NewBuffer(plaintext)) if err != nil { return "", "", err } if ih.Type&paddingType == 0 { return "", "", log.Error(ErrNotPaddingPacket) } } // get processed sender UID uidRes := <-res if uidRes.err != nil { return "", "", uidRes.err } // verify signature, if necessary if contentHash != nil { if !ed25519.Verify(uidRes.msg.PublicSigKey32(), contentHash, &sigBuf) { return "", "", log.Error(ErrInvalidSignature) } // encode signature to base64 as return value sig = base64.Encode(sigBuf[:]) } // read HMAC packet oh, err = readOuterHeader(args.Reader) if err != nil { return "", "", err } if oh.Type != hmacPacket { return "", "", log.Error(ErrNotHMACPacket) } if oh.PacketCount != count { return "", "", log.Error(ErrWrongCount) } count++ if err := oh.write(mac, false); err != nil { return "", "", err } sum := mac.Sum(nil) log.Debugf("HMAC: %s", base64.Encode(sum)) if !hmac.Equal(sum, oh.inner) { return "", "", log.Error(ErrHMACsDiffer) } // delete message key err = args.KeyStore.DelMessageKey(sessionKey, false, h.SenderMessageCount) if err != nil { return "", "", err } return }
func addSessionKey(ss session.Store, ke *uid.KeyEntry) error { ct := uint64(times.Now()) + CleanupTime return ss.AddSessionKey(ke.HASH, string(ke.JSON()), ke.PrivateKey(), ct) }
// Encrypt encrypts a message with the argument given in args and returns the // nymAddress the message should be delivered to. func Encrypt(args *EncryptArgs) (nymAddress string, err error) { log.Debugf("msg.Encrypt(): %s -> %s", args.From.Identity(), args.To.Identity()) // set defaults if args.NumOfKeys == 0 { args.NumOfKeys = NumOfFutureKeys } if args.AvgSessionSize == 0 { args.AvgSessionSize = AverageSessionSize } // create sender key senderHeaderKey, err := cipher.Curve25519Generate(cipher.RandReader) if err != nil { return "", log.Error(err) } // create pre-header ph := newPreHeader(senderHeaderKey.PublicKey()[:]) // create base64 encoder var out bytes.Buffer wc := base64.NewEncoder(&out) // write pre-header var buf bytes.Buffer var count uint32 if err := ph.write(&buf); err != nil { return "", err } oh := newOuterHeader(preHeaderPacket, count, buf.Bytes()) if err := oh.write(wc, true); err != nil { return "", err } count++ // get session state sender := args.From.Identity() recipient := args.To.Identity() sessionStateKey := session.CalcStateKey(args.From.PubKey().PublicKey32(), args.To.PubKey().PublicKey32()) var ss *session.State if args.StatusCode != StatusReset { ss, err = args.KeyStore.GetSessionState(sessionStateKey) if err != nil { return "", err } } if ss == nil { // no session found -> start first session log.Debug("no session found -> start first session") var recipientTemp *uid.KeyEntry recipientTemp, nymAddress, err = args.KeyStore.GetPublicKeyEntry(args.To) if err != nil { return "", err } // create session key var senderSession uid.KeyEntry if err := senderSession.InitDHKey(args.Rand); err != nil { return "", err } // store session key if err := addSessionKey(args.KeyStore, &senderSession); err != nil { return "", err } // root key agreement err = rootKeyAgreementSender(senderHeaderKey.PublicKey(), args.From.Identity(), args.To.Identity(), &senderSession, args.From.PubKey(), recipientTemp, args.To.PubKey(), nil, args.NumOfKeys, args.KeyStore) if err != nil { return "", err } // set session state ss = &session.State{ SenderSessionCount: 0, SenderMessageCount: 0, MaxRecipientCount: 0, RecipientTemp: *recipientTemp, SenderSessionPub: senderSession, NextSenderSessionPub: nil, NextRecipientSessionPubSeen: nil, NymAddress: nymAddress, KeyInitSession: true, } log.Debugf("set session: %s", ss.SenderSessionPub.HASH) err = args.KeyStore.SetSessionState(sessionStateKey, ss) if err != nil { return "", err } } else if args.StatusCode != StatusError { // do not update sessions for StatusError messages log.Debug("session found") log.Debugf("got session: %s", ss.SenderSessionPub.HASH) nymAddress = ss.NymAddress if ss.NextSenderSessionPub == nil { // start new session in randomized fashion n, err := rand.Int(cipher.RandReader, big.NewInt(int64(args.AvgSessionSize))) if err != nil { return "", err } if n.Int64() == 0 { _, err := setNextSenderSessionPub(args.KeyStore, ss, sessionStateKey, args.Rand) if err != nil { return "", err } } } } // create header log.Debugf("senderID: %s", args.From.UIDContent.PUBKEYS[0].HASH) log.Debugf("recipientID: %s", args.To.UIDContent.PUBKEYS[0].HASH) log.Debugf("ss.SenderSessionCount: %d", ss.SenderSessionCount) log.Debugf("ss.SenderMessageCount: %d", ss.SenderMessageCount) log.Debugf("ss.RecipientTempHash: %s", ss.RecipientTemp.HASH) h, err := newHeader(args.From, args.To, ss.RecipientTemp.HASH, &ss.SenderSessionPub, ss.NextSenderSessionPub, ss.NextRecipientSessionPubSeen, args.NymAddress, ss.SenderSessionCount, ss.SenderMessageCount, args.SenderLastKeychainHash, args.Rand, args.StatusCode) if err != nil { return "", err } log.Debugf("h.SenderSessionPub: %s", h.SenderSessionPub.HASH) if h.NextSenderSessionPub != nil { log.Debugf("h.NextSenderSessionPub: %s", h.NextSenderSessionPub.HASH) } if h.NextRecipientSessionPubSeen != nil { log.Debugf("h.NextRecipientSessionPubSeen: %s", h.NextRecipientSessionPubSeen.HASH) } // create (encrypted) header packet recipientIdentityPub, err := args.To.PublicKey() if err != nil { return "", err } hp, err := newHeaderPacket(h, recipientIdentityPub, senderHeaderKey.PrivateKey(), args.Rand) if err != nil { return "", err } // write (encrypted) header packet buf.Reset() if err := hp.write(&buf); err != nil { return "", err } oh = newOuterHeader(encryptedHeader, count, buf.Bytes()) if err := oh.write(wc, true); err != nil { return "", err } count++ sessionKey := session.CalcKey(args.From.PubKey().HASH, args.To.PubKey().HASH, ss.SenderSessionPub.HASH, ss.RecipientTemp.HASH) // make sure we got enough message keys n, err := args.KeyStore.NumMessageKeys(sessionKey) if err != nil { return "", err } if ss.SenderMessageCount >= n { // generate more message keys log.Debugf("generate more message keys (ss.SenderMessageCount=%d)", ss.SenderMessageCount) chainKey, err := args.KeyStore.GetChainKey(sessionKey) if err != nil { return "", err } err = generateMessageKeys(sender, recipient, args.From.PubKey().HASH, args.To.PubKey().HASH, chainKey, false, ss.SenderSessionPub.PublicKey32(), ss.RecipientTemp.PublicKey32(), args.NumOfKeys, args.KeyStore) if err != nil { return "", err } } // get message key messageKey, err := args.KeyStore.GetMessageKey(sessionKey, true, ss.SenderMessageCount) if err != nil { return "", err } // derive symmetric keys cryptoKey, hmacKey, err := deriveSymmetricKeys(messageKey) if err != nil { return "", err } // write crypto setup packet iv := make([]byte, aes.BlockSize) if _, err := io.ReadFull(args.Rand, iv); err != nil { return "", log.Error(err) } oh = newOuterHeader(cryptoSetup, count, iv) if err := oh.write(wc, true); err != nil { return "", err } count++ // start HMAC calculation mac := hmac.New(sha512.New, hmacKey) if err := oh.write(mac, true); err != nil { return "", err } // actual encryption var content []byte if args.StatusCode == StatusOK { // StatusReset and StatusError messages are empty content, err = ioutil.ReadAll(args.Reader) if err != nil { return "", log.Error(err) } } // enforce maximum content length if len(content) > MaxContentLength { return "", log.Errorf("len(content) = %d > %d = MaxContentLength)", len(content), MaxContentLength) } // encrypted packet var contentHash []byte var innerType uint8 if args.PrivateSigKey != nil { contentHash = cipher.SHA512(content) innerType = dataType | signType } else { innerType = dataType } ih := newInnerHeader(innerType, false, content) buf.Reset() if err := ih.write(&buf); err != nil { return "", err } stream := cipher.AES256CTRStream(cryptoKey, iv) stream.XORKeyStream(buf.Bytes(), buf.Bytes()) oh = newOuterHeader(encryptedPacket, count, buf.Bytes()) if err := oh.write(wc, true); err != nil { return "", err } count++ // continue HMAC calculation if err := oh.write(mac, true); err != nil { return "", err } // signature header & padding buf.Reset() if args.PrivateSigKey != nil { sig := ed25519.Sign(args.PrivateSigKey, contentHash) // signature ih = newInnerHeader(signatureType, true, sig[:]) if err := ih.write(&buf); err != nil { return "", err } // padding padLen := MaxContentLength - len(content) pad, err := padding.Generate(padLen, cipher.RandReader) if err != nil { return "", err } ih = newInnerHeader(paddingType, false, pad) if err := ih.write(&buf); err != nil { return "", err } } else { // just padding padLen := MaxContentLength + signatureSize - encryptedPacketSize + innerHeaderSize - len(content) pad, err := padding.Generate(padLen, cipher.RandReader) if err != nil { return "", err } ih = newInnerHeader(paddingType, false, pad) if err := ih.write(&buf); err != nil { return "", err } } // encrypt inner header stream.XORKeyStream(buf.Bytes(), buf.Bytes()) oh = newOuterHeader(encryptedPacket, count, buf.Bytes()) if err := oh.write(wc, true); err != nil { return "", err } count++ // continue HMAC calculation if err := oh.write(mac, true); err != nil { return "", err } // create HMAC header oh = newOuterHeader(hmacPacket, count, nil) oh.PLen = sha512.Size if err := oh.write(mac, false); err != nil { return "", err } oh.inner = mac.Sum(oh.inner) log.Debugf("HMAC: %s", base64.Encode(oh.inner)) if err := oh.write(wc, true); err != nil { return "", err } count++ // write output wc.Close() if out.Len() != EncodedMsgSize { return "", log.Errorf("out.Len() = %d != %d = EncodedMsgSize)", out.Len(), EncodedMsgSize) } if _, err := io.Copy(args.Writer, &out); err != nil { return "", log.Error(err) } // delete message key err = args.KeyStore.DelMessageKey(sessionKey, true, ss.SenderMessageCount) if err != nil { return "", err } // increase SenderMessageCount ss.SenderMessageCount++ err = args.KeyStore.SetSessionState(sessionStateKey, ss) if err != nil { return "", err } return }
func TestSessionKeys(t *testing.T) { tmpdir, keyDB, err := createDB() if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) defer keyDB.Close() var ( ke1 uid.KeyEntry ke2 uid.KeyEntry ) if err := ke1.InitDHKey(cipher.RandReader); err != nil { t.Fatal(err) } if err := ke2.InitDHKey(cipher.RandReader); err != nil { t.Fatal(err) } ct := uint64(times.Now()) + msg.CleanupTime jsn1 := string(ke1.JSON()) pk1 := ke1.PrivateKey() if err := keyDB.AddSessionKey(ke1.HASH, jsn1, pk1, ct); err != nil { t.Fatal(err) } jsn2 := string(ke2.JSON()) pk2 := ke2.PrivateKey() if err := keyDB.AddSessionKey(ke2.HASH, jsn2, pk2, ct); err != nil { t.Fatal(err) } jsn1db, pk1db, err := keyDB.GetSessionKey(ke1.HASH) if err != nil { t.Fatal(err) } if jsn1 != jsn1db { t.Error("jsn1 and jsn1db differ") } if pk1 != pk1db { t.Error("pk1 and pk1db differ") } jsn2db, pk2db, err := keyDB.GetSessionKey(ke2.HASH) if err != nil { t.Fatal(err) } if jsn2 != jsn2db { t.Error("jsn2 and jsn2db differ") } if pk2 != pk2db { t.Error("pk2 and pk2db differ") } // getting undefined key should return sql.ErrNoRows _, _, err = keyDB.GetSessionKey("undefined") if err != sql.ErrNoRows { t.Error("should return sql.ErrNoRows") } // deleting non-existing key should not fail if err := keyDB.DelPrivSessionKey("undefined"); err != nil { t.Error(err) } // delete private key if err := keyDB.DelPrivSessionKey(ke1.HASH); err != nil { t.Fatal(err) } _, pk, err := keyDB.GetSessionKey(ke1.HASH) if err != nil { t.Fatal(err) } if pk != "" { t.Error("pk should be empty") } // deleting key again should not fail if err := keyDB.DelPrivSessionKey(ke1.HASH); err != nil { t.Error(err) } }