Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Общее описание процедуры аутентификации и авторизации пользователя

Информация о профилях пользователей хранится в виде записей в базе данных пользователей. В качестве базы данных используется SQLite3. Путь к файлу базы данных /mnt/jffs/etc/users.sqlite.

Данные профилей зарегистрированных пользователей хранятся в таблице SkyControlUsers базы данных пользователей. Профиль пользователя представляет собой запись в этой таблице. Каждая запись состоит из следующих полей:

  • ID — уникальный идентификатор пользователя, целочисленное значение, начинается с 1;

  • Valid — признак действующей записи, целочисленное значение, равно 1 для действующей записи и 0 для заблокированной (удаленной);

  • Name — уникальное имя зарегистрированного пользователя;

  • Pass — хеш-код секретного набора символов, служащий для авторизации пользователя;

  • RegDate — дата регистрации пользователя;

  • SRead — список доступа на чтение сервера;

  • SWrite — список доступа на запись сервера;

  • CRead — список доступа на чтение клиента;

  • CWrite — список доступа на запись клиента;

  • GRead — список доступа на чтение групп;

  • GWrite — список доступа на запись групп;

  • RFU1 — зарезервированно;

  • RFU2 — зарезервированно.

Первоначально в базе присутствует только одна запись пользователя с именем guest, и паролем, соответствующим хеш-коду набора символов "guest" (используется алгоритм SHA-1).

Аутентификация пользователя производится путём сравнения введённого им пароля Pass с паролем в базе данных пользователей, а также по совпадению имени Name. В качестве пароля используется хеш-код, введенной пользователем строки. Возможен одновременный доступ к системе нескольких клиентов по одной записи пользователя.

При успешной аутентификации пользователя клиенту передается уникальный идентификатор сессии (поле k). Все дальнейшие обращения к серверу производятся с этим идентификатором.

При успешной аутентификации идентификатор сессии, IP адрес клиента и другая служебная информация, сохраняется системой в специальной записи сессии. При перезагрузке системы все записи сессий будут потеряны, соответственно потребуется повторная аутентификация.

Аутентификация и авторизация пользователя

Авторизация пользователя в системе производится при каждом входе в систему с целью определения разрешений доступа пользователя к ресурсам системы.
В процессе авторизации пользователь получает ключ сессии, а также разрешения. Выполнение запросов в системе производится с ключом сессии вплоть до истечения срока действия этого ключа, либо повторной авторизации.
Запрос авторизации содержит следующие поля:

  • querytype — тип запроса: auth — авторизация пользователя в системе;
  • name — имя авторизуемого пользователя;
  • h — хеш пароля авторизуемого пользователя (используется SHA-1, но может применяться любой на выбор веб-разработчика).

При успешной авторизации (совпадении сохраненного и переданного хеша) пример ответа:

...

<user id="1" k="491791596" name="guest" sread="all," swrite="elements," cread="all," cwrite="all," gread="3001, 3002," gwrite="3001," />

Здесь:

  • id — уникальный идентификатор пользователя в системе;
  • k — ключ сессии;
  • name — имя пользователя;
  • sread — список доступа на чтение сервера;
  • swrite — список доступа на запись сервера;
  • сread — список доступа на чтение клиента;
  • сwrite — список доступа на запись клиента;
  • gread — список доступа на чтение групп;
  • gwrite — список доступа на запись групп;

Чтение данных учетной записи пользователя

Запрос чтения учетной записи пользователя содержит следующие поля:

  • querytype — тип запроса: getuser — чтение учетной записи;
  • k — ключ текущей сессии;
  • id — уникальный идентификатор пользователя, запись которого требуется прочитать, в случае отсутствия поля идентификатора в запросе выдается список всех пользователей системы.

Ответ системы имеет следующий вид:

<users> <user id="1" name="guest" sread="all," swrite="elements," cread="all," cwrite="all," gread="3001, 3002," gwrite="3001," />
...</users>

Здесь:

  • id — уникальный идентификатор пользователя в системе;
  • name — имя пользователя;
  • sread — список доступа на чтение сервера;
  • swrite — список доступа на запись сервера;
  • сread — список доступа на чтение клиента;
  • сwrite — список доступа на запись клиента;
  • gread — список доступа на чтение групп;
  • gwrite — список доступа на запись групп;

