Friday, February 15, 2019

ceph-ansible: Installing Ceph

My previous post deals with using Vagrant to install CentOS based test systems to install Ceph on. There, I created 7 virtual machines which include
a) a machine to run ansible commands on,
b) three monitors(mons) and
c) three Object storage devices(OSDs) which each contain an additional 5Gb block device available to the OSD daemon.

Since I use Fedora 29 as my host system, I do not need the ansible vm and disabled it by commenting out the line from the array in the Vagrantfile I posted in the previous post.

The steps detailed below can be run either directly on the host machine or if needed, on the ansible vm with suitable modifications.

Install Ansible on your vm or your host machine.
$ sudo dnf install -y ansible
..
$ rpm -q ansible
ansible-2.7.5-1.fc29.noarch

Obtain the latest ceph-ansible using git
$ git clone https://github.com/ceph/ceph-ansible.git

I wanted to install the "Luminous" version of Ceph. According to the ceph-ansible documentation at
http://docs.ceph.com/ceph-ansible/master/#releases
I need the stable-3.2 branch of ceph-ansible. This will only work with Ansible version 2.6.

From the commands above, we have the 2.7.5-1 version of ansible. We need to downgrade our ansible package.

$ sudo dnf downgrade ansible
..
$ rpm -q ansible
ansible-2.6.5-1.fc29.noarch

We now have to go into the ceph-ansible directory and change to the stable-3.2 branch. I then like to create a branch of my own with the configuration files I need.


$ cd ceph-ansible
$ git checkout stable-3.2
..
$ git checkout -b ceph-test
Switched to a new branch 'ceph-test'

To get ceph-ansible to work, I've also had to separately install python3-pyyaml and python3-notario.

$ sudo dnf install python3-pyyaml
$ sudo dnf install python3-notario

We are not ready to configure ceph-ansible to start the installation.

First create the hosts file containing the machines you would like to use.

[mons]
mon1
mon2
mon3

[osds]
osd1
osd2
osd3

Then create group_vars/all.yml with the content


ceph_origin: 'repository'
ceph_repository: community
ceph_stable_release: luminous
public_network: "192.168.145.0/24"
monitor_interface: eth1
journal_size: 1024
devices:
  - /dev/vdb
osd_scenario: lvm

I use the community repository at http://download.ceph.com to download the Luminous release.
More information at http://docs.ceph.com/ceph-ansible/master/installation/methods.html

ceph_origin: 'repository'
ceph_repository: community
ceph_stable_release: luminous


I create the test machines with the private addresses 192.168.145.0/24 subnet. These are created as eth1 on my KVM based test machines.

public_network: "192.168.145.0/24"
monitor_interface: eth1


The block devices for the OSDs are created as /dev/vdb on these KVM based test machines.

devices:
  - /dev/vdb

The following line was needed for this version of ceph-ansible and describes how ceph-volume creates the devices on the OSD. More information is available at http://docs.ceph.com/ceph-ansible/master/osds/scenarios.html


osd_scenario: lvm

You can look over group_vars/all.yml.sample to look at various configuration options available to you.

Copy over site.yml.

$ cp site.yml.sample site.yml

Make sure that test test machines mon1, mon2, mon3, osd1, osd2, osd3 have been started up using "vagrant up". You can now start deploying ansible on the machine with the command

$ ansible-playbook -i hosts -u root site.yml

This takes several minutes at the end of which you have a ceph cluster installed on your test virtual machines.

At this point, you can optionally commit the changes to the git repo so that you can continue to experiment with various settings and then roll back to the working copy if needed.

Next ssh into mon1 as root and run the "ceph health" and "ceph status" commands
[root@mon1 ~]# ceph health
HEALTH_WARN no active mgr
[root@mon1 ~]# ceph status
  cluster:
    id:     9de96055-aba6-4837-ac8e-12156bb7335c
    health: HEALTH_WARN
            no active mgr

  services:
    mon: 3 daemons, quorum mon1,mon2,mon3
    mgr: no daemons active
    osd: 3 osds: 3 up, 3 in

  data:
    pools:   0 pools, 0 pgs
    objects: 0 objects, 0B
    usage:   0B used, 0B / 0B avail
    pgs:    
 
The warning message "no active mgr" is seen because Ceph, since Luminous requires the ceph-mgr daemon running alongside its monitor daemons to provide additional monitoring and to allow external monitoring tools to monitor the system through the interface it provides.

We will cover the installation of the ceph-mgr daemon in the next post.


Using Vagrant to create KVM based vms to test Ceph

Ceph, the software defined storage solution has been growing in popularity especially as a cloud storage platform. To learn more about this product, I purchased the book 'Mastering Ceph: Redefine your storage system' by Nick Fisk.

The first hurdle when using the book was that the examples provided in the book rely on using Vagrant with Virtual box to create test machines which themselves were running Ubuntu. I use a Fedora 29 machine and would like to use CentOS on KVM instead for my setup.

