Example #1
0
        public IKeyshareInstance GetKeyShareInstance(NamedGroup namedGroup)
        {
            switch (namedGroup)
            {
            case NamedGroup.ffdhe2048:
            case NamedGroup.ffdhe3072:
            case NamedGroup.ffdhe4096:
            case NamedGroup.ffdhe6144:
            case NamedGroup.ffdhe8192:
                return(new FiniteFieldInstance(namedGroup));

            case NamedGroup.secp256r1:
                return(new ECCurveInstance(namedGroup, 65));

            case NamedGroup.secp384r1:
                return(new ECCurveInstance(namedGroup, 97));

            case NamedGroup.secp521r1:
                return(new ECCurveInstance(namedGroup, 133));

            case NamedGroup.x25519:
            case NamedGroup.x448:
                return(new ECFunctionInstance(namedGroup));

            default:
                return(null);
            }
        }
Example #2
0
            public NamedGroup GetGroup(uint i)
            {
                if (i >= ActualNumberOfGroups)
                {
                    throw new ArgumentOutOfRangeException();
                }

                // calculate the offset of the NamedGroup
                uint offset = m_offsetGroupInfo + 2;

                for (uint j = 0; j < i; j++)
                {
                    if (PrecededBy16BitFlag())
                    {
                        offset += 2;
                    }
                    NamedGroup ngTemp = new NamedGroup(offset, m_bufTable);
                    offset += ngTemp.GetLength();
                }
                if (PrecededBy16BitFlag())
                {
                    offset += 2;
                }

                return(new NamedGroup(offset, m_bufTable));
            }
        public static KeyShareEntry Parse(MemoryCursor cursor)
        {
            var group = NamedGroup.Parse(cursor);
            var key   = ByteVector.SliceVectorBytes(cursor, 0..ushort.MaxValue);

            return(new KeyShareEntry(group, key));
        }
        public OpenSslECCurveKeyExchange(NamedGroup namedGroup)
        {
            _namedGroup = namedGroup;
            switch (NamedGroup)
            {
            case NamedGroup.secp256r1:
                _curveNid        = OBJ_sn2nid("prime256v1");
                _keyExchangeSize = 65;
                break;

            case NamedGroup.secp384r1:
                _curveNid        = OBJ_sn2nid("secp384r1");
                _keyExchangeSize = 97;
                break;

            case NamedGroup.secp521r1:
                _curveNid        = OBJ_sn2nid("secp521r1");
                _keyExchangeSize = 133;
                break;

            default:
                ExceptionHelper.ThrowException(new InvalidOperationException());
                break;
            }
        }
Example #5
0
 public static byte[] ServerECDHParams(NamedGroup namedCurve, byte[] pubkeyWith04)
 {
     using (var ms = new System.IO.MemoryStream())
     {
         ms.WriteByte((byte)ECCurveType.named_curve);
         ms.WriteValue((ushort)namedCurve);
         ms.WriteValue(pubkeyWith04, new[] { (byte)(pubkeyWith04.Length) });// Pubkey[0] == 0x04 uncompress pubkey
         return(ms.ToArray());
     }
 }
Example #6
0
        public KeyShareEntry(NamedGroup group, byte[] key)
        {
            Group       = group;
            KeyExchange = key;

            Data = new byte[KeyExchange.Length + 4];
            Buffer.BlockCopy(Utils.UInt16Bytes((ushort)Group), 0, Data, 0, 2);
            Buffer.BlockCopy(Utils.UInt16Bytes((ushort)KeyExchange.Length), 0, Data, 2, 2);
            Buffer.BlockCopy(KeyExchange, 0, Data, 4, KeyExchange.Length);
        }
        private IKeyExchange GetEcdheKeyExchange(NamedGroup namedGroup)
        {
            switch (namedGroup)
            {
            case NamedGroup.secp256r1:
            case NamedGroup.secp384r1:
            case NamedGroup.secp521r1:
                return(new OpenSslECCurveKeyExchange(namedGroup));

            case NamedGroup.x25519:
            case NamedGroup.x448:
                return(new OpenSslECFunctionKeyExchange(namedGroup));
            }
            return(null);
        }
Example #8
0
        public ECFunctionInstance(NamedGroup namedGroup)
        {
            _namedGroup = namedGroup;
            switch (namedGroup)
            {
            case NamedGroup.x25519:
                _keyExchangeSize = 32;
                _nid             = OBJ_sn2nid("X25519");
                break;

            case NamedGroup.x448:
                _keyExchangeSize = 56;
                _nid             = OBJ_sn2nid("X448");
                break;
            }
        }