Создание/изменение учетной записи пользователя

Запрос о создании новой учетной записи (или изменении существующей) содержит следующие поля:

  • querytype — тип запроса: adduser — создание учетной записи пользователя в системе;
  • k — ключ текущей сессии;
  • id — необязательное поле, уникальный идентификатор пользователя, запись которого требуется изменить, при отсутствии создаётся новая учетная запись;
  • name — имя пользователя;
  • h — хеш пароля пользователя (MD5, SHA и т.д. на выбор веб-разработчика);
  • sread — список доступа на чтение сервера;
  • swrite — список доступа на запись сервера;
  • сread — список доступа на чтение клиента;
  • сwrite — список доступа на запись клиента;
  • gread — список доступа на чтение групп;
  • gwrite — список доступа на запись групп;.

Удаление учетной записи пользователя

Запрос на удаление существующей записи пользователя содержит следующие поля:

  • querytype — тип запроса: deluser — удаление учетной записи;
  • k — ключ текущей сессии;
  • id — уникальный идентификатор пользователя, которого требуется удалить из системы, пользователь не может удалить свою собственную учетную запись.

При удалении записи не стираются из таблицы, при этом сбрасывается в 0 поле Valid. Восстановление поля Valid обратно в 1 после удаления записи в API не предусмотрено. Пользователь не может удалить свою собственную учетную запись, под которой он вошел в систему.

Пользователь авторизованный через сервер Radius, не может удалять и редактировать существующие локальные записи пользователей, а также создавать новые записи.

Аутентификация и авторизация через сервер RADIUS

Авторизация пользователя также возможна через сервер RADIUS

Настройки клиента RADIUS находятся в директории /mnt/jffs/etc/radius/. Директория содержит файлы:

  • dictionary — словарь Radius, содержащий стандартные параметры attribute-value;

  • dictionary.local — словарь Radius, содержащий специальные параметры производителя (Sky-Control), в данном случае разрешения доступа пользователя. Специальные параметры производителя (Vendor Specific Attribute) должны быть согласованы с серверной частью Radius;

  • radius.conf — файл конфигурации клиента Radius, содержащий адрес, порт и секретный пароль сервера Radius.

Для настройки аутентификации и авторизации через сервер RADIUS предусмотрены соответствующие команды API.  

При установке новой конфигурации аутентификации и авторизации через сервер Radius происходит автоматическая перезагрузка системы, после чего изменения вступают в силу.

Настройка аутентификации и авторизации через сервер RADIUS

Запрос содержит следующие поля:

  • querytype — тип запроса: setradius — конфигурация Radius;

  • k — ключ текущей сессии;

  • enable — включение или отключение аторизации по Radius, может принимать значение 1 или 0;

  • addr — адрес удаленного сервера Radius;

  • port — порт удаленного сервера Radius (обычно 1812) ;

  • secret — пароль доступа к удаленному серверу Radius.

После успешной обработки запроса система произведет автоматическую перезагрузку, после которой изменения вступят в силу.

При включении в работу авторизации через удаленный сервер, процесс авторизации нового пользователя будет проходить в два этапа:

1) поиск пользователя в локальной базе данных устройства;

2) в случае если в локальной базе пользователь не найден, производится обращение к удаленному серверу Radius для авторизации пользователя.

Просмотр настроек аутентификации и авторизации через сервер RADIUS

Запрос содержит следующие поля:

  • querytype — тип запроса: getradius — конфигурация Radius;

  • k — ключ текущей сессии.

Ответ системы имеет следующий вид:

...

<radius enable="1" addr="192.168.1.88" port="1812"/>

или

...

<radius enable="0"/>

Здесь:

  • enable — признак включения или отключения авторизации по Radius;

  • addr — адрес сервера;

  • port — порт сервера.

Настройки сервера Radius

Для настройки сервера Radius необходимо установить словарь производителя, настроить доступ (адрес и пароль) для клиентов сервера (устройств Sky-Control), а также заполнить список пользователей с соответствующими аттрибутами.

Словарь производителя (например, файл dictionary.local) необходимо поместить в директорию /etc/raddb/,