To get the test machines setup for my environment, I've had to deviate from the instructions given in the book. This post is based on my notes. These notes should also benefit those who are just looking to use Vagrant with KVM.

First install Vagrant and the libvirt plugin for vagrant.
sudo dnf install -y vagrant vagrant-libvirt
I use the directory ~/vagrant/ceph as the location for the Vagrantfile for my test machines.

My Vagrant file is as follows


storage_pool_name = "vagrant-pool"

nodes = [
  { :hostname => 'ansible', :ip => '192.168.145.40', :box => 'centos/7' },
  { :hostname => 'mon1', :ip => '192.168.145.41', :box => 'centos/7' },
  { :hostname => 'mon2', :ip => '192.168.145.42', :box => 'centos/7' },
  { :hostname => 'mon3', :ip => '192.168.145.43', :box => 'centos/7' },
  { :hostname => 'osd1', :ip => '192.168.145.51', :box => 'centos/7', :ram =>1024, :osd => 'yes' },
  { :hostname => 'osd2', :ip => '192.168.145.52', :box => 'centos/7', :ram =>1024, :osd => 'yes' },
  { :hostname => 'osd3', :ip => '192.168.145.53', :box => 'centos/7', :ram =>1024, :osd => 'yes' },
]

Vagrant.configure("2") do |config|
  config.ssh.forward_agent = true
  config.ssh.insert_key = false
  config.ssh.private_key_path = ["~/.vagrant.d/insecure_private_key","~/.ssh/id_rsa"]
  config.vm.provision :shell, privileged: false do |s|
    ssh_pub_key = File.readlines("#{Dir.home}/.ssh/id_rsa.pub").first.strip
    s.inline = <<-SHELL
      echo #{ssh_pub_key} >> /home/$USER/.ssh/authorized_keys
      sudo mkdir -m 0700 /root/.ssh/
      sudo bash -c "echo #{ssh_pub_key} >> /root/.ssh/authorized_keys"
    SHELL
  end

  nodes.each do |node|
    config.vm.define node[:hostname] do |nodeconfig|
      nodeconfig.vm.box = node[:box]
      nodeconfig.vm.hostname = node[:hostname]
      nodeconfig.vm.network :private_network, ip: node[:ip]

      memory = node[:ram] ? node[:ram] : 512;
      nodeconfig.vm.provider :libvirt do |lv|
        lv.storage_pool_name = storage_pool_name
        lv.driver = "kvm"
        lv.uri = "qemu:///system"
        lv.memory = memory
        lv.graphics_type = "none"
        if node[:osd] == "yes"
          lv.storage :file, :size => '5G'
        end
      end
    end
  end
end

Going through this step-by-step


    storage_pool_name = "vagrant-pool"

I use a variable storage_pool_name to store the name of the storage pool name in libvirt. This pool is created as a 'Filesystem Directory' on my laptop which has been named "vagrant-pool".


nodes = [
  { :hostname => 'ansible', :ip => '192.168.145.40', :box => 'centos/7' },
  { :hostname => 'mon1', :ip => '192.168.145.41', :box => 'centos/7' },
  { :hostname => 'mon2', :ip => '192.168.145.42', :box => 'centos/7' },
  { :hostname => 'mon3', :ip => '192.168.145.43', :box => 'centos/7' },
  { :hostname => 'osd1', :ip => '192.168.145.51', :box => 'centos/7', :ram =>1024, :osd => 'yes' },
  { :hostname => 'osd2', :ip => '192.168.145.52', :box => 'centos/7', :ram =>1024, :osd => 'yes' },
  { :hostname => 'osd3', :ip => '192.168.145.53', :box => 'centos/7', :ram =>1024, :osd => 'yes' },
]

This is an array or dictionaries containing details of the machines to be setup.


    Vagrant.configure("2") do |config|

    ..

    end

The main configuration block used by Vagrant.

I then initialise common settings for all the test machines. I've commented inline.

      #Use my personal ssh key across the test machines without having to copy my private key to the test machines.
      config.ssh.forward_agent = true

      #Do not regenerate a new key for each test machine.
      config.ssh.insert_key = false

      # The private keys I use. This is used for "vagrant ssh".
      config.ssh.private_key_path = ["~/.vagrant.d/insecure_private_key","~/.ssh/id_rsa"]

      #This block reads plublic keys and appends it to .ssh/authorized_keys for the user and root account.
      config.vm.provision :shell, privileged: false do |s|
        ssh_pub_key = File.readlines("#{Dir.home}/.ssh/id_rsa.pub").first.strip
        s.inline = <<-SHELL
          echo #{ssh_pub_key} >> /home/$USER/.ssh/authorized_keys
          sudo mkdir -m 0700 /root/.ssh/
          sudo bash -c "echo #{ssh_pub_key} >> /root/.ssh/authorized_keys"
        SHELL
      end

