mosquitto权限验证

    本文地址:http://tongxinmao.com/Article/Detail/id/166

    https://www.lixiaodong.com/?p=163
    1.安装需要的包
    sudo apt-get install libc-ares-dev libcurl4-openssl-dev libmysqlclient-dev
    2.下载mosquitto源码并编译安装
    从http://mosquitto.org/download/ 下载源码并解压到某个目录,进入该目录编译安装
    make mosquitto
    sudo make install
    3.下载mosquitto-auth-plug源码
    git clone https://github.com/jpmens/mosquitto-auth-plug.git
    并使用copy命令生成config.mk文件:cp config.mk.in config.mk
    编辑config.mk:根据需要选择合适的后台。我这里只使用mysql数据库验证用户,BACKEND_MYSQL这一行是yes,其余行都是no。在MOSQUITTO_SRC一行输入mosquitto的源码路径,比如MOSQUITTO_SRC =/root/mosquitto-1.4.4/
    。在OPENSSLDIR一行输入openssl的路径,比如OPENSSLDIR = /usr/lib/ssl。
    可以使用以下命令得到openssl的路径:openssl version -a
    4.进入mosquitto-auth-plug所在目录,使用make命令生成so文件。
    5.移动so文件到mosquitto目录(不是源码目录,而是安装后的目录)
    mv auth-plug.so /etc/mosquitto/
    6.编辑mosquitto配置文件
    mosquitto-auth-plug的源码里已经有多种范例配置文件,可以使用这些文件。比如,我用mysql做验证,可以使用 examples目录下的mosquitto-mysql.conf。
    mv mosquitto.conf mosquitto.conf.origin(保留原始配置文件,供以后使用)
    mv mosquitto-auth-plug目录/examples/mosquitto-mysql.conf mosquitto目录/mosquitto.conf
    根据实际情况,编辑文件里的auth_plugin,backend,数据库host,端口,数据库名,用户,密码,sql语句等。
    7.运行mosquitto并观察输出
    mosquitto -c mosquitto-conf -v


    问题:
    1. 输出显示Unable to load auth plugin ".../auth-plug.so"
    解决:
    编辑Mosquitto源码目录下的config.mk:WITH_SRV:=no
    然后重新编译:
    make clean
    make
    生成新的so文件。



    How to make Access Control Lists (ACL) work for Mosquitto MQTT Broker with Auth Plugin?


    https://github.com/jpmens/mosquitto-auth-plug


    If you planning to strengthening your MQTT service, then access control lists (ACL) are mandatory. Mosquitto broker supports this ACL feature through auth plugins.

    One versatile auth-plugin for mosquitto that you should consider using is https://github.com/jpmens/mosquitto-auth-plug. It is very flexible, in that it can support multiple backends as auth provider databases, ranging from CDB, Redis to MySQL and Http. However, getting it compiled and making it start to work is not that straight forward or easy. Hence, this post. It gives some starting point to our students who are venturing into Mosquitto Authentication systems to get started.

    Building the Mosquitto-Auth-Plugin

    The below steps help you for Ubuntu or its variants. Similar steps should get you going with CentOS or other variants if you replace the apt-get commands with their equivalents, such as yum etc.

    • Install required helper and developer packages first

      • sudo apt-get install libc-ares-dev libcurl4-openssl-dev libmysqlclient-dev

    • Get Mosquitto source and build it

    • Get mosquitto-auth-plug source and create a suitable configuration file

    • Edit the created config.mk file to suit your needs

      • vi config.mk

    • Install the appropriate backend developer files (e.g. redis backend)

    • Inside the mosquitto-auth-plug directory use the make command to build the plugin and move it next tomosquitto.conf file

      • make

      • mv auth-plug.so /etc/mosquitto/

    • Edit the Mosquitto configuration file

      • mv /etc/mosquitto/mosquitto.conf.example /etc/mosquitto/mosquitto.conf

      • vi /etc/mosquitto/mosquitto.conf

    Editing the Mosquitto configuration for enabling Auth Plugin

    Inside your mosquitto.conf file you should indicate the auth-plugin options to let the mosquitto MQTT broker know that you are planning on using an auth-plugin and where it is located on the disk.

    Note: Mosquitto MQTT broker usually runs under the identify of an user named mosquitto. So, you should ensure the path to auth-plug.so is accessible to the mosquitto user. You can set permissions using chown and/or chmod commands.

    Edit the /etc/mosquitto/mosquitto.conf file to have its content look something like below (you should search for auth_plugin field in that file):

    auth_plugin /etc/mosquitto/auth-plug.so

    auth_opt_backends mysql

    auth_opt_redis_host 162.252.108.129

    auth_opt_redis_port 12885

    auth_opt_host sql3.freemysqlhosting.net

    auth_opt_port 3306

    auth_opt_dbname sql366410

    auth_opt_user sql366410

    auth_opt_pass nX4*jZ3%

    auth_opt_userquery SELECT pw FROM users WHERE username = ‘%s’

    auth_opt_superquery SELECT COUNT(*) FROM users WHERE username = ‘%s’ AND super = 1

    auth_opt_aclquery SELECT topic FROM acls WHERE (username = ‘%s’) AND (rw >= %d)

    auth_opt_anonusername AnonymouS

    Read the documentation at https://github.com/jpmens/mosquitto-auth-plug to know more about what these fields are how to customize them.

    Testing the ACL workings with Mosquitto Broker

    Once you have edited the mosquitto configuration file to indicate the auth-plugin presence and its backend options, you are ready to deploy it. But before that you need to actually create the user and acl databases in your chosen backend database. In the below few steps are illustrated for mysql as an example database, but the steps should be similar for other databases too.

    1. As a first step, you want to create tables inside your chosen backend database. For mysql you can do this easily using the sample sql script in the examples directory of mosquitto-auth-plug source code

    2. Use the np application found in the mosquitto-auth-plug directory to generate the PBKDF2 strings for passwords

    3. Create new user records with generated PBKDF2 strings in the mysql user table

    4. Edit the acl table to add new topics and restrictions for the created users

    5. Start the mosquitto broker with the modified configuration

      • /usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf

    6. Run a sample sub instance

      • mosquitto_sub -t “topic” -u userName -P password

    7. Run a sample pub instance

      • mosquitto_pub  -t ‘topic’ -m message -u userName -P password

    Points to remember:

    • You never store actual passwords in the backend databases. Only the PBKDF2 strings of the passwords.

    • When you are starting mosquitto_sub and mosquitto_pub you need to use original passwords (and not PBKDF2 strings).

    • PBKDF2 strings are not reversible – that is, for the same password you are not guaranteed to get the same PBKDF2 string every time. They change. Which means, from PBKDF2 string you cannot get back your original password – so you have to remember your passwords (and not rely upon the database to get them back).

    <?php
    /*
     * 1496415797: New connection from 127.0.0.1 on port 18831.
    1496415797: |-- mosquitto_auth_unpwd_check(web)
    1496415797: |-- ** checking backend http
    1496415797: |-- url=http://127.0.0.1:80/mqttauth/auth
    1496415797: |-- data=username=web&password=web&topic=&acc=-1&clientid=
    1496415797: |-- getuser(web) AUTHENTICATED=1 by http
    1496415797: New client connected from 127.0.0.1 as mosqpub/685591-iZ945iox (c1, k60, u'web').
    1496415797: Sending CONNACK to mosqpub/685591-iZ945iox (0, 0)
    1496415797: |-- mosquitto_auth_acl_check(..., mosqpub/685591-iZ945iox, web, gpio, MOSQ_ACL_WRITE)
    1496415797: |-- url=http://127.0.0.1:80/mqttauth/superuser
    1496415797: |-- data=username=web&password=&topic=&acc=-1&clientid=
    1496415797: |-- aclcheck(web, gpio, 2) SUPERUSER=Y by http
    1496415797: |--  Cached  [B31F19D6DEA1F5D102F3535B6BE1F33BAD96B887] for (mosqpub/685591-iZ945iox,web,2)
    1496415797: Received PUBLISH from mosqpub/685591-iZ945iox (d0, q0, r0, m0, 'gpio', ... (20 bytes))
    1496415797: Received DISCONNECT from mosqpub/685591-iZ945iox
    1496415797: Client mosqpub/685591-iZ945iox disconnected.
    
    
    mosquitto_pub -t /publish/we/22 -h 127.0.0.1 -p 1880 -u we -P we -m "{\"pin\":17,\"value\":0}"
    
    
    --
    -- 表的结构 `mqtt_acls`
    --
    --
    -- 表的结构 `mqtt_users`
    --
    
    CREATE TABLE IF NOT EXISTS `mqtt_users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(25) NOT NULL,
      `pw` varchar(128) NOT NULL,
      `super` int(1) NOT NULL DEFAULT '0',
      PRIMARY KEY (`id`),
      UNIQUE KEY `users_username` (`username`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
    
    CREATE TABLE IF NOT EXISTS `mqtt_acls` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(25) NOT NULL,
      `topic` varchar(256) NOT NULL,
      `rw` int(1) NOT NULL DEFAULT '1' COMMENT '1只读 2读写',
      PRIMARY KEY (`id`),
      UNIQUE KEY `acls_user_topic` (`username`,`topic`(228))
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
    
     */
    class mqttauthController extends BaseController {
    
        public function authAction()
        {
    
            $user=g("username");
            $pw=g("password");
    
            $cnt = ORM::for_table('mqtt_users')->where("username",$user)->where("pw",$pw)->where("enable",1)->count();
            if($cnt>0 && $user!="" && $pw!="")
            {
                return;
            }
    
            header('HTTP/1.1 403 Forbidden');
    
    
        }
    
        public function superuserAction()
        {
            $user=g("username");
            $pw=g("password");
    
            $cnt = ORM::for_table('mqtt_users')->where("username",$user)->where("super",1)->count();
            if($cnt>0 && $user!="" && $pw!="")
            {
                return;
            }
    
            header('HTTP/1.1 403 Forbidden');
    
        }
    
        public function aclAction()
        {
            $user=g("username");
            $topic=g("topic");
            $acc=g("acc");//1 == SUB, 2 == PUB
    
            if(strPos($topic,"/publish/".$user)===0)
            {
                die("ACL:".$topic);
            }
    
            header('HTTP/1.1 403 Forbidden');
        }
    
    
    }



    auth_plugin /etc/mosquitto/auth-plug.so

    auth_opt_backends http

    auth_opt_http_ip 127.0.0.1

    auth_opt_http_port 80

    auth_opt_http_hostname tongxinmao.com

    auth_opt_http_getuser_uri /mqtt/auth

    auth_opt_http_superuser_uri /mqtt/superuser

    auth_opt_http_aclcheck_uri /mqtt/acl


    上一篇:mosquitto服务状态监控
    下一篇:vcb 2007 安装破解