Code Block
languagetext
titledictionary.local
#
# Vutlan dictionary of parameters.
#
VENDOR        Vutlan        39052
ATTRIBUTE    SRead            10    string        Vutlan
ATTRIBUTE    SWrite           11    string        Vutlan
ATTRIBUTE    CRead            12    string        Vutlan
ATTRIBUTE    CWrite           13    string        Vutlan
ATTRIBUTE    GRead            14    string        Vutlan
ATTRIBUTE    GWrite           15    string        Vutlan
ATTRIBUTE    RFU1             16    string        Vutlan
ATTRIBUTE    RFU2             17    string        Vutlan

а также убедиться что файл словаря включен в основной словарь (файл dictionary):

Code Block
languagetext
titledictionary
...
$INCLUDE-    dictionary.local
...

Список клиентов сервера находится в файле /etc/raddb/clients.conf. Запись клиента имеет вид:

Code Block
languagetext
title/etc/raddb/clients.conf
client 192.168.1.88 { 
   secret = password123 
}

В записи указывается ip-адрес клиента и пароль для связи с сервером.

Записи пользователей находятся в файле ./etc/raddb/mods-config/files/authorize и имеют следующий вид:

Code Block
languagetext
title/etc/raddb/clients.conf
username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450" 
	SRead = "all,", 
	SWrite = "all,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "all,", 
	RFU1 = "something strange", 
	RFU2 = "anover something strange too" 

В записи указаны имя пользователя, пароль (хеш-код вводимого пользователем пароля), разрешения доступа системы и (в данном случае) зарезервированные аттрибуты.

В случае если атрибут не используется, его нужно удалить из записи. Не допускается сохранение пустых атрибутов вида:

RFU2 = ""

т.к. клиент Radius не обрабатывает корректно такую ситуацию.

В приведенном примере записи пользователя, все устройства, авторизующиеся через единый сервер Radius, будут получать одинаковую конфигурацию разрешений пользователя. Если есть необходимость задавать пользователю различные права на разных устройствах, то нужно добавить проверку IP адреса авторизующегося устройства.

Такие записи будут выглядить, например, так:

Code Block
languagetext
title/etc/raddb/clients.conf
username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450", NAS-IP-Address == "192.168.1.88"
	SRead = "all,", 
	SWrite = "all,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "all,"

username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450", NAS-IP-Address != "192.168.1.88"
	SRead = "all,", 
	SWrite = "devvirt,elements,log,logics,modules,notify,relays,sdcard,system,view,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "3001,3002,"

Здесь, при авторизации пользователя username01 через устройство с IP-адресом 192.168.1.88, он получит полный доступ к устройству (все поля all). При авторизации под тем же именем username01 с других устройств (все IP-адреса, кроме 192.168.1.88), пользователь будет ограничен в правах по записи ресурсов и групп устройства.

...

Article contents:

Table of Contents

Permissions in the system

Each user profile in the system can access system resources in read-only or read-write modes.

Each resource in the system is mapped to its corresponding access identifier.

Access control is performed using lists. A list is a text string consisting of access identifiers, separated by commas.

Accordingly, there are two types of lists in the user profile: access lists for reading and write access lists (meaning both writing and reading).

There are three types of permission lists in the system:

1) Server permission lists:

  • sread - list with read access rights
  • swrite - list with write access rights;

List of server resource IDs:

  • accesskeysmanagement of iButton access keys and compatible;
  • cameras — control of video cameras;
  • canbus — can bus control;
  • devvirt — virtual devices management (timers, pings, triggers);
  • elements — element management;
  • groups — group management;
  • gsm — gsm modem control;
  • languges — installed localization files management;
  • log — system log management;
  • logics — logic control;
  • modules — modules management;
  • notify — notification management (mail, trap, sms);
  • relays — relay control (global functions);
  • sdcard — sd card management;
  • system — runtime management (OC Linux);
  • users — users management;
  • view — control of the web interface appearance;
  • all — any existing resources

2) Lists of client permissions (web interface):

  • cread — access list for reading;
  • cwrite — write access list;

The list of client IDs (web interface) is generated and used exclusively by the client (web interface) in accordance with logical organization;

3) Permissions lists for groups of objects:

  • gread — list of group IDs with read-only access;
  • gwrite — list of group IDs with write access;