Example #9
0
        private static async Task CheckSecret(NamedGroup group, byte[] privKey, byte[] peerKey, byte[] publicKey, byte[] secret)
        {
            using (var factory = new PipelineFactory())
            {
                var pipe  = factory.Create();
                var write = pipe.Alloc();
                write.Write(peerKey);
                write.FlushAsync().Wait();
                var reader = await pipe.ReadAsync();

                var instance = new FiniteFieldInstance(group);
                instance.GenerateKeys(privKey, publicKey);
                instance.SetPeerKey(reader.Buffer);
                var derived = instance.DeriveSecret();
                Assert.Equal <byte>(secret, derived);
            }
        }
Example #10
0
        private bool AreParametersExcluded(IMethodSymbol methodSymbol, NamedGroup group)
        {
            foreach (var parameter in methodSymbol.Parameters)
            {
                if (group.Parameter.Exclude != null &&
                    group.Parameter.Exclude.Any(x => parameter.HasAttribute(WellKnownTypeProvider.GetOrCreateTypeByMetadataName(x.Key))))
                {
                    return(true);
                }
                else if (group.Parameter.Include != null &&
                         group.Parameter.Include.Any(x => parameter.HasAttribute(WellKnownTypeProvider.GetOrCreateTypeByMetadataName(x.Key))))
                {
                    return(false);
                }
            }

            return(group.Parameter.Include.Any());
        }
Example #11
0
            public ushort Get16BitFlag(uint i)
            {
                if (!PrecededBy16BitFlag())
                {
                    throw new InvalidOperationException("invalid attempt to fetch 16 Bit Flag");
                }

                // calculate the offset of the 16 bit flag
                uint offset = m_offsetGroupInfo + 2;

                for (uint j = 0; j < i; j++)
                {
                    offset += 2;
                    NamedGroup ngTemp = new NamedGroup(offset, m_bufTable);
                    offset += ngTemp.GetLength();
                }

                return(m_bufTable.GetUshort(offset));
            }
Example #12
0
        public KeyShare(NamedGroup group, byte[] keyexchange) : base(null)
        {
            Entries = new[] { new KeyShareEntry(group, keyexchange) };

            var entriesBytes = new List <byte>();

            foreach (var entry in Entries)
            {
                entriesBytes.AddRange(entry.Data);
            }

            Data = new byte[2 + 2 + entriesBytes.Count];
            var bytesType = Utils.UInt16Bytes((ushort)Type);
            var bytesLen  = Utils.UInt16Bytes((ushort)entriesBytes.Count);

            Buffer.BlockCopy(bytesType, 0, Data, 0, 2);
            Buffer.BlockCopy(bytesLen, 0, Data, 2, 2);
            Buffer.BlockCopy(entriesBytes.ToArray(), 0, Data, 4, entriesBytes.Count);
        }
Example #13
0
        public ECCurveInstance(NamedGroup namedGroup, int keyExchangeSize)
        {
            _keyExchangeSize = keyExchangeSize;
            _namedGroup      = namedGroup;
            switch (namedGroup)
            {
            case NamedGroup.secp256r1:
                _curveNid = OBJ_sn2nid("prime256v1");
                break;

            case NamedGroup.secp384r1:
                _curveNid = OBJ_sn2nid("secp384r1");
                break;

            case NamedGroup.secp521r1:
                _curveNid = OBJ_sn2nid("secp521r1");
                break;
            }
        }
        public OpenSslECFunctionKeyExchange(NamedGroup namedGroup)
        {
            _namedGroup = namedGroup;
            switch (namedGroup)
            {
            case NamedGroup.x25519:
                _keyExchangeSize = 32;
                _nid             = OBJ_sn2nid("X25519");
                break;

            case NamedGroup.x448:
                _keyExchangeSize = 56;
                _nid             = OBJ_sn2nid("X448");
                break;

            default:
                ExceptionHelper.ThrowException(new InvalidOperationException());
                break;
            }
        }
Example #15
0
        public IKeyshareInstance GetKeyShareInstance(NamedGroup namedGroup)
        {
            switch (namedGroup)
            {
            case NamedGroup.secp256r1:
                return(new ECCurveInstance(_secp256r1, namedGroup, 65));

            case NamedGroup.secp384r1:
                return(new ECCurveInstance(_secp384r1, namedGroup, 97));

            case NamedGroup.secp521r1:
                return(new ECCurveInstance(_secp521r1, namedGroup, 133));

            case NamedGroup.x25519:
                return(null);

            default:
                return(null);
            }
        }
