From dca0103899efd2720ae703eb8ac7dde52a065ad6 Mon Sep 17 00:00:00 2001 From: mcrakhman Date: Sun, 26 Mar 2023 17:53:11 +0200 Subject: [PATCH] Remove old acl methods and tests, acl builder --- .../object/acl/aclrecordproto/aclrecord.pb.go | 114 ++++---- .../acl/aclrecordproto/protos/aclrecord.proto | 2 +- .../object/acl/list/aclrecordbuilder.go | 146 +++++----- .../object/acl/list/aclrecordbuilder_test.go | 36 +-- commonspace/object/acl/list/aclstate.go | 153 ++-------- commonspace/object/acl/list/list.go | 12 +- commonspace/payloads.go | 134 +++------ commonspace/space.go | 14 +- util/crypto/cryptoproto/crypto.pb.go | 249 +++++++++++++++- util/crypto/cryptoproto/protos/crypto.proto | 9 + util/crypto/derived.go | 6 +- util/{keys/decode.go => crypto/encoder.go} | 7 +- .../asymmetric/encryptionkey/encryptionkey.go | 18 -- util/keys/asymmetric/encryptionkey/rsa.go | 275 ------------------ .../keys/asymmetric/encryptionkey/rsa_test.go | 24 -- .../signingkey/edwards25519/ed25519.go | 53 ---- util/keys/asymmetric/signingkey/signingkey.go | 59 ---- .../asymmetric/signingkey/signingkey_test.go | 16 - 18 files changed, 453 insertions(+), 874 deletions(-) rename util/{keys/decode.go => crypto/encoder.go} (65%) delete mode 100644 util/keys/asymmetric/encryptionkey/encryptionkey.go delete mode 100644 util/keys/asymmetric/encryptionkey/rsa.go delete mode 100644 util/keys/asymmetric/encryptionkey/rsa_test.go delete mode 100644 util/keys/asymmetric/signingkey/edwards25519/ed25519.go delete mode 100644 util/keys/asymmetric/signingkey/signingkey.go delete mode 100644 util/keys/asymmetric/signingkey/signingkey_test.go diff --git a/commonspace/object/acl/aclrecordproto/aclrecord.pb.go b/commonspace/object/acl/aclrecordproto/aclrecord.pb.go index a8b99e7e..c00b712f 100644 --- a/commonspace/object/acl/aclrecordproto/aclrecord.pb.go +++ b/commonspace/object/acl/aclrecordproto/aclrecord.pb.go @@ -250,7 +250,7 @@ type AclRoot struct { Identity []byte `protobuf:"bytes,1,opt,name=identity,proto3" json:"identity,omitempty"` SpaceId string `protobuf:"bytes,2,opt,name=spaceId,proto3" json:"spaceId,omitempty"` EncryptedReadKey []byte `protobuf:"bytes,3,opt,name=encryptedReadKey,proto3" json:"encryptedReadKey,omitempty"` - DerivationScheme string `protobuf:"bytes,4,opt,name=derivationScheme,proto3" json:"derivationScheme,omitempty"` + DerivationParams []byte `protobuf:"bytes,4,opt,name=derivationParams,proto3" json:"derivationParams,omitempty"` Timestamp int64 `protobuf:"varint,5,opt,name=timestamp,proto3" json:"timestamp,omitempty"` } @@ -308,11 +308,11 @@ func (m *AclRoot) GetEncryptedReadKey() []byte { return nil } -func (m *AclRoot) GetDerivationScheme() string { +func (m *AclRoot) GetDerivationParams() []byte { if m != nil { - return m.DerivationScheme + return m.DerivationParams } - return "" + return nil } func (m *AclRoot) GetTimestamp() int64 { @@ -1139,61 +1139,61 @@ var fileDescriptor_c8e9f754f34e929b = []byte{ // 907 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x56, 0x4f, 0x6f, 0x1b, 0x45, 0x14, 0xf7, 0xd8, 0x49, 0x1c, 0x3f, 0x9b, 0xc4, 0x19, 0xa0, 0x5d, 0x45, 0xc5, 0x8a, 0x56, 0x42, - 0x8a, 0xaa, 0x2a, 0x11, 0x06, 0x29, 0x55, 0x84, 0xa8, 0xdc, 0x52, 0x64, 0xb7, 0x42, 0xaa, 0x26, - 0x40, 0x51, 0x39, 0x4d, 0x66, 0x47, 0xc9, 0xd0, 0xf5, 0xee, 0x6a, 0x66, 0x6c, 0xe4, 0x4f, 0x01, + 0x8a, 0xaa, 0x2a, 0x11, 0x06, 0x29, 0x55, 0x84, 0xa8, 0xdc, 0x52, 0x64, 0xb7, 0x42, 0x8a, 0x26, + 0x40, 0x51, 0x39, 0x4d, 0x66, 0x47, 0xe9, 0xd0, 0xf5, 0xee, 0x6a, 0x66, 0x6c, 0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 0x04, 0xee, 0x35, 0xaf, 0x96, 0x31, 0x2b, 0xf3, 0x63, + 0x09, 0x6f, 0xaf, 0xf0, 0xdb, 0xd1, 0x19, 0x04, 0xee, 0x35, 0xaf, 0x96, 0x31, 0x2b, 0xf3, 0x63, 0x94, 0xf9, 0xcd, 0x00, 0xcf, 0xd1, 0xf9, 0x28, 0x1e, 0xdb, 0x1b, 0xcf, 0x71, 0xf8, 0x04, 0xda, 0x32, 0x0b, 0x69, 0x6e, 0xb3, 0x98, 0x75, 0xfd, 0xbb, 0x84, 0xa4, 0xe8, 0xfb, 0x27, 0x80, 0xeb, - 0xa2, 0xe0, 0x0e, 0x6c, 0x8e, 0x82, 0xa9, 0x88, 0xfa, 0x0d, 0x0c, 0xb0, 0xf5, 0x52, 0x0a, 0xcd, + 0xa2, 0xe0, 0x0e, 0x6c, 0x8e, 0x82, 0xa9, 0x88, 0xfa, 0x0d, 0x0c, 0xb0, 0xf5, 0x42, 0x0a, 0xcd, 0x65, 0x1f, 0x99, 0x67, 0x73, 0x43, 0x5c, 0xf6, 0x9b, 0x8f, 0x1f, 0xfd, 0x76, 0x3d, 0x40, 0x57, 0xd7, 0x03, 0xf4, 0xe7, 0xf5, 0x00, 0xfd, 0x70, 0x33, 0x68, 0x5c, 0xdd, 0x0c, 0x1a, 0x7f, 0xdc, - 0x0c, 0x1a, 0xaf, 0xde, 0xff, 0x57, 0x5f, 0x7d, 0xe7, 0x5b, 0xf6, 0xe7, 0xc3, 0xbf, 0x03, 0x00, - 0x00, 0xff, 0xff, 0x34, 0xb4, 0xa5, 0x8e, 0x25, 0x0a, 0x00, 0x00, + 0x0c, 0x1a, 0x2f, 0xdf, 0xff, 0x57, 0x5f, 0x7d, 0x17, 0x5b, 0xf6, 0xe7, 0xc3, 0xbf, 0x03, 0x00, + 0x00, 0xff, 0xff, 0xd0, 0x3a, 0xc4, 0x88, 0x25, 0x0a, 0x00, 0x00, } func (m *RawAclRecord) Marshal() (dAtA []byte, err error) { @@ -1365,10 +1365,10 @@ func (m *AclRoot) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x28 } - if len(m.DerivationScheme) > 0 { - i -= len(m.DerivationScheme) - copy(dAtA[i:], m.DerivationScheme) - i = encodeVarintAclrecord(dAtA, i, uint64(len(m.DerivationScheme))) + if len(m.DerivationParams) > 0 { + i -= len(m.DerivationParams) + copy(dAtA[i:], m.DerivationParams) + i = encodeVarintAclrecord(dAtA, i, uint64(len(m.DerivationParams))) i-- dAtA[i] = 0x22 } @@ -2158,7 +2158,7 @@ func (m *AclRoot) Size() (n int) { if l > 0 { n += 1 + l + sovAclrecord(uint64(l)) } - l = len(m.DerivationScheme) + l = len(m.DerivationParams) if l > 0 { n += 1 + l + sovAclrecord(uint64(l)) } @@ -3120,9 +3120,9 @@ func (m *AclRoot) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DerivationScheme", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DerivationParams", wireType) } - var stringLen uint64 + var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowAclrecord @@ -3132,23 +3132,25 @@ func (m *AclRoot) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if byteLen < 0 { return ErrInvalidLengthAclrecord } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthAclrecord } if postIndex > l { return io.ErrUnexpectedEOF } - m.DerivationScheme = string(dAtA[iNdEx:postIndex]) + m.DerivationParams = append(m.DerivationParams[:0], dAtA[iNdEx:postIndex]...) + if m.DerivationParams == nil { + m.DerivationParams = []byte{} + } iNdEx = postIndex case 5: if wireType != 0 { diff --git a/commonspace/object/acl/aclrecordproto/protos/aclrecord.proto b/commonspace/object/acl/aclrecordproto/protos/aclrecord.proto index 4a6658d5..f64b9697 100644 --- a/commonspace/object/acl/aclrecordproto/protos/aclrecord.proto +++ b/commonspace/object/acl/aclrecordproto/protos/aclrecord.proto @@ -26,7 +26,7 @@ message AclRoot { bytes identity = 1; string spaceId = 2; bytes encryptedReadKey = 3; - string derivationScheme = 4; + bytes derivationParams = 4; int64 timestamp = 5; } diff --git a/commonspace/object/acl/list/aclrecordbuilder.go b/commonspace/object/acl/list/aclrecordbuilder.go index e85f6be1..8ea77746 100644 --- a/commonspace/object/acl/list/aclrecordbuilder.go +++ b/commonspace/object/acl/list/aclrecordbuilder.go @@ -4,11 +4,20 @@ import ( "github.com/anytypeio/any-sync/commonspace/object/acl/aclrecordproto" "github.com/anytypeio/any-sync/util/cidutil" "github.com/anytypeio/any-sync/util/crypto" + "github.com/anytypeio/any-sync/util/crypto/cryptoproto" "github.com/gogo/protobuf/proto" ) +type RootContent struct { + PrivKey crypto.PrivKey + SpaceId string + DerivationPath string + EncryptedReadKey []byte +} + type AclRecordBuilder interface { - FromRaw(rawIdRecord *aclrecordproto.RawAclRecordWithId) (rec *AclRecord, err error) + Unmarshall(rawIdRecord *aclrecordproto.RawAclRecordWithId) (rec *AclRecord, err error) + BuildRoot(content RootContent) (rec *aclrecordproto.RawAclRecordWithId, err error) } type aclRecordBuilder struct { @@ -16,92 +25,14 @@ type aclRecordBuilder struct { keyStorage crypto.KeyStorage } -func newAclRecordBuilder(id string, keyStorage crypto.KeyStorage) AclRecordBuilder { +func NewAclRecordBuilder(id string, keyStorage crypto.KeyStorage) AclRecordBuilder { return &aclRecordBuilder{ id: id, keyStorage: keyStorage, } } -// TODO: update with new logic -//func (a *aclRecordBuilder) BuildUserJoin(acceptPrivKeyBytes []byte, encSymKeyBytes []byte, state *AclState) (rec *aclrecordproto.RawAclRecord, err error) { -// acceptPrivKey, err := crypto.NewSigningEd25519PrivKeyFromBytes(acceptPrivKeyBytes) -// if err != nil { -// return -// } -// acceptPubKeyBytes, err := acceptPrivKey.GetPublic().Raw() -// if err != nil { -// return -// } -// encSymKey, err := crypto.UnmarshallAESKey(encSymKeyBytes) -// if err != nil { -// return -// } -// -// invite, err := state.Invite(acceptPubKeyBytes) -// if err != nil { -// return -// } -// -// encPrivKey, signPrivKey := state.UserKeys() -// var symKeys [][]byte -// for _, rk := range invite.EncryptedReadKeys { -// dec, err := encSymKey.Decrypt(rk) -// if err != nil { -// return nil, err -// } -// newEnc, err := encPrivKey.GetPublic().Encrypt(dec) -// if err != nil { -// return nil, err -// } -// symKeys = append(symKeys, newEnc) -// } -// idSignature, err := acceptPrivKey.Sign(state.Identity()) -// if err != nil { -// return -// } -// encPubKeyBytes, err := encPrivKey.GetPublic().Raw() -// if err != nil { -// return -// } -// -// userJoin := &aclrecordproto.AclUserJoin{ -// Identity: state.Identity(), -// EncryptionKey: encPubKeyBytes, -// AcceptSignature: idSignature, -// AcceptPubKey: acceptPubKeyBytes, -// EncryptedReadKeys: symKeys, -// } -// aclData := &aclrecordproto.AclData{AclContent: []*aclrecordproto.AclContentValue{ -// {Value: &aclrecordproto.AclContentValue_UserJoin{UserJoin: userJoin}}, -// }} -// marshalledJoin, err := aclData.Marshal() -// if err != nil { -// return -// } -// aclRecord := &aclrecordproto.AclRecord{ -// PrevId: state.LastRecordId(), -// Identity: state.Identity(), -// Data: marshalledJoin, -// CurrentReadKeyHash: state.CurrentReadKeyId(), -// Timestamp: time.Now().Unix(), -// } -// marshalledRecord, err := aclRecord.Marshal() -// if err != nil { -// return -// } -// recSignature, err := signPrivKey.Sign(marshalledRecord) -// if err != nil { -// return -// } -// rec = &aclrecordproto.RawAclRecord{ -// Payload: marshalledRecord, -// Signature: recSignature, -// } -// return -//} - -func (a *aclRecordBuilder) FromRaw(rawIdRecord *aclrecordproto.RawAclRecordWithId) (rec *AclRecord, err error) { +func (a *aclRecordBuilder) Unmarshall(rawIdRecord *aclrecordproto.RawAclRecordWithId) (rec *AclRecord, err error) { var ( rawRec = &aclrecordproto.RawAclRecord{} pubKey crypto.PubKey @@ -153,6 +84,31 @@ func (a *aclRecordBuilder) FromRaw(rawIdRecord *aclrecordproto.RawAclRecordWithI return } +func (a *aclRecordBuilder) BuildRoot(content RootContent) (rec *aclrecordproto.RawAclRecordWithId, err error) { + identity, err := content.PrivKey.GetPublic().Marshall() + if err != nil { + return + } + var derivationParams []byte + if content.DerivationPath != "" { + keyDerivation := &cryptoproto.KeyDerivation{ + Method: cryptoproto.DerivationMethod_Slip21, + DerivationPath: content.DerivationPath, + } + derivationParams, err = keyDerivation.Marshal() + if err != nil { + return + } + } + aclRoot := &aclrecordproto.AclRoot{ + Identity: identity, + SpaceId: content.SpaceId, + EncryptedReadKey: content.EncryptedReadKey, + DerivationParams: derivationParams, + } + return marshalAclRoot(aclRoot, content.PrivKey) +} + func verifyRaw( pubKey crypto.PubKey, rawRec *aclrecordproto.RawAclRecord, @@ -173,3 +129,31 @@ func verifyRaw( } return } + +func marshalAclRoot(aclRoot *aclrecordproto.AclRoot, key crypto.PrivKey) (rawWithId *aclrecordproto.RawAclRecordWithId, err error) { + marshalledRoot, err := aclRoot.Marshal() + if err != nil { + return + } + signature, err := key.Sign(marshalledRoot) + if err != nil { + return + } + raw := &aclrecordproto.RawAclRecord{ + Payload: marshalledRoot, + Signature: signature, + } + marshalledRaw, err := raw.Marshal() + if err != nil { + return + } + aclHeadId, err := cidutil.NewCidFromBytes(marshalledRaw) + if err != nil { + return + } + rawWithId = &aclrecordproto.RawAclRecordWithId{ + Payload: marshalledRaw, + Id: aclHeadId, + } + return +} diff --git a/commonspace/object/acl/list/aclrecordbuilder_test.go b/commonspace/object/acl/list/aclrecordbuilder_test.go index 24b5c9ce..27a75a28 100644 --- a/commonspace/object/acl/list/aclrecordbuilder_test.go +++ b/commonspace/object/acl/list/aclrecordbuilder_test.go @@ -5,39 +5,5 @@ import ( ) func TestAclRecordBuilder_BuildUserJoin(t *testing.T) { - //st, err := acllistbuilder2.NewListStorageWithTestName("userjoinexample.yml") - //require.NoError(t, err, "building storage should not result in error") - // - //testKeychain := st.(*acllistbuilder2.AclListStorageBuilder).GetKeychain() - //identity := testKeychain.GeneratedIdentities["D"] - //signPrivKey := testKeychain.SigningKeysByYAMLName["D"] - //encPrivKey := testKeychain.EncryptionKeysByYAMLName["D"] - //acc := &accountdata.AccountKeys{ - // Identity: []byte(identity), - // PrivKey: signPrivKey, - // EncKey: encPrivKey, - //} - // - //aclList, err := BuildAclListWithIdentity(acc, st) - //require.NoError(t, err, "building acl list should be without error") - //recordBuilder := newAclRecordBuilder(aclList.Id(), keychain.NewKeychain()) - //rk, err := testKeychain.GetKey("key.Read.EncKey").(*acllistbuilder2.SymKey).Key.Raw() - //require.NoError(t, err) - //privKey, err := testKeychain.GetKey("key.Sign.Onetime1").(signingkey.PrivKey).Raw() - //require.NoError(t, err) - // - //userJoin, err := recordBuilder.BuildUserJoin(privKey, rk, aclList.AclState()) - //require.NoError(t, err) - //marshalledJoin, err := userJoin.Marshal() - //require.NoError(t, err) - //id, err := cidutil.NewCidFromBytes(marshalledJoin) - //require.NoError(t, err) - //rawRec := &aclrecordproto.RawAclRecordWithId{ - // Payload: marshalledJoin, - // Id: id, - //} - //res, err := aclList.AddRawRecord(rawRec) - //require.True(t, res) - //require.NoError(t, err) - //require.Equal(t, aclrecordproto.AclUserPermissions_Writer, aclList.AclState().UserStates()[identity].Permissions) + return } diff --git a/commonspace/object/acl/list/aclstate.go b/commonspace/object/acl/list/aclstate.go index 4c4e4de9..8fff1a8b 100644 --- a/commonspace/object/acl/list/aclstate.go +++ b/commonspace/object/acl/list/aclstate.go @@ -3,6 +3,7 @@ package list import ( "errors" "fmt" + "github.com/anytypeio/any-sync/util/crypto/cryptoproto" "github.com/anytypeio/any-sync/app/logger" "github.com/anytypeio/any-sync/commonspace/object/acl/aclrecordproto" @@ -41,11 +42,10 @@ type AclState struct { userReadKeys map[string]crypto.SymKey userStates map[string]AclUserState statesAtRecord map[string][]AclUserState - //userInvites map[string]*aclrecordproto.AclUserInvite - key crypto.PrivKey - pubKey crypto.PubKey - keyStore crypto.KeyStorage - totalReadKeys int + key crypto.PrivKey + pubKey crypto.PubKey + keyStore crypto.KeyStorage + totalReadKeys int lastRecordId string @@ -62,7 +62,6 @@ func newAclStateWithKeys( userReadKeys: make(map[string]crypto.SymKey), userStates: make(map[string]AclUserState), statesAtRecord: make(map[string][]AclUserState), - //userInvites: make(map[string]*aclrecordproto.AclUserInvite), }, nil } @@ -72,7 +71,6 @@ func newAclState(id string) *AclState { userReadKeys: make(map[string]crypto.SymKey), userStates: make(map[string]AclUserState), statesAtRecord: make(map[string][]AclUserState), - //userInvites: make(map[string]*aclrecordproto.AclUserInvite), } } @@ -177,14 +175,8 @@ func (st *AclState) saveReadKeyFromRoot(record *AclRecord) (err error) { if !ok { return ErrIncorrectRoot } - if len(root.GetDerivationScheme()) != 0 { - var keyBytes []byte - keyBytes, err = st.key.Raw() - if err != nil { - return - } - - readKey, err = crypto.DeriveAccountSymmetric(keyBytes) + if root.DerivationParams != nil { + readKey, err = st.deriveKey(root.DerivationParams) if err != nil { return } @@ -267,113 +259,19 @@ func (st *AclState) applyUserPermissionChange(ch *aclrecordproto.AclUserPermissi } func (st *AclState) applyUserInvite(ch *aclrecordproto.AclUserInvite, recordId string) error { - //acceptPubKey, err := st.keyStore.PubKeyFromProto(ch.AcceptPublicKey) - //if err != nil { - // return nil - //} - //st.userInvites[string(ch.AcceptPublicKey)] = ch + // TODO: check old code and bring it back :-) return nil } func (st *AclState) applyUserJoin(ch *aclrecordproto.AclUserJoin, recordId string) error { - //invite, exists := st.userInvites[string(ch.AcceptPubKey)] - //if !exists { - // // TODO: change key to use same encoding - // return fmt.Errorf("no such invite with such public key %s", keys.EncodeBytesToString(ch.AcceptPubKey)) - //} - //chIdentity := string(ch.Identity) - //if _, exists = st.userStates[chIdentity]; exists { - // return ErrUserAlreadyExists - //} - // - //// validating signature - //signature := ch.GetAcceptSignature() - //verificationKey, err := crypto.UnmarshalEd25519PublicKeyProto(invite.AcceptPublicKey) - //if err != nil { - // return fmt.Errorf("public key verifying invite accepts is given in incorrect format: %v", err) - //} - // - //// TODO: intuitively we need to sign not only the identity but a more complicated payload - //res, err := verificationKey.Verify(ch.Identity, signature) - //if err != nil { - // return fmt.Errorf("verification returned error: %w", err) - //} - //if !res { - // return ErrInvalidSignature - //} - // - //// if ourselves -> we need to decrypt the read keys - //if st.identity == chIdentity { - // for _, key := range ch.EncryptedReadKeys { - // key, err := st.decryptReadKey(key) - // if err != nil { - // return ErrFailedToDecrypt - // } - // - // st.userReadKeys[recordId] = key - // } - //} - // - //// adding user to the list - //userState := &aclrecordproto.AclUserState{ - // Identity: ch.Identity, - // Permissions: invite.Permissions, - //} - //st.userStates[chIdentity] = userState return nil } func (st *AclState) applyUserAdd(ch *aclrecordproto.AclUserAdd, recordId string) error { - //chIdentity := string(ch.Identity) - //if _, exists := st.userStates[chIdentity]; exists { - // return ErrUserAlreadyExists - //} - // - //st.userStates[chIdentity] = &aclrecordproto.AclUserState{ - // Identity: ch.Identity, - // EncryptionKey: ch.EncryptionKey, - // Permissions: ch.Permissions, - //} - // - //if chIdentity == st.identity { - // for _, key := range ch.EncryptedReadKeys { - // key, hash, err := st.decryptReadKey(key) - // if err != nil { - // return ErrFailedToDecrypt - // } - // - // st.userReadKeys[hash] = key - // } - //} - return nil } func (st *AclState) applyUserRemove(ch *aclrecordproto.AclUserRemove, recordId string) error { - //chIdentity := string(ch.Identity) - //if chIdentity == st.identity { - // return ErrDocumentForbidden - //} - // - //if _, exists := st.userStates[chIdentity]; !exists { - // return ErrNoSuchUser - //} - // - //delete(st.userStates, chIdentity) - // - //for _, replace := range ch.ReadKeyReplaces { - // repIdentity := string(replace.Identity) - // // if this is our identity then we have to decrypt the key - // if repIdentity == st.identity { - // key, hash, err := st.decryptReadKey(replace.EncryptedReadKey) - // if err != nil { - // return ErrFailedToDecrypt - // } - // - // st.userReadKeys[hash] = key - // break - // } - //} return nil } @@ -404,32 +302,35 @@ func (st *AclState) isUserJoin(data *aclrecordproto.AclData) bool { return data.GetAclContent() != nil && data.GetAclContent()[0].GetUserJoin() != nil } -//func (st *AclState) isUserAdd(data *aclrecordproto.AclData, identity []byte) bool { -// // if we have a UserAdd, then it should always be the first one applied -// userAdd := data.GetAclContent()[0].GetUserAdd() -// return data.GetAclContent() != nil && userAdd != nil && bytes.Compare(userAdd.GetIdentity(), identity) == 0 -//} +func (st *AclState) isUserAdd(data *aclrecordproto.AclData, identity []byte) bool { + return false +} func (st *AclState) UserStates() map[string]AclUserState { return st.userStates } -//func (st *AclState) Invite(acceptPubKey []byte) (invite *aclrecordproto.AclUserInvite, err error) { -// invite, exists := st.userInvites[string(acceptPubKey)] -// if !exists { -// err = ErrNoSuchInvite -// return -// } -// if len(invite.EncryptedReadKeys) != st.totalReadKeys { -// err = ErrOldInvite -// } -// return -//} +func (st *AclState) Invite(acceptPubKey []byte) (invite *aclrecordproto.AclUserInvite, err error) { + return +} func (st *AclState) LastRecordId() string { return st.lastRecordId } +func (st *AclState) deriveKey(params []byte) (crypto.SymKey, error) { + keyDerivation := &cryptoproto.KeyDerivation{} + err := proto.Unmarshal(params, keyDerivation) + if err != nil { + return nil, err + } + keyBytes, err := st.key.Raw() + if err != nil { + return nil, err + } + return crypto.DeriveSymmetricKey(keyBytes, keyDerivation.DerivationPath) +} + func mapKeyFromPubKey(pubKey crypto.PubKey) string { return string(pubKey.Storage()) } diff --git a/commonspace/object/acl/list/list.go b/commonspace/object/acl/list/list.go index 5a486ae5..d714f407 100644 --- a/commonspace/object/acl/list/list.go +++ b/commonspace/object/acl/list/list.go @@ -58,12 +58,12 @@ type aclList struct { func BuildAclListWithIdentity(acc *accountdata.AccountKeys, storage liststorage.ListStorage) (AclList, error) { builder := newAclStateBuilderWithIdentity(acc) keyStorage := crypto.NewKeyStorage() - return build(storage.Id(), keyStorage, builder, newAclRecordBuilder(storage.Id(), keyStorage), storage) + return build(storage.Id(), keyStorage, builder, NewAclRecordBuilder(storage.Id(), keyStorage), storage) } func BuildAclList(storage liststorage.ListStorage) (AclList, error) { keyStorage := crypto.NewKeyStorage() - return build(storage.Id(), keyStorage, newAclStateBuilder(), newAclRecordBuilder(storage.Id(), crypto.NewKeyStorage()), storage) + return build(storage.Id(), keyStorage, newAclStateBuilder(), NewAclRecordBuilder(storage.Id(), crypto.NewKeyStorage()), storage) } func build(id string, keyStorage crypto.KeyStorage, stateBuilder *aclStateBuilder, recBuilder AclRecordBuilder, storage liststorage.ListStorage) (list AclList, err error) { @@ -77,7 +77,7 @@ func build(id string, keyStorage crypto.KeyStorage, stateBuilder *aclStateBuilde return } - record, err := recBuilder.FromRaw(rawRecordWithId) + record, err := recBuilder.Unmarshall(rawRecordWithId) if err != nil { return } @@ -89,7 +89,7 @@ func build(id string, keyStorage crypto.KeyStorage, stateBuilder *aclStateBuilde return } - record, err = recBuilder.FromRaw(rawRecordWithId) + record, err = recBuilder.Unmarshall(rawRecordWithId) if err != nil { return } @@ -140,7 +140,7 @@ func (a *aclList) AddRawRecord(rawRec *aclrecordproto.RawAclRecordWithId) (added if _, ok := a.indexes[rawRec.Id]; ok { return } - record, err := a.recordBuilder.FromRaw(rawRec) + record, err := a.recordBuilder.Unmarshall(rawRec) if err != nil { return } @@ -159,7 +159,7 @@ func (a *aclList) AddRawRecord(rawRec *aclrecordproto.RawAclRecordWithId) (added } func (a *aclList) IsValidNext(rawRec *aclrecordproto.RawAclRecordWithId) (err error) { - _, err = a.recordBuilder.FromRaw(rawRec) + _, err = a.recordBuilder.Unmarshall(rawRec) if err != nil { return } diff --git a/commonspace/payloads.go b/commonspace/payloads.go index f86703cb..00075379 100644 --- a/commonspace/payloads.go +++ b/commonspace/payloads.go @@ -1,30 +1,24 @@ package commonspace import ( - aclrecordproto "github.com/anytypeio/any-sync/commonspace/object/acl/aclrecordproto" - "github.com/anytypeio/any-sync/commonspace/object/keychain" + "github.com/anytypeio/any-sync/commonspace/object/acl/list" "github.com/anytypeio/any-sync/commonspace/object/tree/objecttree" "github.com/anytypeio/any-sync/commonspace/spacestorage" "github.com/anytypeio/any-sync/commonspace/spacesyncproto" "github.com/anytypeio/any-sync/util/cidutil" - "github.com/anytypeio/any-sync/util/keys/asymmetric/signingkey" + "github.com/anytypeio/any-sync/util/crypto" "hash/fnv" "math/rand" "time" ) const ( - SpaceReserved = "any-sync.space" - SpaceDerivationScheme = "derivation.standard" + SpaceReserved = "any-sync.space" ) func storagePayloadForSpaceCreate(payload SpaceCreatePayload) (storagePayload spacestorage.SpaceStorageCreatePayload, err error) { - // unmarshalling signing and encryption keys - identity, err := payload.SigningKey.GetPublic().Raw() - if err != nil { - return - } - encPubKey, err := payload.EncryptionKey.GetPublic().Raw() + // marshalling keys + identity, err := payload.SigningKey.GetPublic().Marshall() if err != nil { return } @@ -62,43 +56,32 @@ func storagePayloadForSpaceCreate(payload SpaceCreatePayload) (storagePayload sp RawHeader: marshalled, Id: spaceId, } - - // encrypting read key - hasher := fnv.New64() - _, err = hasher.Write(payload.ReadKey) - if err != nil { - return - } - readKeyHash := hasher.Sum64() - encReadKey, err := payload.EncryptionKey.GetPublic().Encrypt(payload.ReadKey) + readKey, err := payload.SigningKey.GetPublic().Encrypt(payload.ReadKey) if err != nil { return } - // preparing acl - aclRoot := &aclrecordproto.AclRoot{ - Identity: identity, - EncryptionKey: encPubKey, - SpaceId: spaceId, - EncryptedReadKey: encReadKey, - CurrentReadKeyHash: readKeyHash, - Timestamp: time.Now().Unix(), - } - rawWithId, err := marshalAclRoot(aclRoot, payload.SigningKey) + // building acl root + keyStorage := crypto.NewKeyStorage() + aclBuilder := list.NewAclRecordBuilder("", keyStorage) + aclRoot, err := aclBuilder.BuildRoot(list.RootContent{ + PrivKey: payload.SigningKey, + SpaceId: spaceId, + EncryptedReadKey: readKey, + }) if err != nil { return } - builder := objecttree.NewChangeBuilder(keychain.NewKeychain(), nil) + // building settings + builder := objecttree.NewChangeBuilder(keyStorage, nil) spaceSettingsSeed := make([]byte, 32) _, err = rand.Read(spaceSettingsSeed) if err != nil { return } - _, settingsRoot, err := builder.BuildRoot(objecttree.InitialContent{ - AclHeadId: rawWithId.Id, - Identity: aclRoot.Identity, + AclHeadId: aclRoot.Id, PrivKey: payload.SigningKey, SpaceId: spaceId, Seed: spaceSettingsSeed, @@ -111,7 +94,7 @@ func storagePayloadForSpaceCreate(payload SpaceCreatePayload) (storagePayload sp // creating storage storagePayload = spacestorage.SpaceStorageCreatePayload{ - AclWithId: rawWithId, + AclWithId: aclRoot, SpaceHeaderWithId: rawHeaderWithId, SpaceSettingsWithId: settingsRoot, } @@ -119,27 +102,19 @@ func storagePayloadForSpaceCreate(payload SpaceCreatePayload) (storagePayload sp } func storagePayloadForSpaceDerive(payload SpaceDerivePayload) (storagePayload spacestorage.SpaceStorageCreatePayload, err error) { - // unmarshalling signing and encryption keys - identity, err := payload.SigningKey.GetPublic().Raw() + // marshalling keys + identity, err := payload.SigningKey.GetPublic().Marshall() if err != nil { return } - signPrivKey, err := payload.SigningKey.Raw() - if err != nil { - return - } - encPubKey, err := payload.EncryptionKey.GetPublic().Raw() - if err != nil { - return - } - encPrivKey, err := payload.EncryptionKey.Raw() + pubKey, err := payload.SigningKey.GetPublic().Raw() if err != nil { return } // preparing replication key hasher := fnv.New64() - _, err = hasher.Write(identity) + _, err = hasher.Write(pubKey) if err != nil { return } @@ -172,35 +147,22 @@ func storagePayloadForSpaceDerive(payload SpaceDerivePayload) (storagePayload sp Id: spaceId, } - // deriving and encrypting read key - readKey, err := aclrecordproto.AclReadKeyDerive(signPrivKey, encPrivKey) - if err != nil { - return - } - hasher = fnv.New64() - _, err = hasher.Write(readKey.Bytes()) - if err != nil { - return - } - readKeyHash := hasher.Sum64() - - // preparing acl - aclRoot := &aclrecordproto.AclRoot{ - Identity: identity, - EncryptionKey: encPubKey, - SpaceId: spaceId, - DerivationScheme: SpaceDerivationScheme, - CurrentReadKeyHash: readKeyHash, - } - rawWithId, err := marshalAclRoot(aclRoot, payload.SigningKey) + // building acl root + keyStorage := crypto.NewKeyStorage() + aclBuilder := list.NewAclRecordBuilder("", keyStorage) + aclRoot, err := aclBuilder.BuildRoot(list.RootContent{ + PrivKey: payload.SigningKey, + SpaceId: spaceId, + DerivationPath: crypto.AnytypeAccountPath, + }) if err != nil { return } - builder := objecttree.NewChangeBuilder(keychain.NewKeychain(), nil) + // building settings + builder := objecttree.NewChangeBuilder(keyStorage, nil) _, settingsRoot, err := builder.BuildRoot(objecttree.InitialContent{ - AclHeadId: rawWithId.Id, - Identity: aclRoot.Identity, + AclHeadId: aclRoot.Id, PrivKey: payload.SigningKey, SpaceId: spaceId, ChangeType: SpaceReserved, @@ -211,37 +173,9 @@ func storagePayloadForSpaceDerive(payload SpaceDerivePayload) (storagePayload sp // creating storage storagePayload = spacestorage.SpaceStorageCreatePayload{ - AclWithId: rawWithId, + AclWithId: aclRoot, SpaceHeaderWithId: rawHeaderWithId, SpaceSettingsWithId: settingsRoot, } return } - -func marshalAclRoot(aclRoot *aclrecordproto.AclRoot, key signingkey.PrivKey) (rawWithId *aclrecordproto.RawAclRecordWithId, err error) { - marshalledRoot, err := aclRoot.Marshal() - if err != nil { - return - } - signature, err := key.Sign(marshalledRoot) - if err != nil { - return - } - raw := &aclrecordproto.RawAclRecord{ - Payload: marshalledRoot, - Signature: signature, - } - marshalledRaw, err := raw.Marshal() - if err != nil { - return - } - aclHeadId, err := cidutil.NewCidFromBytes(marshalledRaw) - if err != nil { - return - } - rawWithId = &aclrecordproto.RawAclRecordWithId{ - Payload: marshalledRaw, - Id: aclHeadId, - } - return -} diff --git a/commonspace/space.go b/commonspace/space.go index f6de90ea..ece13042 100644 --- a/commonspace/space.go +++ b/commonspace/space.go @@ -23,8 +23,7 @@ import ( "github.com/anytypeio/any-sync/commonspace/syncstatus" "github.com/anytypeio/any-sync/net/peer" "github.com/anytypeio/any-sync/nodeconf" - "github.com/anytypeio/any-sync/util/keys/asymmetric/encryptionkey" - "github.com/anytypeio/any-sync/util/keys/asymmetric/signingkey" + "github.com/anytypeio/any-sync/util/crypto" "github.com/anytypeio/any-sync/util/multiqueue" "github.com/anytypeio/any-sync/util/slice" "github.com/cheggaaa/mb/v3" @@ -42,9 +41,7 @@ var ( type SpaceCreatePayload struct { // SigningKey is the signing key of the owner - SigningKey signingkey.PrivKey - // EncryptionKey is the encryption key of the owner - EncryptionKey encryptionkey.PrivKey + SigningKey crypto.PrivKey // SpaceType is an arbitrary string SpaceType string // ReadKey is a first symmetric encryption key for a space @@ -63,10 +60,9 @@ type HandleMessage struct { } type SpaceDerivePayload struct { - SigningKey signingkey.PrivKey - EncryptionKey encryptionkey.PrivKey - SpaceType string - SpacePayload []byte + SigningKey crypto.PrivKey + SpaceType string + SpacePayload []byte } type SpaceDescription struct { diff --git a/util/crypto/cryptoproto/crypto.pb.go b/util/crypto/cryptoproto/crypto.pb.go index 338c1dd9..0f1120cc 100644 --- a/util/crypto/cryptoproto/crypto.pb.go +++ b/util/crypto/cryptoproto/crypto.pb.go @@ -50,6 +50,28 @@ func (KeyType) EnumDescriptor() ([]byte, []int) { return fileDescriptor_ddfeb19e486561de, []int{0} } +type DerivationMethod int32 + +const ( + DerivationMethod_Slip21 DerivationMethod = 0 +) + +var DerivationMethod_name = map[int32]string{ + 0: "Slip21", +} + +var DerivationMethod_value = map[string]int32{ + "Slip21": 0, +} + +func (x DerivationMethod) String() string { + return proto.EnumName(DerivationMethod_name, int32(x)) +} + +func (DerivationMethod) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_ddfeb19e486561de, []int{1} +} + type Key struct { Type KeyType `protobuf:"varint,1,opt,name=Type,proto3,enum=crypto.KeyType" json:"Type,omitempty"` Data []byte `protobuf:"bytes,2,opt,name=Data,proto3" json:"Data,omitempty"` @@ -102,9 +124,63 @@ func (m *Key) GetData() []byte { return nil } +type KeyDerivation struct { + Method DerivationMethod `protobuf:"varint,1,opt,name=method,proto3,enum=crypto.DerivationMethod" json:"method,omitempty"` + DerivationPath string `protobuf:"bytes,2,opt,name=derivationPath,proto3" json:"derivationPath,omitempty"` +} + +func (m *KeyDerivation) Reset() { *m = KeyDerivation{} } +func (m *KeyDerivation) String() string { return proto.CompactTextString(m) } +func (*KeyDerivation) ProtoMessage() {} +func (*KeyDerivation) Descriptor() ([]byte, []int) { + return fileDescriptor_ddfeb19e486561de, []int{1} +} +func (m *KeyDerivation) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *KeyDerivation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_KeyDerivation.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *KeyDerivation) XXX_Merge(src proto.Message) { + xxx_messageInfo_KeyDerivation.Merge(m, src) +} +func (m *KeyDerivation) XXX_Size() int { + return m.Size() +} +func (m *KeyDerivation) XXX_DiscardUnknown() { + xxx_messageInfo_KeyDerivation.DiscardUnknown(m) +} + +var xxx_messageInfo_KeyDerivation proto.InternalMessageInfo + +func (m *KeyDerivation) GetMethod() DerivationMethod { + if m != nil { + return m.Method + } + return DerivationMethod_Slip21 +} + +func (m *KeyDerivation) GetDerivationPath() string { + if m != nil { + return m.DerivationPath + } + return "" +} + func init() { proto.RegisterEnum("crypto.KeyType", KeyType_name, KeyType_value) + proto.RegisterEnum("crypto.DerivationMethod", DerivationMethod_name, DerivationMethod_value) proto.RegisterType((*Key)(nil), "crypto.Key") + proto.RegisterType((*KeyDerivation)(nil), "crypto.KeyDerivation") } func init() { @@ -112,19 +188,24 @@ func init() { } var fileDescriptor_ddfeb19e486561de = []byte{ - // 191 bytes of a gzipped FileDescriptorProto + // 263 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2e, 0x2d, 0xc9, 0xcc, 0xd1, 0x4f, 0x2e, 0xaa, 0x2c, 0x28, 0xc9, 0x87, 0x52, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0xfa, 0x60, 0xb2, 0x18, 0x2a, 0xa4, 0x07, 0xe6, 0x09, 0xb1, 0x41, 0x78, 0x4a, 0x76, 0x5c, 0xcc, 0xde, 0xa9, 0x95, 0x42, 0xca, 0x5c, 0x2c, 0x21, 0x95, 0x05, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x7c, 0x46, 0xfc, 0x7a, 0x50, 0xb5, 0xde, 0xa9, 0x95, 0x20, 0xe1, 0x20, 0xb0, 0xa4, 0x90, 0x10, 0x17, 0x8b, - 0x4b, 0x62, 0x49, 0xa2, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x4f, 0x10, 0x98, 0xad, 0x65, 0xc9, 0xc5, - 0x0e, 0x55, 0x24, 0x24, 0xc8, 0xc5, 0xeb, 0x9a, 0x62, 0x64, 0x6a, 0x6a, 0x68, 0x19, 0x50, 0x9a, - 0x94, 0x93, 0x99, 0x2c, 0xc0, 0x20, 0x24, 0xc4, 0xc5, 0x07, 0x13, 0x2a, 0xca, 0x2c, 0x4b, 0x2c, - 0x49, 0x15, 0x60, 0x14, 0x62, 0xe7, 0x62, 0x76, 0x74, 0x0d, 0x16, 0x60, 0x72, 0x32, 0x3c, 0xf1, - 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, - 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0x71, 0x1c, 0x3e, 0x49, 0x62, 0x03, 0x53, - 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x27, 0xb9, 0xba, 0xd8, 0xeb, 0x00, 0x00, 0x00, + 0x4b, 0x62, 0x49, 0xa2, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x4f, 0x10, 0x98, 0xad, 0x94, 0xc9, 0xc5, + 0xeb, 0x9d, 0x5a, 0xe9, 0x92, 0x5a, 0x94, 0x59, 0x96, 0x58, 0x92, 0x99, 0x9f, 0x27, 0x64, 0xc0, + 0xc5, 0x96, 0x9b, 0x5a, 0x92, 0x91, 0x9f, 0x02, 0x35, 0x4b, 0x02, 0x66, 0x16, 0x42, 0x8d, 0x2f, + 0x58, 0x3e, 0x08, 0xaa, 0x4e, 0x48, 0x8d, 0x8b, 0x2f, 0x05, 0x2e, 0x17, 0x90, 0x58, 0x92, 0x01, + 0xb6, 0x80, 0x33, 0x08, 0x4d, 0x54, 0xcb, 0x92, 0x8b, 0x1d, 0xea, 0x1e, 0x21, 0x41, 0x2e, 0x5e, + 0xd7, 0x14, 0x23, 0x53, 0x53, 0x43, 0xcb, 0x80, 0xd2, 0xa4, 0x9c, 0xcc, 0x64, 0x01, 0x06, 0x21, + 0x21, 0x2e, 0x3e, 0x98, 0x10, 0x58, 0x57, 0xaa, 0x00, 0xa3, 0x10, 0x3b, 0x17, 0xb3, 0xa3, 0x6b, + 0xb0, 0x00, 0x93, 0x96, 0x1c, 0x97, 0x00, 0xba, 0xf5, 0x42, 0x5c, 0x5c, 0x6c, 0xc1, 0x39, 0x99, + 0x05, 0x46, 0x86, 0x02, 0x0c, 0x4e, 0x86, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, + 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, + 0x10, 0x25, 0x8e, 0x23, 0x50, 0x93, 0xd8, 0xc0, 0x94, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x65, + 0xdf, 0xa5, 0x11, 0x76, 0x01, 0x00, 0x00, } func (m *Key) Marshal() (dAtA []byte, err error) { @@ -162,6 +243,41 @@ func (m *Key) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *KeyDerivation) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *KeyDerivation) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *KeyDerivation) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DerivationPath) > 0 { + i -= len(m.DerivationPath) + copy(dAtA[i:], m.DerivationPath) + i = encodeVarintCrypto(dAtA, i, uint64(len(m.DerivationPath))) + i-- + dAtA[i] = 0x12 + } + if m.Method != 0 { + i = encodeVarintCrypto(dAtA, i, uint64(m.Method)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + func encodeVarintCrypto(dAtA []byte, offset int, v uint64) int { offset -= sovCrypto(v) base := offset @@ -189,6 +305,22 @@ func (m *Key) Size() (n int) { return n } +func (m *KeyDerivation) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Method != 0 { + n += 1 + sovCrypto(uint64(m.Method)) + } + l = len(m.DerivationPath) + if l > 0 { + n += 1 + l + sovCrypto(uint64(l)) + } + return n +} + func sovCrypto(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -298,6 +430,107 @@ func (m *Key) Unmarshal(dAtA []byte) error { } return nil } +func (m *KeyDerivation) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: KeyDerivation: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: KeyDerivation: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Method", wireType) + } + m.Method = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Method |= DerivationMethod(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DerivationPath", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthCrypto + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthCrypto + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DerivationPath = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipCrypto(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthCrypto + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipCrypto(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/util/crypto/cryptoproto/protos/crypto.proto b/util/crypto/cryptoproto/protos/crypto.proto index dea6164b..d74f0b61 100644 --- a/util/crypto/cryptoproto/protos/crypto.proto +++ b/util/crypto/cryptoproto/protos/crypto.proto @@ -8,7 +8,16 @@ enum KeyType { AES = 2; } +enum DerivationMethod { + Slip21 = 0; +} + message Key { KeyType Type = 1; bytes Data = 2; } + +message KeyDerivation { + DerivationMethod method = 1; + string derivationPath = 2; +} \ No newline at end of file diff --git a/util/crypto/derived.go b/util/crypto/derived.go index f12fca51..1c3dbe93 100644 --- a/util/crypto/derived.go +++ b/util/crypto/derived.go @@ -2,10 +2,10 @@ package crypto import "github.com/anytypeio/go-slip21" -const anytypeAccountPath = "m/SLIP-0021/anytype/account" +const AnytypeAccountPath = "m/SLIP-0021/anytype/account" -func DeriveAccountSymmetric(seed []byte) (SymKey, error) { - master, err := slip21.DeriveForPath(anytypeAccountPath, seed) +func DeriveSymmetricKey(seed []byte, path string) (SymKey, error) { + master, err := slip21.DeriveForPath(path, seed) if err != nil { return nil, err } diff --git a/util/keys/decode.go b/util/crypto/encoder.go similarity index 65% rename from util/keys/decode.go rename to util/crypto/encoder.go index 374241de..64432dee 100644 --- a/util/keys/decode.go +++ b/util/crypto/encoder.go @@ -1,11 +1,10 @@ -package keys +package crypto import ( "encoding/base64" - "github.com/anytypeio/any-sync/util/crypto" ) -func EncodeKeyToString[T crypto.Key](key T) (str string, err error) { +func EncodeKeyToString[T Key](key T) (str string, err error) { raw, err := key.Raw() if err != nil { return @@ -18,7 +17,7 @@ func EncodeBytesToString(bytes []byte) string { return base64.StdEncoding.EncodeToString(bytes) } -func DecodeKeyFromString[T crypto.Key](str string, construct func([]byte) (T, error), def T) (T, error) { +func DecodeKeyFromString[T Key](str string, construct func([]byte) (T, error), def T) (T, error) { dec, err := DecodeBytesFromString(str) if err != nil { return def, err diff --git a/util/keys/asymmetric/encryptionkey/encryptionkey.go b/util/keys/asymmetric/encryptionkey/encryptionkey.go deleted file mode 100644 index 9c4215ce..00000000 --- a/util/keys/asymmetric/encryptionkey/encryptionkey.go +++ /dev/null @@ -1,18 +0,0 @@ -package encryptionkey - -import ( - "github.com/anytypeio/any-sync/util/crypto" -) - -type PrivKey interface { - crypto.Key - - Decrypt([]byte) ([]byte, error) - GetPublic() PubKey -} - -type PubKey interface { - crypto.Key - - Encrypt(data []byte) ([]byte, error) -} diff --git a/util/keys/asymmetric/encryptionkey/rsa.go b/util/keys/asymmetric/encryptionkey/rsa.go deleted file mode 100644 index 855daf55..00000000 --- a/util/keys/asymmetric/encryptionkey/rsa.go +++ /dev/null @@ -1,275 +0,0 @@ -package encryptionkey - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/sha512" - "crypto/subtle" - "crypto/x509" - "errors" - "github.com/anytypeio/any-sync/util/crypto" - "github.com/cespare/xxhash" - mrand "golang.org/x/exp/rand" - "io" - "math" - "math/big" -) - -var bigZero = big.NewInt(0) -var bigOne = big.NewInt(1) - -var MinRsaKeyBits = 2048 - -var ErrKeyLengthTooSmall = errors.New("error key length too small") - -type EncryptionRsaPrivKey struct { - privKey rsa.PrivateKey -} - -type EncryptionRsaPubKey struct { - pubKey rsa.PublicKey -} - -func (e *EncryptionRsaPubKey) Equals(key crypto.Key) bool { - other, ok := (key).(*EncryptionRsaPubKey) - if !ok { - return keyEquals(e, key) - } - - return e.pubKey.N.Cmp(other.pubKey.N) == 0 && e.pubKey.E == other.pubKey.E -} - -func (e *EncryptionRsaPubKey) Raw() ([]byte, error) { - return x509.MarshalPKIXPublicKey(&e.pubKey) -} - -func (e *EncryptionRsaPubKey) Encrypt(data []byte) ([]byte, error) { - hash := sha512.New() - return rsa.EncryptOAEP(hash, rand.Reader, &e.pubKey, data, nil) -} - -func (e *EncryptionRsaPrivKey) Equals(key crypto.Key) bool { - other, ok := (key).(*EncryptionRsaPrivKey) - if !ok { - return keyEquals(e, key) - } - - return e.privKey.N.Cmp(other.privKey.N) == 0 && e.privKey.E == other.privKey.E -} - -func (e *EncryptionRsaPrivKey) Raw() ([]byte, error) { - b := x509.MarshalPKCS1PrivateKey(&e.privKey) - return b, nil -} - -func (e *EncryptionRsaPrivKey) Decrypt(bytes []byte) ([]byte, error) { - hash := sha512.New() - return rsa.DecryptOAEP(hash, rand.Reader, &e.privKey, bytes, nil) -} - -func (e *EncryptionRsaPrivKey) GetPublic() PubKey { - return &EncryptionRsaPubKey{pubKey: e.privKey.PublicKey} -} - -func GenerateRandomRSAKeyPair(bits int) (PrivKey, PubKey, error) { - return GenerateRSAKeyPair(bits, rand.Reader) -} - -func GenerateRSAKeyPair(bits int, src io.Reader) (PrivKey, PubKey, error) { - if bits < MinRsaKeyBits { - return nil, nil, ErrKeyLengthTooSmall - } - priv, err := rsa.GenerateKey(src, bits) - if err != nil { - return nil, nil, err - } - pk := priv.PublicKey - return &EncryptionRsaPrivKey{privKey: *priv}, &EncryptionRsaPubKey{pubKey: pk}, nil -} - -func DeriveRSAKePair(bits int, seed []byte) (PrivKey, PubKey, error) { - if bits < MinRsaKeyBits { - return nil, nil, ErrKeyLengthTooSmall - } - seed64 := xxhash.Sum64(seed) - priv, err := rsaGenerateMultiPrimeKey(mrand.New(mrand.NewSource(seed64)), 2, bits) - if err != nil { - return nil, nil, err - } - pk := priv.PublicKey - return &EncryptionRsaPrivKey{privKey: *priv}, &EncryptionRsaPubKey{pubKey: pk}, nil -} - -func NewEncryptionRsaPrivKeyFromBytes(bytes []byte) (PrivKey, error) { - sk, err := x509.ParsePKCS1PrivateKey(bytes) - if err != nil { - return nil, err - } - if sk.N.BitLen() < MinRsaKeyBits { - return nil, ErrKeyLengthTooSmall - } - return &EncryptionRsaPrivKey{privKey: *sk}, nil -} - -func NewEncryptionRsaPubKeyFromBytes(bytes []byte) (PubKey, error) { - pub, err := x509.ParsePKIXPublicKey(bytes) - if err != nil { - return nil, err - } - pk, ok := pub.(*rsa.PublicKey) - if !ok { - return nil, errors.New("not actually an rsa public key") - } - if pk.N.BitLen() < MinRsaKeyBits { - return nil, ErrKeyLengthTooSmall - } - - return &EncryptionRsaPubKey{pubKey: *pk}, nil -} - -func keyEquals(k1, k2 crypto.Key) bool { - a, err := k1.Raw() - if err != nil { - return false - } - b, err := k2.Raw() - if err != nil { - return false - } - return subtle.ConstantTimeCompare(a, b) == 1 -} - -// generateMultiPrimeKey is a copied original rsa.GenerateMultiPrimeKey but without randutil.MaybeReadByte calls -func rsaGenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*rsa.PrivateKey, error) { - - priv := new(rsa.PrivateKey) - priv.E = 65537 - - if nprimes < 2 { - return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2") - } - - if bits < 64 { - primeLimit := float64(uint64(1) << uint(bits/nprimes)) - // pi approximates the number of primes less than primeLimit - pi := primeLimit / (math.Log(primeLimit) - 1) - // Generated primes start with 11 (in binary) so we can only - // use a quarter of them. - pi /= 4 - // Use a factor of two to ensure that key generation terminates - // in a reasonable amount of time. - pi /= 2 - if pi <= float64(nprimes) { - return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key") - } - } - - primes := make([]*big.Int, nprimes) - -NextSetOfPrimes: - for { - todo := bits - // crypto/rand should set the top two bits in each prime. - // Thus each prime has the form - // p_i = 2^bitlen(p_i) × 0.11... (in base 2). - // And the product is: - // P = 2^todo × α - // where α is the product of nprimes numbers of the form 0.11... - // - // If α < 1/2 (which can happen for nprimes > 2), we need to - // shift todo to compensate for lost bits: the mean value of 0.11... - // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2 - // will give good results. - if nprimes >= 7 { - todo += (nprimes - 2) / 5 - } - for i := 0; i < nprimes; i++ { - var err error - primes[i], err = randPrime(random, todo/(nprimes-i)) - if err != nil { - return nil, err - } - todo -= primes[i].BitLen() - } - - // Make sure that primes is pairwise unequal. - for i, prime := range primes { - for j := 0; j < i; j++ { - if prime.Cmp(primes[j]) == 0 { - continue NextSetOfPrimes - } - } - } - - n := new(big.Int).Set(bigOne) - totient := new(big.Int).Set(bigOne) - pminus1 := new(big.Int) - for _, prime := range primes { - n.Mul(n, prime) - pminus1.Sub(prime, bigOne) - totient.Mul(totient, pminus1) - } - if n.BitLen() != bits { - // This should never happen for nprimes == 2 because - // crypto/rand should set the top two bits in each prime. - // For nprimes > 2 we hope it does not happen often. - continue NextSetOfPrimes - } - - priv.D = new(big.Int) - e := big.NewInt(int64(priv.E)) - ok := priv.D.ModInverse(e, totient) - - if ok != nil { - priv.Primes = primes - priv.N = n - break - } - } - - priv.Precompute() - return priv, nil -} - -func randPrime(rand io.Reader, bits int) (*big.Int, error) { - if bits < 2 { - return nil, errors.New("crypto/rand: prime size must be at least 2-bit") - } - - b := uint(bits % 8) - if b == 0 { - b = 8 - } - - bytes := make([]byte, (bits+7)/8) - p := new(big.Int) - - for { - if _, err := io.ReadFull(rand, bytes); err != nil { - return nil, err - } - - // Clear bits in the first byte to make sure the candidate has a size <= bits. - bytes[0] &= uint8(int(1<= 2 { - bytes[0] |= 3 << (b - 2) - } else { - // Here b==1, because b cannot be zero. - bytes[0] |= 1 - if len(bytes) > 1 { - bytes[1] |= 0x80 - } - } - // Make the value odd since an even number this large certainly isn't prime. - bytes[len(bytes)-1] |= 1 - - p.SetBytes(bytes) - if p.ProbablyPrime(20) { - return p, nil - } - } -} diff --git a/util/keys/asymmetric/encryptionkey/rsa_test.go b/util/keys/asymmetric/encryptionkey/rsa_test.go deleted file mode 100644 index 55b2bfd8..00000000 --- a/util/keys/asymmetric/encryptionkey/rsa_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package encryptionkey - -import ( - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "testing" -) - -func TestDeriveRSAKePair(t *testing.T) { - privKey1, _, err := DeriveRSAKePair(4096, []byte("test seed")) - require.NoError(t, err) - - privKey2, _, err := DeriveRSAKePair(4096, []byte("test seed")) - require.NoError(t, err) - data := []byte("test data") - - encryped, err := privKey1.GetPublic().Encrypt(data) - require.NoError(t, err) - - decrypted, err := privKey2.Decrypt(encryped) - require.NoError(t, err) - - assert.Equal(t, data, decrypted) -} diff --git a/util/keys/asymmetric/signingkey/edwards25519/ed25519.go b/util/keys/asymmetric/signingkey/edwards25519/ed25519.go deleted file mode 100644 index 12e8086a..00000000 --- a/util/keys/asymmetric/signingkey/edwards25519/ed25519.go +++ /dev/null @@ -1,53 +0,0 @@ -package edwards25519 - -import ( - "crypto/ed25519" - "crypto/sha512" - "filippo.io/edwards25519" - "golang.org/x/crypto/curve25519" -) - -// Ed25519PublicKeyToCurve25519 converts an Ed25519 public key to a Curve25519 public key -func Ed25519PublicKeyToCurve25519(pk ed25519.PublicKey) []byte { - // Unmarshalling public key into edwards curve point - epk, err := (&edwards25519.Point{}).SetBytes(pk) - if err != nil { - panic(err) - } - // converting to curve25519 (see here for more details https://github.com/golang/go/issues/20504) - return epk.BytesMontgomery() -} - -/* - * ISC License - * - * Copyright (c) 2013-2020 - * Frank Denis - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -// https://github.com/jedisct1/libsodium/blob/master/src/libsodium/crypto_sign/ed25519/ref10/keypair.c#L69-L83 - -// Ed25519PrivateKeyToCurve25519 converts an Ed25519 private key to a Curve25519 private key -func Ed25519PrivateKeyToCurve25519(pk ed25519.PrivateKey) []byte { - h := sha512.New() - h.Write(pk.Seed()) - out := h.Sum(nil) - - out[0] &= 248 - out[31] &= 127 - out[31] |= 64 - - return out[:curve25519.ScalarSize] -} diff --git a/util/keys/asymmetric/signingkey/signingkey.go b/util/keys/asymmetric/signingkey/signingkey.go deleted file mode 100644 index f284f87a..00000000 --- a/util/keys/asymmetric/signingkey/signingkey.go +++ /dev/null @@ -1,59 +0,0 @@ -package signingkey - -import ( - "crypto/ed25519" - "crypto/rand" - "github.com/anytypeio/any-sync/util/keys/asymmetric/signingkey/edwards25519" - "golang.org/x/crypto/blake2b" - "golang.org/x/crypto/nacl/box" -) - -type PrivKey interface { - //crypto.Key - - Sign([]byte) ([]byte, error) - GetPublic() PubKey -} - -type PubKey interface { - //crypto.Key - - Verify(data []byte, sig []byte) (bool, error) -} - -func EncryptWithEd25519(pk ed25519.PublicKey, msg []byte) []byte { - conv := edwards25519.Ed25519PublicKeyToCurve25519(pk) - return Encrypt((*[32]byte)(conv), msg) -} - -func DecryptWithEd25519(pub ed25519.PublicKey, priv ed25519.PrivateKey, msg []byte) []byte { - cPub := edwards25519.Ed25519PublicKeyToCurve25519(pub) - cPriv := edwards25519.Ed25519PrivateKeyToCurve25519(priv) - return Decrypt((*[32]byte)(cPriv), (*[32]byte)(cPub), msg) -} - -func Encrypt(pubKey *[32]byte, msg []byte) []byte { - var nonce [24]byte - epk, esk, _ := box.GenerateKey(rand.Reader) - nonceWriter, _ := blake2b.New(24, nil) - nonceSlice := nonceWriter.Sum(append(epk[:], pubKey[:]...)) - copy(nonce[:], nonceSlice) - - return box.Seal(epk[:], msg, &nonce, pubKey, esk) -} - -func Decrypt(privKey, pubKey *[32]byte, encrypted []byte) []byte { - var epk [32]byte - var nonce [24]byte - copy(epk[:], encrypted[:32]) - - nonceWriter, _ := blake2b.New(24, nil) - nonceSlice := nonceWriter.Sum(append(epk[:], pubKey[:]...)) - copy(nonce[:], nonceSlice) - - decrypted, ok := box.Open(nil, encrypted[32:], &nonce, &epk, privKey) - if !ok { - panic("Decryption error.") - } - return decrypted -} diff --git a/util/keys/asymmetric/signingkey/signingkey_test.go b/util/keys/asymmetric/signingkey/signingkey_test.go deleted file mode 100644 index e0a1d0ca..00000000 --- a/util/keys/asymmetric/signingkey/signingkey_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package signingkey - -import ( - "crypto/ed25519" - "crypto/rand" - "fmt" - "testing" -) - -func Test(t *testing.T) { - pubKey, privKey, _ := ed25519.GenerateKey(rand.Reader) - msg := []byte("some stuffsafeesafujeaiofjoeai joaij fioaj iofaj oifaj foiajio fjao jo") - enc := EncryptWithEd25519(pubKey, msg) - dec := DecryptWithEd25519(pubKey, privKey, enc) - fmt.Println(string(enc), string(dec)) -}