summaryrefslogtreecommitdiffstats
path: root/tinydns-model.lua
blob: 360e3d3d0d5ebeaaeb82d2ba035e5846e3788b89 (plain)
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
module(..., package.seeall)

-- Load libraries
require("modelfunctions")
require("fs")
require("format")
require("validator")
require("authenticator")
require("roles")
require("posix")

-- Set variables
local configfiles = {}
local configuser
local packagename = "tinydns"
local processname = "tinydns"
local configfile = "/etc/conf.d/" .. processname
local configdir = "/etc/"..processname
local descr = {
	prefix={
		['.']="Name server for your domain (NS + A + SOA)", 
		['&']="Delegate subdomain (NS + A)", 
		['=']="Host (A + PTR)", 
		['+']="Alias (A, no PTR)", 
		['@']="Mail exchanger (MX)",
		["'"]="Text record (TXT)",
		['^']="Reverse record (PTR)", 
		['C']="Canonical name (CNAME)", 
		['Z']="SOA record (SOA)", 
		[':']="Generic record", 
		['%']="Client location", 
	},
	fieldlabels={
		['.']={"Domain", "IP address", "Name server", "Time to live", "Timestamp", "Location", }, 
		['&']={"Domain", "IP address", "Name server", "Time to live", "Timestamp", "Location", }, 
		['=']={"Host", "IP address", "Time to live", "Timestamp", "Location", }, 
		['+']={"Alias", "IP address", "Time to live", "Timestamp", "Location", }, 
		['@']={"Domain", "IP address", "Mail exchanger", "Distance", "Time to live", "Timestamp", "Location", }, 
		['\'']={"Domain", "Text Record", "Time to live", "Timestamp", "Location", }, 
		['^']={"PTR", "Domain name", "Time to live", "Timestamp", "Location", }, 
		['C']={"Domain", "Canonical name", "Time to live", "Timestamp", "Location", }, 
		['Z']={"Domain", "Primary name server", "Contact address", "Serial number", "Refresh time", "Retry time", "Expire time", "Minimum time", "Time to live", "Timestamp", "Location",}, 
		[':']={"Domain", "Record type", "Record data", "Time to live", "Timestamp", "Location", }, 
		['%']={"Location", "IP prefix", }, 
	},
}

-- ################################################################################
-- LOCAL FUNCTIONS