Example #16
0
        //https://tools.ietf.org/html/rfc5246#section-7.4.3

        public ServerKeyExchange(NamedGroup namedCurve, byte[] pubkeyWith04, SignatureAlgorithm signatureAlgorithm, byte[] signature) : base(null)
        {
            CurveType          = ECCurveType.named_curve;
            NamedCurve         = namedCurve;
            PubkeyLength       = (byte)(pubkeyWith04.Length);
            Pubkey             = pubkeyWith04;
            SignatureAlgorithm = signatureAlgorithm;
            SignatureLength    = (ushort)signature.Length;
            Signature          = signature;

            using (var ms = new System.IO.MemoryStream())
            {
                ms.WriteByte((byte)CurveType);
                ms.WriteValue((ushort)NamedCurve);
                ms.WriteValue(Pubkey, new[] { PubkeyLength });// Pubkey[0] == 0x04 uncompress pubkey
                ms.WriteValue((ushort)signatureAlgorithm);
                ms.WriteValue(Signature, Utils.UInt16Bytes(SignatureLength));

                Data = ms.ToArray();
            }
        }
Example #17
0
        private static async Task CheckSecret(NamedGroup group, byte[] privKey, byte[] peerKey, byte[] publicKey, byte[] secret)
        {
            using (var bufferPool = new MemoryPool())
            {
                var options = new PipeOptions(bufferPool);
                var pipe    = new Pipe(options);
                var write   = pipe.Writer.Alloc();
                write.WriteBigEndian((byte)peerKey.Length);
                write.Write(peerKey);
                await write.FlushAsync();

                var reader = await pipe.Reader.ReadAsync();

                var instance = new OpenSsl11.OpenSslFiniteFieldKeyExchange(group);
                instance.GenerateKeys(privKey, publicKey);
                SetPeerKey(reader, instance);
                var buffer = new byte[instance.KeyExchangeSize];
                var size   = instance.DeriveSecret(buffer);
                TestSecret(secret, buffer, size);
            }
        }
Example #18
0
        public ServerKeyExchangeParser(ReadableBuffer reader)
        {
            var originalSpan = reader.ToSpan();
            var span         = new BigEndianAdvancingSpan(originalSpan);

            span.Read <HandshakeHeader>();
            _curveType = span.Read <ECCurveType>();
            if (_curveType != ECCurveType.named_curve)
            {
                Alerts.AlertException.ThrowAlert(Alerts.AlertLevel.Fatal, Alerts.AlertDescription.handshake_failure, "We only support named curves");
            }

            _namedGroup = span.Read <NamedGroup>();
            _key        = span;
            span.ReadVector <byte>();
            var dataLength = originalSpan.Length - span.Length;

            _data = originalSpan.Slice(4, dataLength - 4);

            _signatureScheme = span.Read <SignatureScheme>();
            _signature       = span.ReadVector <ushort>().ToSpan();
            Debug.Assert(span.Length == 0);
        }
Example #19
0
 public void Hide(NamedGroup group)
 {
     group.visible = false;
     Hide(group.group);
 }
Example #20
0
 public FiniteFieldInstance(NamedGroup namedGroup)
 {
     _namedGroup = namedGroup;
 }
        public static ByteVector.CursorWritingContext StartWriting(MemoryCursor cursor, NamedGroup group)
        {
            group.WriteBytes(cursor);

            return(ByteVector.StartVectorWriting(cursor, 0..ushort.MaxValue));
        }
Example #22
0
 internal ECCurveInstance(SafeBCryptAlgorithmHandle algo, NamedGroup group, int keyExchangeSize)
 {
     _keyExchangeSize = keyExchangeSize;
     _group           = group;
     _algo            = algo;
 }
Example #23
0
 public void Show(NamedGroup group)
 {
     group.visible = true;
     Show(group.group);
 }
Example #24
0
            public ushort Get16BitFlag(uint i)
            {
                if (!PrecededBy16BitFlag())
                {
                    throw new InvalidOperationException("invalid attempt to fetch 16 Bit Flag");
                }

                // calculate the offset of the 16 bit flag
                uint offset = m_offsetGroupInfo + 2;
                for (uint j=0; j<i; j++)
                {
                    offset += 2;
                    NamedGroup ngTemp = new NamedGroup(offset, m_bufTable);
                    offset += ngTemp.GetLength();
                }

                return m_bufTable.GetUshort(offset);
            }
 public KeyShareEntry(NamedGroup group, MemoryBuffer key)
 {
     Group = group;
     Key   = key;
 }