Lists of permissions for groups consist of group IDs and are intended to restrict the client (web interface) access to group objects.

The format of the list is the IDs (positive integer) available in the group system, separated by commas, with special control words:

  • all — full access, to all groups and elements not in groups;

  • none — access is completely prohibited.

By default, there are no groups in the system, elements and modules are not in a groups, and access to them is possible only with rights "all".

General description of the authentication and authorization procedure for the users

Information about user profiles is stored as records in the user database SQLite3. Path to the database file is /mnt/jffs/etc/users.sqlite.

Registered user profile data is stored in the SkyControlUsers table of the user database. User profile is a record in this table. Each record consists of the following fields:

  • ID — a unique user identifier, an integer value, starts with 1;

  • Valid — the sign of the valid record, an integer value, is 1 for the current record and 0 for the blocked (remote) record;

  • Name — unique name of the registered user;

  • Pass — hash of the secret character set, which serves to authorize the user;

  • RegDate — user registration date;

  • SRead — list of access to read server;

  • SWrite — list of access to the server record;

  • CRead — access list for reading the client;

  • CWrite — list of access to the client's record;

  • GRead — access list for reading groups;

  • GWrite — list of access to record groups;

  • RFU1 — reserved;

  • RFU2 — reserved.

Initially, there is only one user entry in the database with the name guest and the password corresponding to the hash of the "guest" character set (the SHA-1 algorithm is used).

The user is authenticated by comparing the password he entered with the password in the user database, and also by the coincidence of the Name name. The password is a hash code entered by the user. Simultaneous access to the system of several clients is possible by one user record.

Upon successful user authentication, a unique session ID (field k) is sent to the client. All further calls to the server are made with this identifier.

Upon successful authentication, the session identifier, client IP address and other service information is stored by the system in a special session record. When the system is rebooted, all session entries will be lost, so you will need to re-authenticate.

Users authentication and authorization

User authorization in the system is performed every time you log in to determine the permissions for the user to access the system resources.
During the authorization process, the user receives a session key, as well as permissions. Execution of requests in the system is performed with the key of the session until the expiration of this key or reauthorization.
The authorization request contains the following fields:

  • querytype — request type: auth — user authorization in the system;
  • name — authorized user name;
  • h — hash of the password of the authorized user (SHA-1 is used, but any one can be used to choose the web developer).

If the authorization is successful (the saved and transmitted hash match), an example of the answer is:

<user id="1" k="491791596" name="guest" sread="all," swrite="elements," cread="all," cwrite="all," gread="3001, 3002," gwrite="3001," />

Here:

  • id — unique user ID;
  • k — session key;
  • name — user name;
  • sread — list of access to read server;
  • swrite — list of access to the server record;
  • сread — access list for reading the client;
  • сwrite — list of access to the client's record;
  • gread — access list for reading groups;
  • gwrite — список доступа на запись групп;

Reading user account data

The read request for the user account contains the following fields:

  • querytype — request type: getuser — read account;
  • k — the key of the current session;
  • id — a unique user ID whose record is required to be read, in the absence of an identifier field, a list of all users of the system is displayed in the query.

The response of the system is as follows:

<users> <user id="1" name="guest" sread="all," swrite="elements," cread="all," cwrite="all," gread="3001, 3002," gwrite="3001," />
...</users>

Here:

  • id - unique user ID;
  • k - session key;
  • name - user name;
  • sread - list of access to read server;
  • swrite - list of access to the server record;
  • withread-access - list for reading the client;
  • сwrite - list of access to the client's record;
  • gread - access list for reading groups;
  • gwrite - list of access to record groups;

Create / modify user account

The request to create a new account (or modify an existing one) contains the following fields:

  • querytype - request type: adduser - create a user account in the system;
  • k - the key of the current session;
  • id - optional fiel unique user ID, whose record requires to be changed; in the absence of it, a new account is created;
  • name - the user name;
  • h - hash of the user's password (MD5, SHA, etc. to the choice of the web developer);
  • sread - list of read access to the server;
  • swrite - list of access to the server record;
  • сread - list of access to read client;
  • сwrite - list of access to the client's record;
  • gread - access list for reading groups;
  • gwrite - list of access to record groups;