We then iterate through the list of nodes in the nodes array setting up a test box for each node with the described features in the block.


  #For each node in the nodes array.
  nodes.each do |node|
    #define a new test box with name :hostname.
    config.vm.define node[:hostname] do |nodeconfig|
      #This is set to centos/7 for all the nodes.
      nodeconfig.vm.box = node[:box]
      #This is the name to be set.
      nodeconfig.vm.hostname = node[:hostname]
      #Set an ip address given in the private network.
      nodeconfig.vm.network :private_network, ip: node[:ip]

      #If a value has been provided for ram, we use that or default to 512M
      memory = node[:ram] ? node[:ram] : 512;
      #We configure testmachine in libvirt
      nodeconfig.vm.provider :libvirt do |lv|
        #This is set to "vagrant-pool" we created earlier
        lv.storage_pool_name = storage_pool_name
        #Use KVM.
        lv.driver = "kvm"
        lv.uri = "qemu:///system"
        lv.memory = memory
        lv.graphics_type = "none"

        #Create a new storage of 5G if it is an OSD.
        if node[:osd] == "yes"
          lv.storage :file, :size => '5G'
        end
      end
    end
  end

To create the test machines, we simply call

$ vagrant up

We can also call up individual machines by providing a list of names.

$ vagrant up mon1 osd1

On first run, vagrant will download an image of CentOS 7. Subsequent runs will be faster.

We can suspend and resume using the commands

$ vagrant suspend
$ vagrant resume

This ensures that the virtual machines are available later when you get back to it.

When we are done and no longer need the machines, we can use the following command to stop and delete them.

$ vagrant destroy

As with "vagrant up", we can provide machine names.

To complete the setup, I add the following to my /etc/hosts file.

#Vagrant hosts
192.168.145.40  ansible
192.168.145.41  mon1
192.168.145.42  mon2
192.168.145.43  mon3
192.168.145.51  osd1
192.168.145.52  osd2
192.168.145.53  osd3

Since I will be recreating these test machines several times, I do not want to keep modifying the ~/.ssh/known_hosts because of the default StrictHostKeyChecking I have on my main setup.
I add the following lines to ~/.ssh/config.

#Vagrant hosts
HOST mon?
        StrictHostKeyChecking no
HOST osd?
        StrictHostKeyChecking no

You can now test by sshing into the test machines
$ ssh root@mon1

Monday, October 08, 2018

Samba: Triggering oplock breaks

I have been investigating the Samba code as part of my task to implement oplock break retry code for a multichannel setup. This is a small extract from my notes which looks into how the oplock break is triggered on the samba server.

Registering the oplock break handler

The smbd server forks a new smbd process to handle a new incoming request by a SMB client.

As part of initialisation of the new smbd process an oplock break handler is initialised.



void smbd_process(struct tevent_context *ev_ctx,
                  struct messaging_context *msg_ctx,
                  int sock_fd,
                  bool interactive)
{
..
        status = smbXsrv_client_create(ev_ctx, ev_ctx, msg_ctx, now, &client);
..
        status = smbd_add_connection(client, sock_fd, &xconn);
..
        /* Setup oplocks */
        if (!init_oplocks(sconn))
                exit_server("Failed to init oplocks");
..
}

The oplock message queue is registered along with the necessary call backs.


bool init_oplocks(struct smbd_server_connection *sconn)

{

        DEBUG(3,("init_oplocks: initializing messages.\n"));



        messaging_register(sconn-&gt;msg_ctx, sconn, MSG_SMB_BREAK_REQUEST,

                           process_oplock_break_message);

        messaging_register(sconn-&gt;msg_ctx, sconn, MSG_SMB_KERNEL_BREAK,

                           process_kernel_oplock_break);

        return true;

}


This is the oplock break handler which handles oplock break requests coming in for files opened by this smbd process.

Triggering an oplock break


For another smbd process attempting to open the file, we end up calling the handler open_file_ntcreate().

In this case, we are not looking at the scenario where kernel oplocks are enabled. Kernel oplocks are useful when you other processes(eg: NFS) using the filesystem exported by samba at the same time. Without kernel oplocks, other processes cannot safely use the filesystem since the locking info is stored by samba in its own databases.


tatic NTSTATUS open_file_ntcreate(connection_struct *conn,

                            struct smb_request *req,

                            uint32_t access_mask,               /* access bits (FILE_READ_DATA etc.) */

                            uint32_t share_access,      /* share constants (FILE_SHARE_READ etc) */

                            uint32_t create_disposition,        /* FILE_OPEN_IF etc. */

                            uint32_t create_options,    /* options such as delete on close. */

                            uint32_t new_dos_attributes,        /* attributes used for new file. */

                            int oplock_request,         /* internal Samba oplock codes. */

                            struct smb2_lease *lease,

                                                        /* Information (FILE_EXISTS etc.) */

                            uint32_t private_flags,     /* Samba specific flags. */

                            int *pinfo,

                            files_struct *fsp)