Example #26
0
        private void VisitClass(
            ITypeSymbol classSymbol,
            NamedGroup group,
            Dictionary <Location, Diagnostic> diagnostics,
            ConcurrentDictionary <INamedTypeSymbol, bool> classCache)
        {
            if (!(classSymbol is INamedTypeSymbol typeSymbol))
            {
                return;
            }

            if (RequiredAttributeExists((c) => typeSymbol.TryGetDerivedAttribute(c), group.IncludedRequiredAttributes, group.ExcludedRequiredAttributes))
            {
                return;
            }

            if (group.Class != null)
            {
                if (!classCache.TryGetValue(typeSymbol, out bool isTheClass))
                {
                    isTheClass = false;

                    bool IsTheClassBySuffix()
                    {
                        if (typeSymbol.Name.EndsWith(group.Class.Suffix.Text, StringComparison.Ordinal))
                        {
                            return(true);
                        }
                        else if (group.Class.Suffix.IncludeParent &&
                                 typeSymbol.GetBaseTypes().Any(x => x.Name.EndsWith(group.Class.Suffix.Text, StringComparison.Ordinal)))
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }

                    if (group.Class.Accessibility != null &&
                        group.Class.Accessibility.All(a => a != typeSymbol.DeclaredAccessibility))
                    {
                        isTheClass = false;
                    }
                    else
                    {
                        if (group.Class.Suffix != null &&
                            group.Class.Parent == null)
                        {
                            isTheClass = IsTheClassBySuffix();
                        }
                        else if (group.Class.Parent != null &&
                                 typeSymbol.GetBaseTypesAndThis().Any(x => x == WellKnownTypeProvider.GetOrCreateTypeByMetadataName(group.Class.Parent)))
                        {
                            isTheClass = group.Class.Suffix != null?IsTheClassBySuffix() : true;
                        }

                        if (group.Class?.Exclude != null &&
                            RequiredAttributeExists((c) => typeSymbol.TryGetDerivedAttribute(c), group.Class.Exclude))
                        {
                            isTheClass = false;
                        }
                        else if (group.Class?.Include != null &&
                                 RequiredAttributeExists((c) => typeSymbol.TryGetDerivedAttribute(c), group.Class.Include))
                        {
                            isTheClass = true;
                        }
                    }

                    classCache.TryAdd(typeSymbol, isTheClass);
                }

                if (!isTheClass)
                {
                    return;
                }
            }

            foreach (var member in classSymbol.GetMembers())
            {
                if (!(member is IMethodSymbol methodSymbol) || methodSymbol.IsPropertyAccessor())
                {
                    continue;
                }

                var location = methodSymbol.Locations[0];
                if (diagnostics.ContainsKey(location)) // first NamedGroup in a sequence wins
                {
                    continue;
                }

                if (group.Method != null)
                {
                    if (group.Method.Static.HasValue && group.Method.Static != methodSymbol.IsStatic)
                    {
                        continue;
                    }

                    if (group.Method.IncludeConstructor.HasValue && group.Method.IncludeConstructor != methodSymbol.IsConstructor())
                    {
                        continue;
                    }

                    if (group.Method?.Accessibility?.All(a => a != methodSymbol.DeclaredAccessibility) == true)
                    {
                        continue;
                    }

                    if (group.Method?.Exclude != null &&
                        RequiredAttributeExists((c) => methodSymbol.TryGetDerivedAttribute(c), group.Method.Exclude))
                    {
                        continue;
                    }
                    else if (group.Method?.Include?.Any() == true &&
                             !RequiredAttributeExists((c) => methodSymbol.TryGetDerivedAttribute(c), group.Method.Include))
                    {
                        continue;
                    }
                }

                if (RequiredAttributeExists((c) => methodSymbol.TryGetDerivedAttribute(c), group.IncludedRequiredAttributes, group.ExcludedRequiredAttributes))
                {
                    continue;
                }

                if (group.Parameter != null && AreParametersExcluded(methodSymbol, group))
                {
                    continue;
                }

                diagnostics.Add(location, Diagnostic.Create(group.Message != null ? group.Message : Rule, location));
            }
        }
Example #27
0
            public NamedGroup GetGroup(uint i)
            {
                if (i >= ActualNumberOfGroups)
                {
                    throw new ArgumentOutOfRangeException();
                }

                // calculate the offset of the NamedGroup
                uint offset = m_offsetGroupInfo + 2;
                for (uint j=0; j<i; j++)
                {
                    if (PrecededBy16BitFlag())
                    {
                        offset += 2;
                    }
                    NamedGroup ngTemp = new NamedGroup(offset, m_bufTable);
                    offset += ngTemp.GetLength();
                }
                if (PrecededBy16BitFlag())
                {
                    offset += 2;
                }

                return new NamedGroup(offset, m_bufTable);
            }
 public OpenSslFiniteFieldKeyExchange(NamedGroup namedGroup) => _namedGroup = namedGroup;