Deleting a user account

The request to delete an existing user record contains the following fields:

  • querytype - request type: deluser - delete account;
  • k - the key of the current session;
  • id is the unique identifier of the user you want to remove from the system, the user can not delete his own account.

When you delete records, they are not erased from the table, while the Valid field is cleared to 0. Restoring the Valid field back to 1 after removing the entry in the API is not

...

provided. The user can not delete his own account, under which he logged on.

The user authorized through the Radius server can not delete and edit existing local user records, or create new entries.

Authentication and authorization via the RADIUS server

User authorization is also possible via the RADIUS server

The RADIUS client settings are located in the /mnt/jffs/etc/radius/ directory. The directory contains the following files:

  • dictionary - Radius dictionary containing standard parameters attribute-value;
  • dictionary.local - Radius dictionary containing special manufacturer parameters (Vutlan), in this case, user access permissions. Special manufacturer parameters (Vendor Specific Attribute) must be coordinated with the server part of Radius;
  • radius.conf - Radius client configuration file that contains the address, port, and secret password of the Radius server.

To configure authentication and authorization through the RADIUS server, appropriate API commands are provided.

When you install a new configuration of authentication and authorization through the Radius server, the system automatically reboots, after which the changes take effect.

Configure authentication and authorization through the RADIUS server

The request contains the following fields:

  • querytype - request type: setradius - Radius configuration;
  • k - the key of the current session;
  • enable - Enable or disable Radius atomization, can be set to 1 or 0;
  • addr - address of the remote Radius server;
  • port - port of the remote server Radius (usually 1812);
  • secret - the password for accessing the remote Radius server.

After successful processing of the request, the system will perform an automatic reboot, after which the changes will take effect.

When you enable authorization through a remote server, the authorization process for a new user will take place in two stages:

1) search for a user in the local database of the device;

2) if the user is not found in the local database, the remote Radius server is contacted to authorize the user.

View authentication and authorization settings via the RADIUS server

The request contains the following fields:

  • querytype - request type: getradius - Radius configuration;
  • k - the key of the current session.


The response of the system is as follows:

<radius enable="1" addr="192.168.1.88" port="1812"/>

or

<radius enable="0"/>


Here:

  • enable - a sign shows if Radius authorization is enabled or disabled;
  • addr - server address;
  • port - the server port.

Radius server settings

To configure the Radius server, you need to install a vendor dictionary, configure access (address and password) for the server clients (Sky-Control devices), and fill out a list of users with the appropriate attributes.

The manufacturer's dictionary (for example, the dictionary.local file) must be placed in the /etc/raddb/ directory,

Code Block
languagetext
titledictionary.local
#
# Vutlan dictionary of parameters.
#
VENDOR        Vutlan        39052
ATTRIBUTE    SRead            10    string        Vutlan
ATTRIBUTE    SWrite           11    string        Vutlan
ATTRIBUTE    CRead            12    string        Vutlan
ATTRIBUTE    CWrite           13    string        Vutlan
ATTRIBUTE    GRead            14    string        Vutlan
ATTRIBUTE    GWrite           15    string        Vutlan
ATTRIBUTE    RFU1             16    string        Vutlan
ATTRIBUTE    RFU2             17    string        Vutlan


and also make sure that the dictionary file is included in the main dictionary (file dictionary):

Code Block
languagetext
titledictionary
...
$INCLUDE-    dictionary.local
...


The server client list is located in /etc/raddb/clients.conf. The client record looks like this:

Code Block
languagetext
title/etc/raddb/clients.conf
client 192.168.1.88 { 
   secret = password123 
}

The record specifies the client's ip-address and password for communication with the server.


User records are in the ./etc/raddb/mods-config/files/authorize file and have the following appearance:

Code Block
languagetext
title/etc/raddb/clients.conf
username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450" 
	SRead = "all,", 
	SWrite = "all,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "all,", 
	RFU1 = "something strange", 
	RFU2 = "anover something strange too" 

The record specifies the user name, password (hash code of user input password), system access permissions and (in this case) reserved attributes.

If the attribute is not used, it must be removed from the record. It is not allowed to store empty attributes of the form:

RFU2 = ""

since the Radius client does not handle this situation correctly.