{

..

        /* ignore any oplock requests if oplocks are disabled */

        if (!lp_oplocks(SNUM(conn)) ||

            IS_VETO_OPLOCK_PATH(conn, smb_fname-&gt;base_name)) {

                /* Mask off everything except the private Samba bits. */

                oplock_request &amp;= SAMBA_PRIVATE_OPLOCK_MASK;

        }

..

 //First open the file

        fsp_open = open_file(fsp, conn, req, parent_dir,

                             flags|flags2, unx_mode, access_mask,

                             open_access_mask, &amp;new_file_created);

..

 //Fetch the share mode from the database or allocate a fresh one if record doesn't exist.

        lck = get_share_mode_lock(talloc_tos(), id,

                                  conn-&gt;connectpath,

                                  smb_fname, &amp;old_write_time);

..

 //Check to see if oplocks are set and if they violate the share mode

        status = open_mode_check(conn, lck,

                                 access_mask, share_access);

..

 //If there is a sharing violation, delay for oplock.

        if (req != NULL) {

                /*

                 * Handle oplocks, deferring the request if delay_for_oplock()

                 * triggered a break message and we have to wait for the break

                 * response.

                 */

                bool delay;

                bool sharing_violation = NT_STATUS_EQUAL(

                        status, NT_STATUS_SHARING_VIOLATION);



  //Here we end up calling send_break_message() to the smbd pid which opened the file 1st.

                delay = delay_for_oplock(fsp, oplock_request, lease, lck,

                                         sharing_violation,

                                         create_disposition,

                                         first_open_attempt);

                if (delay) {

                        schedule_defer_open(lck, fsp-&gt;file_id,

                                            request_time, req);

                        TALLOC_FREE(lck);

                        fd_close(fsp);

                        return NT_STATUS_SHARING_VIOLATION;

                }

        }

..

 //And finally set the new oplock for the file.

        /*

         * Setup the oplock info in both the shared memory and

         * file structs.

         */

        status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);

        if (!NT_STATUS_IS_OK(status)) {

                TALLOC_FREE(lck);

                fd_close(fsp);

                return status;

        }



}


Thus the oplock break is trigerred.

Monday, March 05, 2018

Samba: Handling new connections

Samba uses the tevents library to handle new incoming connections. The Samba server makes use of event handling to perform tasks such as creating a new process for each new client connection and to further handle new requests made by this client. Before the Samba server can handle these events, the events meant to be caught have to be registered along with a handler which handles these events.

More information on the tevent library is available at
https://tevent.samba.org/tevent_tutorial.html

We look at the code patch at the start of the smbd process. We start in main().
 int main(int argc,const char *argv[])
{
..
        struct tevent_context *ev_ctx;
..
        /*
         * Initialize the event context. The event context needs to be
         * initialized before the messaging context, cause the messaging
         * context holds an event context.
         */
        // This eventually returns tevent_context_init(NULL)
        ev_ctx = server_event_context();
        if (ev_ctx == NULL) {
                exit(1);
        }
..
        //Read notes on this function below.
        if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports))
                exit_server("open_sockets_smbd() failed");
..
        //Loop and wait for events.
        //This function is where the tevent contexts such as handling
        //incoming requests or reading new information on the socket.
        smbd_parent_loop(ev_ctx, parent);
..
}

The function which opens sockets and adds the necessary tevents required to handle socket communication
static bool open_sockets_smbd(struct smbd_parent_context *parent,
                              struct tevent_context *ev_ctx,
                              struct messaging_context *msg_ctx,
                              const char *smb_ports)
{
..
                                /*
                                 * If we fail to open any sockets
                                 * in this loop the parent-sockets == NULL
                                 * case below will prevent us from starting.
                                 */

                                (void)smbd_open_one_socket(parent,
                                                  ev_ctx,
                                                  &ss,
                                                  port);
..
}

static bool smbd_open_one_socket(struct smbd_parent_context *parent,
                                 struct tevent_context *ev_ctx,
                                 const struct sockaddr_storage *ifss,
                                 uint16_t port)
{
..
        s->fd = open_socket_in(SOCK_STREAM,
                               port,
                               parent->sockets == NULL ? 0 : 2,
                               ifss,
                               true);
..
        /* ready to listen */
        set_socket_options(s->fd, "SO_KEEPALIVE");
        set_socket_options(s->fd, lp_socket_options());

        /* Set server socket to
         * non-blocking for the accept. */
        set_blocking(s->fd, False);
..
        //This sets the tevent context for the parent sockets.
        //The handling function smbd_accept_connection()
        //is responsible for accepting new client connections.
        s->fde = tevent_add_fd(ev_ctx,
                               s,
                               s->fd, TEVENT_FD_READ,
                               smbd_accept_connection,
                               s);
..
        tevent_fd_set_close_fn(s->fde, smbd_open_socket_close_fn);
..
}

On the parent processes, the process loops waiting for events to be handled.
int main(int argc,const char *argv[])
{
..
        smbd_parent_loop(ev_ctx, parent);
..
}

