Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
53 changes: 34 additions & 19 deletions src/TgSharp.Core/Auth/Authenticator.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,60 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using TgSharp.Core.Network;

namespace TgSharp.Core.Auth
{
public static class Authenticator
internal class Authenticator
{
public static async Task<Step3_Response> DoAuthentication(TcpTransport transport, CancellationToken token = default(CancellationToken))
private readonly MtProtoPlainSender sender;
private TaskCompletionSource<Step3_Response> completionSource;
internal Authenticator(WSTransport transport)
{
token.ThrowIfCancellationRequested();
sender = new MtProtoPlainSender(transport);
completionSource = new TaskCompletionSource<Step3_Response>();
}

var sender = new MtProtoPlainSender(transport);
internal Task<Step3_Response> DoAuthentication()
{
var step1 = new Step1_PQRequest();

await sender.Send(step1.ToBytes(), token).ConfigureAwait(false);
var step1Response = step1.FromBytes(await sender.Receive(token)
.ConfigureAwait(false));
sender.OnResponseReceived = (step1Message) => Sender_OnStep1ResponseReceived(step1, step1Message);
sender.Send(step1.ToBytes());

return completionSource.Task;
}

private void Sender_OnStep1ResponseReceived(Step1_PQRequest step1, byte[] step1Message)
{
var step1Response = step1.FromBytes(step1Message);

var step2 = new Step2_DHExchange();
await sender.Send(step2.ToBytes(
sender.OnResponseReceived = (step2message) => Sender_OnStep2ResponseReceived(step2, step2message);
sender.Send(step2.ToBytes(
step1Response.Nonce,
step1Response.ServerNonce,
step1Response.Fingerprints,
step1Response.Pq), token)
.ConfigureAwait(false);
step1Response.Pq));
}

private void Sender_OnStep2ResponseReceived(Step2_DHExchange step2, byte[] step2message)
{
var step2Response = step2.FromBytes(step2message);

var step2Response = step2.FromBytes(await sender.Receive(token)
.ConfigureAwait(false));

var step3 = new Step3_CompleteDHExchange();
await sender.Send(step3.ToBytes(
sender.OnResponseReceived = (step3Message) => Sender_OnStep3ResponseReceived(step3, step3Message);
sender.Send(step3.ToBytes(
step2Response.Nonce,
step2Response.ServerNonce,
step2Response.NewNonce,
step2Response.EncryptedAnswer), token)
.ConfigureAwait(false);

var step3Response = step3.FromBytes(await sender.Receive(token)
.ConfigureAwait(false));
step2Response.EncryptedAnswer));
}

return step3Response;
private void Sender_OnStep3ResponseReceived(Step3_CompleteDHExchange step3, byte[] response)
{
completionSource.SetResult(step3.FromBytes(response));
}
}
}
13 changes: 0 additions & 13 deletions src/TgSharp.Core/FileSessionStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,6 @@ public static Session FromBytes (byte [] buffer, ISessionStore store, string ses
{
using (var stream = new MemoryStream (buffer))
using (var reader = new BinaryReader (stream)) {
var id = reader.ReadUInt64 ();
var sequence = reader.ReadInt32 ();

// we do this in CI when running tests so that the they can always use a
// higher sequence than previous run
#if CI
sequence = Session.CurrentTime();
#endif

var salt = reader.ReadUInt64 ();
var lastMessageId = reader.ReadInt64 ();
var timeOffset = reader.ReadInt32 ();
Expand All @@ -80,9 +71,7 @@ public static Session FromBytes (byte [] buffer, ISessionStore store, string ses

return new Session () {
AuthKey = new AuthKey (authData),
Id = id,
Salt = salt,
Sequence = sequence,
LastMessageId = lastMessageId,
TimeOffset = timeOffset,
SessionExpires = sessionExpires,
Expand All @@ -97,8 +86,6 @@ internal byte [] ToBytes (Session session)
{
using (var stream = new MemoryStream ())
using (var writer = new BinaryWriter (stream)) {
writer.Write (session.Id);
writer.Write (session.Sequence);
writer.Write (session.Salt);
writer.Write (session.LastMessageId);
writer.Write (session.TimeOffset);
Expand Down
96 changes: 96 additions & 0 deletions src/TgSharp.Core/MTProto/Crypto/AesCtr.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace TgSharp.Core.MTProto.Crypto
{
/*
* AES-256-CTR Implementation
* Original implementation by OpenSSL, ported to C#
*/
public class AesCtr
{
// The input encrypted as though 128bit counter mode is being used. The extra
// state information to record how much of the 128bit block we have used is
// contained in number, and the encrypted counter is kept in encryptedCount. Both
// *num and ecount_buf must be initialised with zeros before the first call to
// CRYPTO_ctr128_encrypt().
//
// This algorithm assumes that the counter is in the x lower bits of the IV
// (ivec), and that the application has full control over overflow and the rest
// of the IV. This implementation takes NO responsibility for checking that
// the counter doesn't overflow into the rest of the IV when incremented.

public static void Ctr128Encrypt(byte[] input, byte[] key, ref byte[] ivec, ref byte[] encryptedCount, ref int number, byte[] output)
{
int n;
n = number;

int outputPos = 0, inputPos = 0;
int len = input.Length;

while (n != 0 && len != 0)
{
output[outputPos++] = (byte)(input[inputPos++] ^ encryptedCount[n]);
--len;
n = (n + 1) % 16;
}

while (len >= 16)
{
encryptedCount = EncryptBlock(ivec, key);
Ctr128Inc(ivec);
for (n = 0; n < 16; n += sizeof(ulong))
{
var xoredResult = BitConverter.GetBytes(BitConverter.ToUInt64(input, inputPos + n) ^ BitConverter.ToUInt64(encryptedCount, n));
Buffer.BlockCopy(xoredResult, 0, output, outputPos + n, 8);
}
len -= 16;
outputPos += 16;
inputPos += 16;
n = 0;
}

if (len != 0)
{
encryptedCount = EncryptBlock(ivec, key);
Ctr128Inc(ivec);
while (len-- != 0)
{
output[outputPos + n] = (byte)(input[inputPos + n] ^ encryptedCount[n]);
++n;
}
}
number = n;
}

// increment counter (128-bit int) by 1
private static void Ctr128Inc(byte[] counter)
{
uint n = 16, c = 1;

do
{
--n;
c += counter[n];
counter[n] = (byte)c;
c >>= 8;
} while (n != 0);
}

private static byte[] EncryptBlock(byte[] toEncrypt, byte[] key)
{
using (var aes = new RijndaelManaged())
{
aes.Key = key;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.None;
ICryptoTransform cTransform = aes.CreateEncryptor();
return cTransform.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);
}
}
}
}
46 changes: 46 additions & 0 deletions src/TgSharp.Core/Network/Message.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System;
using System.IO;
using System.Linq;
using TgSharp.Core.MTProto.Crypto;

namespace TgSharp.Core.Network
{
internal class Message
{
internal byte[] Body { get; private set; }

internal Message(byte[] body)
{
if (body == null)
throw new ArgumentNullException(nameof(body));

Body = body;
}

internal static Message Decode(byte[] body)
{
using (var memoryStream = new MemoryStream(body))
{
using (var binaryReader = new BinaryReader(memoryStream))
{
int length = binaryReader.ReadInt32();
return new Message(binaryReader.ReadBytes(length));
}
}
}

internal byte[] Encode()
{
using (var memoryStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memoryStream))
{
binaryWriter.Write(Body.Length);
binaryWriter.Write(Body);
return memoryStream.ToArray();
}
}
}

}
}
49 changes: 22 additions & 27 deletions src/TgSharp.Core/Network/MtProtoPlainSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,39 @@

namespace TgSharp.Core.Network
{
public class MtProtoPlainSender
internal class MtProtoPlainSender
{
public Action<byte[]> OnResponseReceived;

private int timeOffset;
private long lastMessageId;
private Random random;
private TcpTransport transport;
private WSTransport transport;

public MtProtoPlainSender(TcpTransport transport)
internal MtProtoPlainSender(WSTransport transport)
{
this.transport = transport;
transport.OnUnencryptedMessage += Transport_OnUnencryptedMessage;
random = new Random();
}

public async Task Send(byte[] data, CancellationToken token = default(CancellationToken))
private void Transport_OnUnencryptedMessage(Message message)
{
token.ThrowIfCancellationRequested();
using (var memoryStream = new MemoryStream(message.Body))
using (var binaryReader = new BinaryReader(memoryStream))
{
long authKeyid = binaryReader.ReadInt64();
long messageId = binaryReader.ReadInt64();
int messageLength = binaryReader.ReadInt32();

byte[] response = binaryReader.ReadBytes(messageLength);

OnResponseReceived?.Invoke(response);
}
}

internal void Send(byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memoryStream))
Expand All @@ -33,28 +49,7 @@ public MtProtoPlainSender(TcpTransport transport)

byte[] packet = memoryStream.ToArray();

await transport.Send(packet, token).ConfigureAwait(false);
}
}
}

public async Task<byte[]> Receive(CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();

var result = await transport.Receive(token).ConfigureAwait(false);

using (var memoryStream = new MemoryStream(result.Body))
{
using (BinaryReader binaryReader = new BinaryReader(memoryStream))
{
long authKeyid = binaryReader.ReadInt64();
long messageId = binaryReader.ReadInt64();
int messageLength = binaryReader.ReadInt32();

byte[] response = binaryReader.ReadBytes(messageLength);

return response;
transport.Send(packet);
}
}
}
Expand Down
Loading