In the example of the user's entry, all devices that are authorized through a single Radius server will receive the same configuration of the user's permissions. If there is a need to give the user different rights on different devices, then you need to add an IP address check of the authorized device.

Such records will look, for example, like this:


Code Block
languagetext
title/etc/raddb/clients.conf
username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450", NAS-IP-Address == "192.168.1.88"
	SRead = "all,", 
	SWrite = "all,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "all,"

username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450", NAS-IP-Address != "192.168.1.88"
	SRead = "all,", 
	SWrite = "devvirt,elements,log,logics,modules,notify,relays,sdcard,system,view,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "3001,3002,"

Here, when authorizing username01 through a device with IP address 192.168.1.88, user will get full access to the device (all fields are all). When authorizing the same username01 from other devices (all IP addresses except 192.168.1.88), the user will be restricted in the rights to write the resources and device groups.



Permissions in the system

Each user profile in the system can access system resources in read-only or read-write modes.
Each resource in the system is mapped to its corresponding access identifier.
Access control is performed using lists.A list is a text string of access identifiers, separated by commas.
There are two types of lists in the user profile: access lists for reading and writing access lists.
There are three types of permission lists in the system:

1) Server permission lists:

  • sread - list with read access rights
  • swrite - list with write access rights;

List of server resource IDs:

  • accesskeys - management of iButton access keys and compatible;
  • cameras - management of video cameras;
  • CANbus - CAN bus control;
  • devvirt - management of virtual devices (timers, pings, triggers - you need separate permissions for each ???);
  • elements - element management;
  • groups - group management;
  • gsm - control of the GSM modem;
  • languges - management of installed localization files;
  • log - management of the system log;
  • logics - logic schemes management;
  • modules - module management;
  • notify - notification management (mail, trap, SMS - you need separate permissions for each ???);
  • relays - relay control (global functions);
  • sdcard - management of the SD-card;
  • system - runtime environment management (OC Linux);
  • users - user management;
  • view - control the appearance of the web interface;
  • all - any existing resources;
  • accesskeys -
  • cameras - management of video cameras;
    CANbus - CAN bus control;
    devvirt - management of virtual devices (timers, pings, triggers - you need separate permissions for each ???);
    elements - element management;
    groups - group management;
    gsm - control of the GSM modem;
    languges - management of installed localization files;
    log - management of the system log;
    logics - logic schemesmanagement;
    modules - module management;
    notify - notification management (mail, trap, SMS - you need separate permissions for each ???);
    relays - relay control (global functions);
    sdcard - management of the SD-card;
    system - runtime environment management (OC Linux);
    users - user management;
    view - control the appearance of the web interface;
    all - any existing resources;

2) Lists of client permissions (web interface):

  • cread - list of access to read;
  • cwrite - access list for writing;

The list of resource identifiers of the client (web interface) is generated and used exclusively by the client (web interface) in accordance with its logical organization;

3) Permission lists for groups of objects:

  • gread - list of identifiers of groups with read-only access;
  • gwrite - a list of group IDs with read-only access;

Lists of permissions for groups consist of group identifiers and are intended to restrict the client (web interface) access to group objects.

The format of the list is the identifiers (positive integer) available in the group system, separated by commas, with special control words:

  • all - full access, to all groups and elements not in groups;
  • none - access is completely denied.

By default, there are no groups in the system, elements and modules are not in groups, and access to them is possible only with the rights of all.

General description of the authentication and authorization procedure for the user

Information about user profiles is stored as records in the user database. The database uses SQLite3. The path to the database file is /mnt/jffs/etc/users.sqlite.

Registered user profile data is stored in the SkyControlUsers table of the user database. The user profile is an entry in this table. Each entry consists of the following fields:

  • ID - unique user identifier, integer value, starts with 1;
  • Valid - the sign of the valid record, the integer value, is 1 for the current record and 0 for the blocked (remote) record;
  • Name - the unique name of the registered user;
  • Pass - hash code of the secret character set, which serves to authorize the user;
  • RegDate - user registration date;
  • SRead - access list for reading the server;
  • SWrite - list of access to the server record;
  • CRead - access list for reading the client;
  • CWrite - list of access to the client's record;
  • GRead - access list for reading groups;
  • GWrite - list of access to record groups;
  • RFU1 - reserved;
  • RFU2 - reserved.