A new incoming request triggers the tevent context for the fd which has the handling function set to
smbd_accept_connection().
static void smbd_accept_connection(struct tevent_context *ev,
                                   struct tevent_fd *fde,
                                   uint16_t flags,
                                   void *private_data)
{
..
        pid = fork();
        //For child process
        if (pid == 0) {
..
                //Process the incoming request.
                smbd_process(ev, msg_ctx, fd, false);
         exit:
                exit_server_cleanly("end of child");
                return;
        }
        //For the parent process ie. main smbd process.

        /* The parent doesn't need this socket */
        close(fd);
..
        if (pid != 0) {
                add_child_pid(s->parent, pid);
        }
..
}
The parent process at this point forks a child process which is used to handle the new client. The parent process continues looping in main().

Below is the code path followed by the clild process.


void smbd_process(struct tevent_context *ev_ctx,
                  struct messaging_context *msg_ctx,
                  int sock_fd,
                  bool interactive)
{
..
        struct smbXsrv_client *client = NULL;
        ..
        struct smbXsrv_connection *xconn = NULL;
..
        //Create a new struct to store information about this client
        status = smbXsrv_client_create(ev_ctx, ev_ctx, msg_ctx, now, &client);
..
        //The connection information itself is stored in xconn
        status = smbd_add_connection(client, sock_fd, &xconn);
..
        //Loop and wait for new events.
        ret = tevent_loop_wait(ev_ctx);
..
}

With multichannel support, we can have multiple connections connected to the same client. We do not consider multichannel in this document.

NTSTATUS smbd_add_connection(struct smbXsrv_client *client, int sock_fd,
                             struct smbXsrv_connection **_xconn)
{
..
        xconn = talloc_zero(client, struct smbXsrv_connection);
..
        xconn->transport.fde = tevent_add_fd(client->ev_ctx,
                                             xconn,
                                             sock_fd,
                                             TEVENT_FD_READ,
                                             smbd_server_connection_handler,
                                             xconn);
..
        /* for now we only have one connection */
        DLIST_ADD_END(client->connections, xconn);
        xconn->client = client;
..
}
The new connection represented by struct smbXsrv_connection xconn is now connected to the client.
The tevent handler for this socket is now changed to smbd_server_connection_handler().

The child smbd process is now attached to a single client connection. It loops in smbd_process()
void smbd_process(struct tevent_context *ev_ctx,
                  struct messaging_context *msg_ctx,
                  int sock_fd,
                  bool interactive)
{
..
        //Loop and wait for new events.
        ret = tevent_loop_wait(ev_ctx);
..
}

Any new data now sent to this socket will trigger the event handler smbd_server_connection_handler().


static void smbd_server_connection_handler(struct tevent_context *ev,
                                           struct tevent_fd *fde,
                                           uint16_t flags,
                                           void *private_data)
{
..
        if (!NT_STATUS_IS_OK(xconn->transport.status)) {
                /*
                 * we're not supposed to do any io
                 */
                TEVENT_FD_NOT_READABLE(xconn->transport.fde);
                TEVENT_FD_NOT_WRITEABLE(xconn->transport.fde);
                return;
        }
..
        if (flags & TEVENT_FD_WRITE) {
                smbd_server_connection_write_handler(xconn);
                return;
        }
        if (flags & TEVENT_FD_READ) {
                smbd_server_connection_read_handler(xconn, xconn->transport.sock);
                return;
        }
}

static void smbd_server_connection_read_handler(
        struct smbXsrv_connection *xconn, int fd)
{
..
        status = receive_smb_talloc(mem_ctx, xconn, fd,
                                    (char **)(void *)&inbuf,
                                    0, /* timeout */
                                    &unread_bytes,
                                    &encrypted,
                                    &inbuf_len, &seqnum,
                                    !from_client /* trusted channel */);
..
        process_smb(xconn, inbuf, inbuf_len, unread_bytes,
                    seqnum, encrypted, NULL);
}
The call is then processed by the samba server as needed in process_smb.

Wednesday, September 27, 2017

SMB3 encryption in the kernel cifs module

This is a code walk through which takes you through how the cifs module goes through encrypting its communications with the server.

Mount option parsing.

static int
cifs_parse_mount_options(const char *mountdata, const char *devname,
                         struct smb_vol *vol)
{
..
                case Opt_seal:
                        /* we do not do the following in secFlags because seal
                         * is a per tree connection (mount) not a per socket
                         * or per-smb connection option in the protocol
                         * vol->secFlg |= CIFSSEC_MUST_SEAL;
                         */
                        vol->seal = 1;
..
}

