-
Notifications
You must be signed in to change notification settings - Fork 0
/
expenses.nim
393 lines (286 loc) · 11.3 KB
/
expenses.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import strutils, std/strformat, std/os, std/times, std/threadpool
#TODO Change all Banner
var startBanner = "Welcome to expenses!\n"
var loginBanner = "Login\n"
var registerBanner = "Register\n"
var userBanner = "UserPanel\n"
#A HashMap containig the credentials collected from the Users.txt
var username = ""
var inactive_time = 0.0
proc checkLastInputTime() =
while true:
sleep(100)
let timeSinceInput = epochTime() - inactive_time
if timeSinceInput > 60:
echo "No user input in the last 2 minutes."
quit(QuitSuccess)
# Handle no user input logic here
proc setTime() =
inactive_time = epochTime()
proc timeCheck() =
let time = epochTime() - inactive_time
echo "Time: ", time
if time > 10.0:
quit(QuitSuccess)
#[
This functionr returns an unsigned integer typed in by the user which is not bigger then "bound"
]#
proc getUserInputInteger(bound: uint8): uint =
var userInput:uint = 0
setTime()
while true:
try:
userInput = parseUInt(stdin.readLine)
except CatchableError:
echo "Error please try again!"
quit(QuitFailure)
if userInput < bound:
return userInput
echo "Please enter a unsigned integer not bigger then ", bound
#TODO Maybe add bound like in getUserInputInteger(bound: uint8)
proc getUserInputString(): string =
setTime()
return stdin.readLine()
#Check if the username already exists. Returns true if exists else false
proc usernameExists(username: string): bool =
for _, path in walkDir("data"):
#TODO Could be a problem with different os because of unix and windows path
var splitPath = path.split('/')
if username == splitPath[1]:
return true
return false
proc badChars(input: string): bool =
if input.contains("..") or input.contains("/") or input.contains("\\"):
return true
return false
#Logic for Logging into the Application
proc login() =
setTime()
echo loginBanner
var counter = 3
while counter >= 1:
echo "Username > "
username = getUserInputString()
if not usernameExists(username):
dec counter
echo "Username does not exists, ", counter, " attempts left"
continue
echo "Password > "
let password = getUserInputString()
if password == readFile(fmt"data/{username}/passwd.txt"):
echo "Welcome ", username
return
dec counter
echo "Password was not correct, ", counter, " attempts left"
quit(QuitFailure)
#Logic for Registering a new User
proc register() =
echo registerBanner
var password = ""
while true:
echo "Username > "
username = getUserInputString()
if badChars(username):
echo "Enter another Username bad Character detected!"
quit(QuitFailure)
if usernameExists(username):
echo "Username already exists take another one\n"
quit(QuitFailure)
if username.len() < 1:
quit(QuitFailure)
echo "Password > "
password = getUserInputString()
if usernameExists(username):
echo "Username already exists take another one\n"
quit(QuitFailure)
break
#Check if username contains .. or /
createDir(fmt"data/{username}")
writeFile(fmt"data/{username}/passwd.txt", password)
createDir(fmt"data/{username}/Expenses")
#Testing inline assembly
asm """
nop
nop
nop
"""
template label(name, body) =
{.emit: astToStr(name) & ":".}
body
template goto(name) =
{.emit: "goto " & astToStr(name) & ";".}
proc userMenu() =
while true:
echo userBanner
echo "0. Add Expense\n1. Show Expenses\n2. Show Expense details\n3. Delete Expense\n4. Show max amount spend\n5. Delete Account\n6. Share Expense\n7. Exit\n"
let userChoice = getUserInputInteger(8)
#TODO handle crash wrong candidate name
case userChoice:
of 0:
#Stop path Traversal
var fileName = ""
while true:
echo "Enter the name of the expense > "
fileName = getUserInputString()
if badChars(fileName):
echo "Bad Char Detected!"
quit(QuitFailure)
break
echo "Enter a little description of the expense > "
let description = getUserInputString()
label a:
echo "Enter the amount you spend as an Integer > "
var amount = 0.0
#let amount = parseInt(stdin.readLine)
try:
amount = parseFloat(stdin.readLine)
except CatchableError:
goto a
#let toWrite = description & '\n' & intToStr(amount)
let toWrite = description & '\n' & amount.formatFloat(ffDecimal, 2)
writeFile(fmt"data/{username}/Expenses/{fileName}", toWrite)
of 1:
echo "These are all your expenses"
#TODO Refactor this return hashmap with every file/dir in the directory
for _, path in walkDir(fmt"data/{username}/Expenses/"):
#TODO Could be a problem with different os because of unix and windows path
var splitPath = path.split('/')
echo splitPath[3]
of 2:
echo "Enter the name of the expense > "
let expenseName = getUserInputString()
for _, path in walkDir(fmt"data/{username}/Expenses"):
#TODO Could be a problem with different os because of unix and windows path
let splitPath = path.split('/')
#First Vulnerability logical flaw
#User can traverse every directory he wants because or splitPath[3] != expenseName is bugged
asm """
nop
nop
nop
"""
#echo (path)
# echo (splitPath[3])
# echo(expenseName)
if (splitPath[3] == expenseName or splitPath[3] != expenseName) and fileExists(fmt"data/{username}/Expenses/{expenseName}") and not expenseName.contains("passwd.txt"):
let fileContent = readFile(fmt"data/{username}/Expenses/{expenseName}")
asm """
nop
nop
nop
"""
echo fileContent
break
of 3:
var expenseName = ""
while true:
echo "Enter the Name of the expense you want to delete > "
expenseName = getUserInputString()
if badChars(expenseName):
echo "Bad Character Detected!"
quit(QuitFailure)
break
let filePath = fmt"data/{username}/Expenses/{expenseName}"
if fileExists(filePath):
removeFile(filePath)
echo "Expense Deleted"
else:
echo "The expense you want to delete does not exist!"
of 4:
#var sum = 0
var sum = 0.0
for _, path in walkDir(fmt"data/{username}/Expenses"):
#TODO Could be a problem with different os because of unix and windows path
let lines = readLines(path, 2)
#sum += parseInt(lines[1])
sum += parseFloat(lines[1])
echo lines[1]
echo fmt"You spend: ${sum}"
of 5:
echo "Do you really want to delete your account? (y or n)"
setTime()
let choice = stdin.readLine()
case choice:
of "y":
removeDir(fmt"data/{username}")
quit(QuitSuccess)
of "n":
continue
else:
continue
of 6:
echo "With how many Users do you want to share the expense?"
var choice = getUserInputInteger(10)
let share = choice
var counter = 1
var users: seq[string]
if choice == 0:
continue
while choice > 0:
echo "Enter the name of the #", counter, " users"
let user = getUserInputString()
#Check if username exists if not continue to ask for registered user
if not usernameExists(user) or username == user or users.contains(user):
echo "User not found/User already entered/Own Username! Please enter another User that is already registered"
continue
else:
inc counter
dec choice
users.add(user)
echo "Enter the name of the expense > "
let fileName = getUserInputString()
echo "Enter a little description of the expense > "
let description = getUserInputString()
label b:
echo "Enter the amount you spend as an Integer > "
#var amount = parseInt(stdin.readLine)
var amount = 0.0
try:
amount = parseFloat(stdin.readLine)
except CatchableError:
goto b
#amount = int(amount / int(share + 1))
amount = amount / float(share + 1)
echo amount
#let toWrite = description & '\n' & intToStr(amount)
let toWrite = description & '\n' & amount.formatFloat(ffDecimal, 2)
for x in users:
writeFile(fmt"data/{x}/Expenses/{fileName}_Shared", toWrite)
writeFile(fmt"data/{username}/Expenses/{fileName}_Shared", toWrite)
of 7:
quit(QuitSuccess)
else:
discard "impossible"
proc ctrlc() {.noconv.} =
echo "Ctrl+C fired!"
quit(QuitSuccess)
proc main() =
#[
#Read Users.txt into program and store into hashmap
var strm = newFileStream("data/users/Users.txt", fmRead)
var line = ""
if not isNil(strm):
while strm.readLine(line):
var x = line.split(':')
credentialsMap[x[0]] = (x[1], parseBool(x[2]))
echo credentialsMap
strm.close()
]#
spawn checkLastInputTime()
setControlCHook(ctrlc)
setTime()
echo startBanner
echo "0.Login\n1.Register"
let userChoice = getUserInputInteger(2)
echo userChoice
case userChoice:
of 0:
login()
of 1:
register()
else:
discard "impossible"
userMenu()
#Starting point
when isMainModule:
main()