Initially, there is only one user entry in the database named guest, and the password corresponding to the hash code of the "guest" character set (the SHA-1 algorithm is used).

User authentication is performed by comparing the Pass password entered with the password in the user database, and also by matching the Name name. The password is a hash code entered by the user of the string. Simultaneous access to the system of several clients is possible

...

using one user record.

If the user is successfully authenticated, the client receives a unique session identifier (field k). All further calls to the server are made with this identifier.

Upon successful authentication, the session identifier, client IP address and other service information is stored by the system in a special session record. When the system is rebooted, all session entries will be lost, so you will need to re-authenticate.

Authentication and authorization of the user

User authorization in the system is performed every time you log in to determine the permissions for the user to access the system resources.

During the authorization process, the user receives a session key, as well as permissions. Execution of requests in the system is performed with the key of the session until the expiration of this key or reauthorization.

The authorization request contains the following fields:

  • querytype - request type: auth - authorization of the user in the system;
  • name - the name of the authorized user;
  • h is the password hash of the authorized user (SHA-1 is used, but any one can be used by the choice of the web developer).

If the authorization is successful (the saved and transmitted hash match), an example of the

...

response is:

<user id="1" k="491791596" name="guest" sread="all," swrite="elements," cread="all," cwrite="all," gread="3001, 3002," gwrite="3001," />

Here:

  • id - unique identifier of the user in the system;
  • k

...

  • - session key;
  • name - the user name;
  • sread - list of read access to the server;
  • swrite - list of access to the server record;
  • сread - list of access to read client;
  • сwrite - list of access to the client's record;
  • gread - access list for reading groups;
  • gwrite - list of access to record groups;

Reading user account data

The request to read the user account contains the following fields:

  • querytype - request type: getuser - read account;
  • k - the key of the current session;
  • id

...

  • - unique identifier of the user whose entry is required to be read, in the absence of an identifier field, a list of all users of the system is displayed in the query.

The response of the system is as follows:

<users> <user id="1" name="guest" sread="all," swrite="elements," cread="all," cwrite="all," gread="3001, 3002," gwrite="3001," />
...</users>

Here:

  • id - unique identifier of the user in the system;
  • name - the user name;
  • sread - list of read access to the server;
  • swrite - list of access to the server record;
  • сread - list of access to read client;
  • сwrite - list of access to the client's record;
  • gread - access list for reading groups;
  • gwrite - list of access to record groups;

Create / modify user account

The request to create a new account (or modify an existing one) contains the following fields:

  • querytype - request type: adduser - create a user account in the system;
  • k - the key of the current session;
  • id - optional field, unique user ID, whose record

...

  • needs to be changed, in the absence of which, a new account is created;
  • name - the user name;
  • h - hash of the user's password (MD5, SHA, etc. to the choice of the web developer);
  • sread - list of read access to the server;
  • swrite - list of access to the server record;
  • сread - list of access to read client;
  • сwrite - list of access to the client's record;
  • gread - access list for reading groups;
  • gwrite - list of access to record groups;

Deleting a user account

The request to delete an existing user record contains the following fields:

  • querytype - request type: deluser - delete account;
  • k - the key of the current session;
  • id

...

  • - unique identifier of the user you want to remove from the system, the user can not delete his own account.

When you delete records, they are not erased from the table, while the Valid field is cleared to 0. Restoring the Valid field back to 1 after removing the entry in the API is not provided. The user can not delete his own account, under which he logged on.

The user authorized through the Radius server can not delete and edit existing local user records, or create new entries.

Authentication and authorization via the RADIUS server

User authorization is also possible via the RADIUS server

The RADIUS client settings are located in the /mnt/jffs/etc/radius/ directory. The directory contains the following files:

  • dictionary - Radius dictionary containing standard parameters attribute-value;
  • dictionary.local - Radius dictionary containing special manufacturer parameters (Sky-Control / Vutlan), in this case, user access permissions. Special manufacturer parameters (Vendor Specific Attribute) must be coordinated with the server part of Radius;
  • radius.conf - Radius client configuration file that contains the address, port, and secret password of the Radius server.