static struct cifs_tcon *
cifs_get_tcon(struct cifs_ses *ses, struct smb_vol *volume_info)
{
..
        if (volume_info->seal) {
                if (ses->server->vals->protocol_id == 0) {
                        cifs_dbg(VFS,
                                 "SMB3 or later required for encryption\n");
                        rc = -EOPNOTSUPP;
                        goto out_fail;
#ifdef CONFIG_CIFS_SMB2
                } else if (tcon->ses->server->capabilities &
                                        SMB2_GLOBAL_CAP_ENCRYPTION)
                        tcon->seal = true;
                else {
                        cifs_dbg(VFS, "Encryption is not supported on share\n");
                        rc = -EOPNOTSUPP;
                        goto out_fail;
#endif /* CONFIG_CIFS_SMB2 */
                }
        }
..
}

So at this point, tcon->seal is set.

We check if encryption is required before making a call using the check
static int encryption_required(const struct cifs_tcon *tcon)
{
        if (!tcon)
                return 0;
        if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
            (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
                return 1;
        if (tcon->seal &&
            (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
                return 1;
        return 0;
}

Which is then called before each SMB call to determine if encryption is required.

int
SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
          __u8 *oplock, struct smb2_file_all_info *buf,
          struct smb2_err_rsp **err_buf)
{
..
        if (encryption_required(tcon))
                flags |= CIFS_TRANSFORM_REQ;
..
}

This check for encryption is made for every call and if required, the CIFS_TRANSFORM_REQ flag is set.

struct smb2_transform_hdr {
        __be32 smb2_buf_length; /* big endian on wire */
                                /* length is only two or three bytes - with
                                 one or two byte type preceding it that MBZ */
        __le32 ProtocolId;      /* 0xFD 'S' 'M' 'B' */
        __u8   Signature[16];
//Below this point, we use the information to authenticate but not encrypt. Only the data is encrypted.
//This is the associate data.

        __u8   Nonce[16];
        __le32 OriginalMessageSize;
        __u16  Reserved1;
        __le16 Flags; /* EncryptionAlgorithm */
        __u64  SessionId;
} __packed;


static int
smb_send_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst, int flags)
{
        struct smb_rqst cur_rqst;
        int rc;
        // If the packet doesn't need to be transformed, send it out
        if (!(flags & CIFS_TRANSFORM_REQ))
                return __smb_send_rqst(server, rqst);
        //Check for init_transform_rq and free_transform_rq to transform headers.        if (!server->ops->init_transform_rq ||
            !server->ops->free_transform_rq) {
                cifs_dbg(VFS, "Encryption requested but transform callbacks are missed\n");
                return -EIO;
        }
        //Call the transform functions.
        //Here cur request is a pointer to a cur_rqst on the heap.

        rc = server->ops->init_transform_rq(server, &cur_rqst, rqst);
        if (rc)
                return rc;
        //Send packets.        rc = __smb_send_rqst(server, &cur_rqst);
        //Free packets.        server->ops->free_transform_rq(&cur_rqst);
        return rc;
}

struct smb_version_operations smb30_operations = {
..
        .init_transform_rq = smb3_init_transform_rq,
        .free_transform_rq = smb3_free_transform_rq,
..
};
static int
smb3_init_transform_rq(struct TCP_Server_Info *server, struct smb_rqst *new_rq,
                       struct smb_rqst *old_rq)
{
        struct kvec *iov;
        struct page **pages;
        struct smb2_transform_hdr *tr_hdr;
        unsigned int npages = old_rq->rq_npages;
        int i;
        int rc = -ENOMEM;
        //Allocate an array of page pointers        pages = kmalloc_array(npages, sizeof(struct page *), GFP_KERNEL);
        if (!pages)
                return rc;
        //Copy over the data for pages from the old array.
        new_rq->rq_pages = pages;
        new_rq->rq_npages = old_rq->rq_npages;
        new_rq->rq_pagesz = old_rq->rq_pagesz;
        new_rq->rq_tailsz = old_rq->rq_tailsz;
        //Allocate a new set of pages for the new request to be transformed.
        for (i = 0; i < npages; i++) {
                pages[i] = alloc_page(GFP_KERNEL|__GFP_HIGHMEM);
                if (!pages[i])
                        goto err_free_pages;
        }
        //Create a new array of iov pointers.
        iov = kmalloc_array(old_rq->rq_nvec, sizeof(struct kvec), GFP_KERNEL);
        if (!iov)
                goto err_free_pages;
        /* copy all iovs from the old except the 1st one (rfc1002 length) */
        memcpy(&iov[1], &old_rq->rq_iov[1],
                                sizeof(struct kvec) * (old_rq->rq_nvec - 1));
        new_rq->rq_iov = iov;
        new_rq->rq_nvec = old_rq->rq_nvec;
        //Add a transform header to be used for the first iov.
        tr_hdr = kmalloc(sizeof(struct smb2_transform_hdr), GFP_KERNEL);
        if (!tr_hdr)
                goto err_free_iov;
        /* fill the 1st iov with a transform header */
        fill_transform_hdr(tr_hdr, old_rq);
        new_rq->rq_iov[0].iov_base = tr_hdr;
        new_rq->rq_iov[0].iov_len = sizeof(struct smb2_transform_hdr);
        /* copy pages form the old */
        for (i = 0; i < npages; i++) {
                char *dst = kmap(new_rq->rq_pages[i]);
                char *src = kmap(old_rq->rq_pages[i]);
                unsigned int len = (i < npages - 1) ? new_rq->rq_pagesz :
                                                        new_rq->rq_tailsz;
                memcpy(dst, src, len);
                kunmap(new_rq->rq_pages[i]);
                kunmap(old_rq->rq_pages[i]);
        }
        //Now encrypt the new iov.
        rc = crypt_message(server, new_rq, 1);
        cifs_dbg(FYI, "encrypt message returned %d", rc);
        if (rc)
                goto err_free_tr_hdr;
        return rc;
err_free_tr_hdr:
        kfree(tr_hdr);
err_free_iov:
        kfree(iov);
err_free_pages:
        for (i = i - 1; i >= 0; i--)
                put_page(pages[i]);
        kfree(pages);
        return rc;
}

