Skip to content

Solve Man-in-the-middle attack #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 59 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
494634d
-_-
the-pesar Aug 21, 2024
280e098
update
the-pesar Aug 21, 2024
bbb7661
update
the-pesar Aug 21, 2024
09c49d3
update
the-pesar Aug 21, 2024
4de8759
update
the-pesar Aug 21, 2024
02c86e6
update
the-pesar Aug 21, 2024
b3ce5f8
update
the-pesar Aug 21, 2024
78942cf
update
the-pesar Aug 21, 2024
a2a13ed
update
the-pesar Aug 21, 2024
905658d
updayte
the-pesar Aug 21, 2024
7e33d34
update
the-pesar Aug 21, 2024
a099e25
update
the-pesar Aug 21, 2024
ec016fb
update
the-pesar Aug 21, 2024
3d11eff
update
the-pesar Aug 21, 2024
e0f8791
update
the-pesar Aug 21, 2024
130a2de
update
the-pesar Aug 21, 2024
c190eb0
update
the-pesar Aug 21, 2024
b7c9f7a
update
the-pesar Aug 21, 2024
36273b3
update
the-pesar Aug 21, 2024
03ac72b
update
the-pesar Aug 21, 2024
7bd42ce
udpate
the-pesar Aug 22, 2024
51a2db9
udpate
the-pesar Aug 22, 2024
73f764d
udpate
the-pesar Aug 22, 2024
41d2bcb
udpate
the-pesar Aug 22, 2024
352ee1f
udpate
the-pesar Aug 22, 2024
58907a0
udpate
the-pesar Aug 22, 2024
11c9f9f
udpate
the-pesar Aug 22, 2024
45ea005
udpate
the-pesar Aug 22, 2024
4c0f82a
udpate
the-pesar Aug 22, 2024
1194d51
udpate
the-pesar Aug 22, 2024
95cf0d9
udpate
the-pesar Aug 22, 2024
dcc1723
udpate
the-pesar Aug 22, 2024
6d3c971
udpate
the-pesar Aug 22, 2024
49dbc7e
udpate
the-pesar Aug 22, 2024
8952faa
udpate
the-pesar Aug 22, 2024
f619d79
udpate
the-pesar Aug 22, 2024
71174c6
udpate
the-pesar Aug 22, 2024
12a764b
udpate
the-pesar Aug 22, 2024
b5f3c2a
udpate
the-pesar Aug 22, 2024
d834e72
udpate
the-pesar Aug 22, 2024
12be03f
udpate
the-pesar Aug 22, 2024
eb91556
udpate
the-pesar Aug 22, 2024
7ca59bf
udpate
the-pesar Aug 22, 2024
35b97e5
udpate
the-pesar Aug 22, 2024
5e92881
udpate
the-pesar Aug 22, 2024
7e0364d
udpate
the-pesar Aug 22, 2024
3a54545
udpate
the-pesar Aug 22, 2024
ed40a1b
udpate
the-pesar Aug 22, 2024
9db0acd
udpate
the-pesar Aug 22, 2024
b87b492
udpate
the-pesar Aug 22, 2024
86dee57
udpate
the-pesar Aug 22, 2024
3eb886f
udpate
the-pesar Aug 22, 2024
62fca52
udpate
the-pesar Aug 22, 2024
5d959f9
udpate
the-pesar Aug 22, 2024
333d6f8
udpate
the-pesar Aug 22, 2024
55d4913
udpate
the-pesar Aug 22, 2024
8a96379
udpate
the-pesar Aug 22, 2024
7381bb6
udpate
the-pesar Aug 22, 2024
9e6645e
udpate
the-pesar Aug 22, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions bot/src/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,20 @@ export const handleCommands = () => {
web_app: { url: WEB_APP_URL },
type: 'web_app',
})

const query = ctx.update.message.text.split(' ')
if (query.length === 2) {
const username = query[1]
return ctx.reply(
`الان داری به کاربر ${username} پیام می‌فرستی`,
Markup.inlineKeyboard([
Markup.button.webApp('ورود به ربات', `${WEB_APP_URL}/@${username}`),
]),
)
const usernameWithHash = query[1].split('-')
if (usernameWithHash.length === 2) {
return ctx.reply(
`الان داری به کاربر ${usernameWithHash[0]} پیام می‌فرستی`,
Markup.inlineKeyboard([
Markup.button.webApp('ورود به ربات', `${WEB_APP_URL}/@${query[1]}`),
]),
)
}
}