To configure authentication and authorization through the RADIUS server, appropriate API commands are provided.

When you install a new configuration of authentication and authorization through the Radius server, the system automatically reboots, after which the changes take effect.

Configure authentication and authorization through the RADIUS server

The request contains the following fields:

  • querytype - request type: setradius - Radius configuration;
  • k - the key of the current session;
  • enable - Enable or disable Radius atomization, can be set to 1 or 0;
  • addr - address of the remote Radius server;
  • port - port of the remote server Radius (usually 1812);
  • secret - the password for accessing the remote Radius server.

After successful processing of the request, the system will perform an automatic reboot, after which the changes will take effect.

When you enable authorization through a remote server, the authorization process for a new user will take place in two stages:

1) search for a user in the local database of the device;

2) if the user is not found in the local database, the remote Radius server is contacted to authorize the user.

View authentication and authorization settings via the RADIUS server

The request contains the following fields:

  • querytype - request type: getradius - Radius configuration;
  • k is the key of the current session.

The response of the system is as follows:

<radius enable="1" addr="192.168.1.88" port="1812"/>

or

<radius enable="0"/>

Here:

  • enable - a sign

...

  • that shows if Radius authorization is enabled or disabled;
  • addr - server address;
  • port is the server port.

Radius server settings

To configure the Radius server, you need to install a vendor dictionary, configure access (address and password) for the server clients (Sky-Control devices), and fill out a list of users with the appropriate attributes.

The manufacturer's dictionary (for example, the dictionary.local file) must be placed in the /etc/raddb/ directory,

Code Block
languagetext
titledictionary.local
#
# Vutlan dictionary of parameters.
#
VENDOR        Vutlan        39052
ATTRIBUTE    SRead            10    string        Vutlan
ATTRIBUTE    SWrite           11    string        Vutlan
ATTRIBUTE    CRead            12    string        Vutlan
ATTRIBUTE    CWrite           13    string        Vutlan
ATTRIBUTE    GRead            14    string        Vutlan
ATTRIBUTE    GWrite           15    string        Vutlan
ATTRIBUTE    RFU1             16    string        Vutlan
ATTRIBUTE    RFU2             17    string        Vutlan


and also make sure that the dictionary file is included in the main dictionary (file dictionary):

Code Block
languagetext
titledictionary
...
$INCLUDE-    dictionary.local
...


The server client list is located in /etc/raddb/clients.conf. The client record looks like this:

Code Block
languagetext
title/etc/raddb/clients.conf
client 192.168.1.88 { 
   secret = password123 
}

The record specifies the client's ip-address and password for communication with the server.


User records are in the ./etc/raddb/mods-config/files/authorize file and have the following appearance:

Code Block
languagetext
title/etc/raddb/clients.conf
username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450" 
	SRead = "all,", 
	SWrite = "all,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "all,", 
	RFU1 = "something strange", 
	RFU2 = "anover something strange too" 

The record specifies the user name, password (hash code of user input password), system access permissions and (in this case) reserved attributes.

If the attribute is not used, it must be removed from the record. It is not allowed to store empty attributes of the form:

RFU2 = ""

since the Radius client does not handle this situation correctly.

In the example of the user's entry, all devices that are authorized through a single Radius server will receive the same configuration of the user's permissions. If there is a need to give the user different rights on different devices, then you need to add an IP address check of the authorized device.

Such records will look, for example, like this:

Code Block
languagetext
title/etc/raddb/clients.conf
username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450", NAS-IP-Address == "192.168.1.88"
	SRead = "all,", 
	SWrite = "all,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "all,"

username01 Cleartext-Password := "35675e68f4b5af7b995d9205ad0fc43842f16450", NAS-IP-Address != "192.168.1.88"
	SRead = "all,", 
	SWrite = "devvirt,elements,log,logics,modules,notify,relays,sdcard,system,view,", 
	CRead = "all,", 
	CWrite = "all,", 
	GRead = "all,", 
	GWrite = "3001,3002,"

Here, when authorizing username01 through a device with IP address 192.168.1.88, it will get full access to the device (all fields are all). When authorizing the same username01 from other devices (all IP addresses except 192.168.1.88), the user will be restricted in the rights to write the resources and device groups.