static int
crypt_message(struct TCP_Server_Info *server, struct smb_rqst *rqst, int enc)
{
        struct smb2_transform_hdr *tr_hdr =
                        (struct smb2_transform_hdr *)rqst->rq_iov[0].iov_base;
        unsigned int assoc_data_len = sizeof(struct smb2_transform_hdr) - 24;
        int rc = 0;
        struct scatterlist *sg;
        u8 sign[SMB2_SIGNATURE_SIZE] = {};
        u8 key[SMB3_SIGN_KEY_SIZE];
        struct aead_request *req;
        char *iv;
        unsigned int iv_len;
        struct cifs_crypt_result result = {0, };
        struct crypto_aead *tfm;
        unsigned int crypt_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
        init_completion(&result.completion);
        //Go through the sessions list and get the encryption/decryption key
        rc = smb2_get_enc_key(server, tr_hdr->SessionId, enc, key);
        if (rc) {
                cifs_dbg(VFS, "%s: Could not get %scryption key\n", __func__,
                         enc ? "en" : "de");
                return 0;
        }
        //Allocate the AED transforms and save it in server->secmech.ccmaesencrypt/decrypt
        //This is done only once for the server
        rc = smb3_crypto_aead_allocate(server);
        if (rc) {
                cifs_dbg(VFS, "%s: crypto alloc failed\n", __func__);
                return rc;
        }
       //use the right tfm
        tfm = enc ? server->secmech.ccmaesencrypt :
                                                server->secmech.ccmaesdecrypt;
        //Set the session key
        rc = crypto_aead_setkey(tfm, key, SMB3_SIGN_KEY_SIZE);
        if (rc) {
                cifs_dbg(VFS, "%s: Failed to set aead key %d\n", __func__, rc);
                return rc;
        }
        rc = crypto_aead_setauthsize(tfm, SMB2_SIGNATURE_SIZE);
        if (rc) {
                cifs_dbg(VFS, "%s: Failed to set authsize %d\n", __func__, rc);
                return rc;
        }
        req = aead_request_alloc(tfm, GFP_KERNEL);
        if (!req) {
                cifs_dbg(VFS, "%s: Failed to alloc aead request", __func__);
                return -ENOMEM;
        }
        if (!enc) {
                memcpy(sign, &tr_hdr->Signature, SMB2_SIGNATURE_SIZE);
                crypt_len += SMB2_SIGNATURE_SIZE;
        }
        sg = init_sg(rqst, sign);
        if (!sg) {
                cifs_dbg(VFS, "%s: Failed to init sg %d", __func__, rc);
                goto free_req;
        }
        iv_len = crypto_aead_ivsize(tfm);
         iv = kzalloc(iv_len, GFP_KERNEL);
        if (!iv) {
                cifs_dbg(VFS, "%s: Failed to alloc IV", __func__);
                goto free_sg;
        }
        iv[0] = 3;
        memcpy(iv + 1, (char *)tr_hdr->Nonce, SMB3_AES128CMM_NONCE);
        aead_request_set_crypt(req, sg, sg, crypt_len, iv);
        aead_request_set_ad(req, assoc_data_len);
        aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
                                  cifs_crypt_complete, &result);
        rc = enc ? crypto_aead_encrypt(req) : crypto_aead_decrypt(req);
        if (rc == -EINPROGRESS || rc == -EBUSY) {
                wait_for_completion(&result.completion);
                rc = result.err;
        }
        if (!rc && enc)
                memcpy(&tr_hdr->Signature, sign, SMB2_SIGNATURE_SIZE);
        kfree(iv);
free_sg:
        kfree(sg);
free_req:
        kfree(req);
        return rc;
}
                                            

Friday, July 15, 2016

RTL-SDR: Logging home energy consumption