ctx.reply(
START_MESSAGE,
Markup.inlineKeyboard([
Expand Down
Binary file modified bun.lockb
Binary file not shown.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
},
"dependencies": {
"@twa-dev/types": "^7.8.0",
"@types/crypto-js": "^4.2.2",
"axios": "^1.6.8",
"crypto-js": "^4.2.0",
"node-forge": "^1.3.1",
"pinia": "^2.1.7",
"telegraf": "^4.16.3",
Expand Down
1 change: 1 addition & 0 deletions server/database/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ func InitConnection() error {
func migration() {
DB.AutoMigrate(&User{})
DB.AutoMigrate(&Message{})
DB.AutoMigrate(&Session{})
}
36 changes: 20 additions & 16 deletions server/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func SetPublicKey(c *fiber.Ctx) error {
Model(&result).
Where("userid = ?", userid).
Update("public_key", body.PublicKey).
Update("public_key_hash", utils.GenerateSHA256(body.PublicKey))
Update("public_key_hash", utils.GenerateMD5(body.PublicKey))

return c.JSON(response.SetPublicKey{
PublicKey: body.PublicKey,
Expand Down Expand Up @@ -192,7 +192,7 @@ func SendMessage(c *fiber.Ctx) error {
log.Fatalf("Failed to publish message: %v", err)
}

return c.JSON(response.SendMessage{Message: "The message was sent"})
return c.JSON(response.SendMessage{Message: "The message was sent", SessionID: session.ID})
}

func GetPublicKey(c *fiber.Ctx) error {
Expand Down Expand Up @@ -227,12 +227,13 @@ func ReplayMessage(c *fiber.Ctx) error {
database.DB.Where("userid = ?", userid).Find(&user)

database.DB.Create(&database.Message{
Content: body.Message,
FromID: user.ID,
ToID: result.FromID,
OwnerID: result.OwnerID,
ParentID: result.ID,
Time: time.Now()})
Content: body.Message,
FromID: user.ID,
ToID: result.FromID,
SessionID: result.SessionID,
OwnerID: result.OwnerID,
ParentID: result.ID,
Time: time.Now()})

var targetUser database.User
database.DB.Where("id = ?", result.FromID).Find(&targetUser)
Expand Down Expand Up @@ -261,6 +262,7 @@ func GetMessages(c *fiber.Ctx) error {

var sourceUser database.User
database.DB.Where("id = ?", result[i].FromID).Find(&sourceUser)

if result[i].ParentID != 0 {
var res database.Message
database.DB.Where("id = ?", result[i].ParentID).Find(&res)
Expand All @@ -271,6 +273,7 @@ func GetMessages(c *fiber.Ctx) error {
ID: result[i].ID,
Content: result[i].Content,
Time: result[i].Time,
SessionID: result[i].SessionID,
Owner: owner, // true
CanReplay: true,
Quote: &response.Quote{
Expand All @@ -297,16 +300,17 @@ func GetMessages(c *fiber.Ctx) error {
database.DB.Where("id = ?", result[i].SessionID).Find(&session)

messages = append(messages, response.GetMessages{
ID: result[i].ID,
SessionID: result[i].SessionID,
Time: result[i].Time,
Owner: owner,
Quote: nil,
Content: result[i].Content,
CanReplay: true,
ID: result[i].ID,
SessionID: result[i].SessionID,
SessionKey: session.Key,
Time: result[i].Time,
Owner: owner,
Quote: nil,
Content: result[i].Content,
CanReplay: true,
})

database.DB.Delete(&database.Session{}, result[i].SessionID)
// database.DB.Delete(&database.Session{}, result[i].SessionID)
}

}
Expand Down
2 changes: 1 addition & 1 deletion server/request/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type SetPublicKey struct {
}

type SendMessage struct {
Id string `json:"id"`
Id uint64 `json:"id"`
Message string `json:"message"`
SessionKey string `json:"session_key"`
}
Expand Down
3 changes: 2 additions & 1 deletion server/response/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ type GetProfile struct {
}

type SendMessage struct {
Message string `json:"message"`
Message string `json:"message"`
SessionID uint64 `json:"session_id"`
}

type GetMe struct {
Expand Down
6 changes: 3 additions & 3 deletions server/utils/utils.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package utils

import (
"crypto/sha256"
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
Expand Down Expand Up @@ -76,8 +76,8 @@ func Parse(initData string) (InitData, error) {
return d, nil
}

func GenerateSHA256(input string) string {
hash := sha256.New()
func GenerateMD5(input string) string {
hash := md5.New()
hash.Write([]byte(input))
return hex.EncodeToString(hash.Sum(nil))
}
146 changes: 66 additions & 80 deletions src/components/Message.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,28 @@ import { ref } from 'vue'

import axios from '@/plugins/axios'
import { decryptE2EPacket, createE2EPacket } from '@/cryptography/DiffieHellman'
import * as RSA from '@/cryptography/RSA'
import * as AES from '@/cryptography/AES'

import Time from '@/components/UI/Time.vue'
import Button from '@/components/UI/Button.vue'
import Textarea from '@/components/UI/Textarea.vue'

const props = defineProps<{
id: number
text: string
time: string
owner: boolean
mark: boolean
canReplay: boolean
sender_public_key: string
quote?: {
message: {
id: number
content: string
time: string
owner: boolean
mark: boolean
can_replay: boolean
session_id: number
session_key?: string
sender_public_key: string
quote?: {
id: number
content: string
}
}
}>()

Expand All @@ -29,32 +35,34 @@ const replaySent = ref(false)
const vDecrypt = {
mounted: async (el: HTMLParagraphElement) => {
try {
const isQuote = !!el.getAttribute('quote')
if (props.owner) {
window.Telegram.WebApp.CloudStorage.getItem(
'receive_private_key',
async (error, privateKey) => {
const decryptedMsg = await decryptE2EPacket(
privateKey!,
props.sender_public_key,
el.innerText,
)
el.innerText = decryptedMsg!
},
)
} else {
window.Telegram.WebApp.CloudStorage.getItem(
'send_private_key',
async (error, privateKey) => {
const decryptedMsg = await decryptE2EPacket(
privateKey!,
props.sender_public_key,
el.innerText,
)
el.innerText = decryptedMsg!
},
)
}
window.Telegram.WebApp.CloudStorage.getItem(
String(props.message.session_id),
async (error, sessionKey) => {
if (!sessionKey) {
window.Telegram.WebApp.CloudStorage.getItem("private_key", async (error, value) => {
const decryptedSessionKey = await RSA.decrypt(props.message.session_key!, value!)
window.Telegram.WebApp.CloudStorage.setItem(String(props.message.session_id), decryptedSessionKey)

try {
const decryptedMsg = await AES.decrypt(el.innerText, decryptedSessionKey!)
el.innerText = decryptedMsg!
} catch (error) {
alert(error)
el.innerText = 'خطا در رمزگشایی!'
}
})
} else {
try {
const decryptedMsg = await AES.decrypt(el.innerText, sessionKey!)
el.innerText = decryptedMsg!
} catch (error) {
alert(error)
el.innerText = 'خطا در رمزگشایی!'
}
}

},
)
} catch (error) {
alert(error)
el.innerText = 'خطا در رمزگشایی!'
Expand All @@ -71,51 +79,36 @@ const vFocus = {
function Submit() {
if (!replayMessage.value) return

axios.get(`/get-key/${props.id}`).then(async ({ data: key }) => {
window.Telegram.WebApp.CloudStorage.getItem(
props.owner ? 'receive_private_key' : 'send_private_key',
async (error, privateKey) => {
const encryptedMsg = await createE2EPacket(
key,
privateKey!,
replayMessage.value,
)
axios
.post('/replay-message', {
message_id: props.id,
message: encryptedMsg,
})
.then(() => {
replaying.value = false
replayMessage.value = ''
replaySent.value = true
window.Telegram.WebApp.CloudStorage.getItem(String(props.message.session_id), async (error, sessionKey) => {
const encryptedMsg = await AES.encrypt(replayMessage.value, sessionKey!)
axios
.post('/replay-message', {
message_id: props.message.id,
message: encryptedMsg,
})
.then(() => {
replaying.value = false
replayMessage.value = ''
replaySent.value = true

setTimeout(() => (replaySent.value = false), 1500)
})
},
)
setTimeout(() => (replaySent.value = false), 1500)
}).catch((err: any) => {
alert(err)
})
})
}
</script>
<template>
<div
class="flex flex-col bg-[#ffffff] px-4 pt-3 pb-4 rounded-lg shadow-sm"
:class="mark && ['border-2 border-[#119af5]']"
>
<Time :value="time" class="text-gray-400 text-end text-sm"></Time>
<p
v-if="quote?.content"
class="border-r-4 rounded-md border-r-blue-500 pr-2 py-2 mt-2 truncate w-full"
style="background-color: rgba(137, 207, 240, 0.3)"
quote="true"
v-decrypt
>
{{ quote.content }}
<div class="flex flex-col bg-[#ffffff] px-4 pt-3 pb-4 rounded-lg shadow-sm">
<Time :value="message.time" class="text-gray-400 text-end text-sm"></Time>
<p v-if="message.quote?.content" class="border-r-4 rounded-md border-r-blue-500 pr-2 py-2 mt-2 truncate w-full"
style="background-color: rgba(137, 207, 240, 0.3)" quote="true" v-decrypt>
{{ message.quote.content }}
</p>

<p class="break-words py-2" dir="auto" v-decrypt>{{ text }}</p>
<p class="break-words py-2" dir="auto" v-decrypt>{{ message.content }}</p>

<template v-if="canReplay">
<template v-if="message.can_replay">
<div v-if="!replaying" class="flex justify-end text-gray-400 text-end">
<div class="flex items-center cursor-pointer" @click="replaying = true">
<span class="ml-1 text-sm">پاسخ</span>
Expand All @@ -124,16 +117,9 @@ function Submit() {
</div>

<div v-else class="flex flex-col mt-4">
<Textarea
v-model="replayMessage"
placeholder="پاسخ شما..."
v-focus
></Textarea>
<Textarea v-model="replayMessage" placeholder="پاسخ شما..." v-focus></Textarea>
<Button :block="true" class="mt-4" @click="Submit">ارسال</Button>
<p
class="text-center pt-4 text-[#119af5] font-bold cursor-pointer"
@click="replaying = false"
>
<p class="text-center pt-4 text-[#119af5] font-bold cursor-pointer" @click="replaying = false">
بیخیال
</p>
</div>
Expand Down
14 changes: 6 additions & 8 deletions src/components/Settings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ async function generateKeys() {

await generateKeyPair().then(({ privateKey, publicKey }) => {
receivePublicKey = publicKey
window.Telegram.WebApp.CloudStorage.setItem("receive_private_key", privateKey)
window.Telegram.WebApp.CloudStorage.setItem("private_key", privateKey)

})

await generateKeyPair().then(({ privateKey, publicKey }) => {
sendPublicKey = publicKey
window.Telegram.WebApp.CloudStorage.setItem("send_private_key", privateKey)
window.Telegram.WebApp.CloudStorage.setItem("private_key", privateKey)
})

axios
Expand All @@ -43,11 +43,10 @@ async function generateKeys() {
receive_public_key: receivePublicKey!,
})
.then(({ data }) => {
userStore.user.sendPublicKey = data.send_public_key
userStore.user.receivePublicKey = data.receive_public_key
userStore.user.publicKey = data.public_key

window.Telegram.WebApp.CloudStorage.setItem("send_public_key", data.send_public_key)
window.Telegram.WebApp.CloudStorage.setItem("receive_public_key", data.receive_public_key)
window.Telegram.WebApp.CloudStorage.setItem("public_key", data.send_public_key)
window.Telegram.WebApp.CloudStorage.setItem("public_key", data.receive_public_key)
})
.finally(() => {
loading.value = false
Expand All @@ -68,8 +67,7 @@ function importHandler(event: Event) {
receive_public_key: keys.receivePublicKey,
})
.then(({ data }) => {
userStore.user.sendPublicKey = data.send_public_key
userStore.user.receivePublicKey = data.receive_public_key
userStore.user.publicKey = data.public_key

window.Telegram.WebApp.CloudStorage.setItem("send_public_key", data.send_public_key)
window.Telegram.WebApp.CloudStorage.setItem("receive_public_key", data.receive_public_key)
Expand Down
Loading