-- Return a table with the config-content of a file
-- Commented/Blank lines are ignored
local function get_value_from_file(file)
	local output = {}
	local filecontent = fs.read_file_as_array(file)
	for i=1,table.maxn(filecontent) do
		local l = filecontent[i]
		if not (string.find ( l, "^[;#].*" )) and not (string.find (l, "^%s*$")) then
			table.insert(output, string.match(l,"(.-)%s*$"))
		end
	end
	if (#output > 0) then
		return true, output
	else
		return false, output
	end

end

-- Function to recursively inserts all filenames in a dir into an array
local function recursedir(path, filearray)
	local k,v
	for k,v in pairs(posix.dir(path) or {}) do
		-- Ignore files that begins with a '.'
		if not string.match(v, "^%.") then
			local f = path .. "/" .. v
			-- If subfolder exists, list files in this subfolder
			if (posix.stat(f).type == "directory") then
				recursedir(f, filearray)
			else
				table.insert(filearray, f)
			end
		end
	end
end

-- Functin to split items into a table
local function split_config_items(orgitem)
	local delimiter = ":"
	local output = {}
	output = format.string_to_table(string.sub(orgitem,2),delimiter)
	output.type = string.sub(orgitem,1,1)
	output.label = descr['prefix'][output.type]
	return output
end

local function getallowedlist(self, userid)
	local allowedlist = {}
	local entry = authenticator.auth.read_entry(self, authenticator.usertable, processname, userid) or ""
	for x in string.gmatch(entry, "([^,]+),?") do allowedlist[#allowedlist + 1] = x end
	
	-- also check to see if there are allowed files for this user's roles
	local rols = authenticator.get_userinfo_roles(self, userid)
	-- add in the guest role
	rols.value[#rols.value + 1] = roles.guest_role
	for i,role in ipairs(rols.value) do
		local entry = authenticator.auth.read_entry(self, authenticator.roletable, processname, role) or ""
		for x in string.gmatch(entry, "([^,]+),?") do allowedlist[#allowedlist + 1] = x end
	end
	return allowedlist
end

-- Feed the configfiles table with list of all configfiles that are available and allowed
-- Default to allowing all files if no userid or allowed list
local function searchforconfigfiles(self, userid)
	if #configfiles > 0 and configuser == userid then
		return configfiles
	end
	local cnffile = {}
	recursedir(configdir, cnffile)
	local allowedlist = getallowedlist(self, userid)
	if allowedlist and #allowedlist > 0 then
		local reverseallowed = {}
		for x,name in ipairs(allowedlist) do reverseallowed[name] = x end
		for k,v in pairs(cnffile) do
			if reverseallowed[v] then
				table.insert(configfiles, v)
			end
		end
	else
		configfiles = cnffile
	end
	configuser = userid
	return configfiles
end

local function validfilename(path)
	for k,v in pairs(configfiles) do
		if (v == path) then
			return true
		end
	end
	return false, "Not a valid filename!"
end

-- ################################################################################
-- PUBLIC FUNCTIONS

function startstop_service(action)
	return modelfunctions.startstop_service(processname, action)
end

-- Present some general status
function getstatus()
	local status = modelfunctions.getstatus(processname, packagename, "TinyDNS Status")

	status.value.configdir = cfe({
		label="Config directory",
		value=configdir,
		})

	local config = getconfig()
	status.value.listen = config.value.listen

	return status
end

function getconfig()
	local config = {}

	local listenaddr = format.parse_ini_file(fs.read_file(configfile),"","IP") or ""
	config.listen = cfe({
		label="IP address to listen on",
		value=listenaddr,
		 })
	local test, errtxt = validator.is_ipv4(config.listen.value)
	if not test then
		config.listen.errtxt = errtxt
	end

	return cfe({ type="group", value=config, label="TinyDNS Configuration" })
end

function setconfig(conf)
	local test, errtxt = validator.is_ipv4(conf.value.listen.value)
	if not test then
		conf.value.listen.errtxt = errtxt
		conf.errtxt = "Failed to set configuration"
	else
		write_file_with_audit(APP, configfile, format.update_ini_file(fs.read_file(configfile) or "","","IP",conf.value.listen.value))
	end

	return conf
end

-- If you enter 'filter_type' (this should be one of the options found in local function check_signs() ) then
-- the output will be filtered to only contain this type of data.
function getconfigobjects(self, file_name, userid, filter_type)
	configfiles = searchforconfigfiles(self, userid)
	local configobjects = {}
	--Loop through all available configfiles
	for i,filename in pairs(configfiles) do
		if not file_name or file_name == filename then
			local filecontent = fs.read_file_as_array(filename)
			for linenumber,configline in ipairs(filecontent) do
				local domaindetails = {}
				local filecontent_table = split_config_items(configline)
				filecontent_table.configline = configline

				-- Use only configs that has a valid prefix
				-- If function is called with some filter options... then show only the filtered values
				if ( not (filter_type) or ((filter_type) and (filter_type == filecontent_table.type)) )
					and (filecontent_table.label) 
				then
					filecontent_table.filename = filename
					filecontent_table.linenumber = linenumber
					
					-- we're gonna add a reverse domain name to make it easier to sort
					local domain = {}
					for mt in string.gmatch(filecontent_table[1], "([^.]+)") do
						table.insert(domain, mt)
					end
					local reversedomain = {}
					for i=#domain,1,-1 do
						table.insert(reversedomain, domain[i])
					end
					filecontent_table.sort = table.concat(reversedomain, ".")

					-- add it to the table
					table.insert(configobjects, filecontent_table)
				end
			end
		end
	end

	-- Sort the table by domain name (entry 1)
	table.sort(configobjects, function(a,b)
			if a == b then
				return false
			elseif a.sort ~= b.sort then
				return a.sort < b.sort
			elseif a.configline ~= b.configline then
				return a.configline < b.configline
			end
			a.errtxt = "Duplicate entry"
			b.errtxt = "Duplicate entry"
			return false
		end)
	for i,entry in ipairs(configobjects) do
		entry.sort = nil
	end

	return cfe({ type="structure", value=configobjects, label="DNS Entries", filename=file_name, fieldlabels=descr.fieldlabels })
end

function getfilelist(self, userid)
	configfiles = searchforconfigfiles(self, userid)
	return cfe({ type="list", value=configfiles, label="List of config files" })
end

function get_filedetails(self, path, userid)
	configfiles = searchforconfigfiles(self, userid)
	return modelfunctions.getfiledetails(path, validfilename)
end

function set_filedetails (self, filedetails, userid)
	configfiles = searchforconfigfiles(self, userid)
	return modelfunctions.setfiledetails(filedetails, validfilename)
end

function getnewconfigfile()
	local options = {}
	options.filename = cfe({ label="File Name" })
	return cfe({ type="group", value=options, label="New config file" })
end

function createconfigfile(self, configfile, userid)
	configfile.errtxt = "Failed to create file"
	local path = configfile.value.filename.value
	if not string.find(path, "/") then
		path = configdir .. "/" .. path
	end
	if validator.is_valid_filename(path,configdir) then
		if (posix.stat(path)) then
			configfile.value.filename.errtxt = "File already exists"
		else
			local file = io.open(path, "w")
			file:close()
			configfile.errtxt = nil

			-- We have to add this file to the allowed list, if there is one
			local allowed = getallowedlist(self, userid)
			if #allowed > 0 then
				local perm = getuserpermissions(self, userid)
				perm.value.allowed.value[#perm.value.allowed.value + 1] = path
				setuserpermissions(self, perm)
			end
		end
	else
		configfile.value.filename.errtxt = "Invalid filename"
	end

	return configfile
end

function remove_file(self, path, userid)
	configfiles = searchforconfigfiles(self, userid)
	local success = "Failed to delete file"
	local errtxt
	if not (fs.is_file(path)) then
		errtxt = "File doesn't exist!"
	elseif (validfilename(path)) then
		local cmd, errors = io.popen( "/bin/rm " .. path, r )
		local cmdoutput = cmd:read("*a")
		cmd:close()
		success = "File Deleted"
	else
		errtxt = "Not a valid filename!"
	end
	return cfe({ value=success, label="Delete config file result", errtxt=errtxt })
end

function getpermissionslist(self)
	local users = authenticator.list_users(self)
	local userlist = {}
	for i,user in ipairs(users) do
		local allowedlist = {}
		local entry = authenticator.auth.read_entry(self, authenticator.usertable, processname, user) or ""
		for x in string.gmatch(entry, "([^,]+),?") do allowedlist[#allowedlist + 1] = x end
		userlist[#userlist + 1] = {id=user, allowed=allowedlist}
	end
	-- Need to check for roles as well as users
	local rolelist = {}
	local rols = roles.list_all_roles(self)
	for i,role in ipairs(rols) do
		local allowedlist = {}
		local entry = authenticator.auth.read_entry(self, authenticator.roletable, processname, role) or ""
		for x in string.gmatch(entry, "([^,]+),?") do allowedlist[#allowedlist + 1] = x end
		rolelist[#rolelist + 1] = {id=role, allowed=allowedlist}
	end
	table.sort(userlist, function(a,b) return a.id < b.id end)
	table.sort(rolelist, function(a,b) return a.id < b.id end)
	return cfe({ type="structure", value={user=userlist, role=rolelist}, label="TinyDNS Permissions" })
end

local function validateuserpermissions(self, userpermissions)
	local success = false
	userpermissions.value.userid.errtxt = "Invalid user"
	local users = authenticator.list_users(self)
	for i,user in ipairs(users) do
		if userpermissions.value.userid.value == user then
			userpermissions.value.userid.errtxt = nil
			success = true
			break
		end
	end
	success = modelfunctions.validatemulti(userpermissions.value.allowed) and success
	return success, userpermissions
end

local function validaterolepermissions(self, rolepermissions)
	local success = false
	rolepermissions.value.role.errtxt = "Invalid role"
	local rols = roles.list_all_roles(self)
	for i,role in ipairs(rols) do
		if rolepermissions.value.role.value == role then
			rolepermissions.value.role.errtxt = nil
			success = true
			break
		end
	end
	success = modelfunctions.validatemulti(rolepermissions.value.allowed) and success
	return success, rolepermissions
end

function getuserpermissions(self, userid)
	local allowedlist = {}
	local entry = authenticator.auth.read_entry(self, authenticator.usertable, processname, userid) or ""
	for x in string.gmatch(entry, "([^,]+),?") do allowedlist[#allowedlist + 1] = x end
	local cnffile = {}
	recursedir(configdir, cnffile)
	local allowed = cfe({ type="multi", value=allowedlist, label="TinyDNS Permissions", option=cnffile, descr="If no permissions are defined, then all are allowed" })
	local user = cfe({ value=userid, label="User Name" })
	local output = cfe({ type="group", value={userid=user, allowed=allowed}, label="TinyDNS Permissions" })
	validateuserpermissions(self, output)
	return output
end

function setuserpermissions(self, userpermissions)
	local success, userpermissions = validateuserpermissions(self, userpermissions)

	if success then
		authenticator.auth.write_entry(self, authenticator.usertable, processname, userpermissions.value.userid.value, table.concat(userpermissions.value.allowed.value, ","))
	else
		userpermissions.errtxt = "Failed to set user permissions"
	end
	return userpermissions
end

function getrolepermissions(self, role)
	local allowedlist = {}
	local entry = authenticator.auth.read_entry(self, authenticator.roletable, processname, role) or ""
	for x in string.gmatch(entry, "([^,]+),?") do allowedlist[#allowedlist + 1] = x end
	local cnffile = {}
	recursedir(configdir, cnffile)
	local allowed = cfe({ type="multi", value=allowedlist, label="TinyDNS Permissions", option=cnffile, descr="If no permissions are defined, then all are allowed" })
	local rol = cfe({ value=role, label="Role" })
	local output = cfe({ type="group", value={role=rol, allowed=allowed}, label="TinyDNS Permissions" })
	validaterolepermissions(self, output)
	return output
end

function setrolepermissions(self, rolepermissions)
	local success, rolepermissions = validaterolepermissions(self, rolepermissions)

	if success then
		authenticator.auth.write_entry(self, authenticator.roletable, processname, rolepermissions.value.role.value, table.concat(rolepermissions.value.allowed.value, ","))
	else
		rolepermissions.errtxt = "Failed to set role permissions"
	end
	return rolepermissions
end