I have been using an energy meter for a while to track the energy consumption at home. The system consists of a transmitter and a receiver. The transmitter is placed in a meter box with a clamp on the live feed going into the house and the receiver sits in my office. The transmitter transmits the energy consumption in watts(joules/sec) at certain intervals while the receiver converts these readings from the transmitter to energy consumed in KW-hr and tracks the consumption for a day, week, month and year.

While this system works and allows me to track consumption, I wanted a bit more flexibility in the way energy consumption was displayed. For example, one of the requirements was to break down the energy consumption for various times in the day.

There were multiple solutions available.
1) Use energy consumption monitors which also provide a cloud based service reporting on energy consumption. I rejected this as I am locked into using a particular vendor who may one day decide to shut shop.
2) There are some monitors available which allow you to download data off the the receiver which you can then use. This is a manual process which requires you to connect to the device with a USB cable to pull the data.
3) Find another method to capture the data sent by the transmitter directly and process it. This is the method I finally chose.

The energy consumption monitor I have is an Efergy Elite Classic(Bought second hand on ebay for GBP 21). The transmitter operates in the 433 MHz range and can be set to transmit data in 6/12/18 second intervals.
I also purchased a RTL-SDR USB dongle(GBP 11.99, again bought off ebay) which allows me to tune into various frequencies using software on a computer. You can also use the software(I use gqrx on linux) to scan and determine exactly which frequencies have data being transmitted on them.
An idle raspberry pi was requisitioned for this project and will happily use the RTL-SDR dongle.

Looking around for ideas, I came across the project rtl_433 which uses rtl-sdr libraries and has a large number of decoders already in place. It scans the 433 MHz frequency and automatically decodes data packets for any of the various supported devices. The utility already supports the Efergy energy consumption monitor which is a big plus.

Once the dongle is connected and rtl_433 built, we can simply decode calls over the wire with the command
rtl_433 -f 433550000 -R 36
By default, the rtl_433 utility tunes to 433920000 Hz. The Efergy transmitter transmits on 433550000 Hz I have to pass this frequency with the -f option. This is where I used gqrx to determine the frequency which Efergy transmitter transmits on.

The output is of the form
Power consumption at 110 volts: 92.40 watts
Power consumption at 115 volts: 96.60 watts
Power consumption at 120 volts: 100.80 watts
Power consumption at 220 volts: 184.80 watts
Power consumption at 230 volts: 193.20 watts
Power consumption at 240 volts: 201.60 watts
The mains power in the UK is at 240 volts and it shows my consumption at that voltage to be 201.60 watts. The data in watts is then further processed using a combination of grep, sed and a python script and upload it to Thingspeak. 

Thingspeak is aimed at IoT applications. Thingspeak provides you a REST api to record data. This data can be analysed and used as needed. As a bonus, there are a few Android apps available too which can read the data off the Thingspeak platform.

I first started recording the data in watts updating the Thingspeak channel every time the transmitter transmitted. However the resulting graph was difficult to read because of the huge spikes every time I turned the kettle or the microwave on. To give me a better understanding of my energy consumption, I converted the watts to KW-hr and update the Thingspeak channel every hour instead. This gives me consumption for an hour instead. I preferred looking at the readings in KW-hr as my energy company charges me per KW-hr.

The resulting graph:


Sunday, June 26, 2016

MQTT

MQTT is a lightweight protocol on top of TCP/IP which is used to transfer data between nodes. It was built to be used by devices having low network bandwidth. The low overheads in using this protocol has made it a popular choice for use with IoT devices.

The protocol uses a subscribe/publish method wherein both the data source and the recipient subscribe to a topic on a broker. This model is similar to twitter where a tweet sent by a user can be read by multiple users who subscribe to the user.

A broker is a software run on a more capable hardware which acts as a data distributor. A topic is similar to a subject and is built in a tree structure with its components separated by a '/'. Wildcards are allowed when describing topics to subscribe to.  Mosquitto(http://mosquitto.org/) is the most popular opensource broker at this moment.

Clients connect to the broker and subscribe to the topic. A client wishing to transmit its data(the sender) will publish data for the topic on the broker. Subscribers to the topic on the broker receive the data and process it further. MQTT is data agnostic and the data can take any format the sender wishes.

MQTT apis are available for multiple programming languages at the eclipse paho website.

The PubSub client library is available for use with arduinos.

Some use cases for MQTT are
a) Sensors such as temperature sensors periodically sending information about its surroundings.
b) Sending commands to a device from various sources.

An example project which uses MQTT in an arduino setting is available on the Make website. Here  the automation software - openhab is configured with MQTT bindings to send commands specifying the colour required to the broker(mosquitto) running on a raspberry pi. The ESP8266 connected to a LED strip subscribes to this broker reads the colour data off the broker and sets the light colour accordingly.

More information is on the protocol is available in the mqtt man page at
http://mosquitto.org/man/mqtt-7.html

Setting a frost alarm on Home assistant

One of the issues with winter is the possibility of ice covering your windscreen which needs to be cleared before you can drive. Clearing ou...