When supplying credentials in plain text in Python applications and tools are a concern of the security policy in your company, Kerberos keytab might be a relief. Kerberos keytab hides sensitive information and it serves as a password to authenticate access to different resources. In other words, a keytab is a password replacement.

The most common use case is a service account when an application utilizes a special account. All users who run an application are authenticated with the same service account. It is convenient way to access, for example, data located on SQL Server.

The sample code is developed in CentOS 7 with Python 3 and pyodbc library.

Prerequisites

Sample

import pyodbc
import os

def createKerberosTicket(user_full_name, keytab_path):

    error_code = os.system(f'kinit {user_full_name} -k -t {keytab_path}')
    if (error_code != 0):
        message = 'kinit error: {}'.format(error_code)
        print(message)

    return error_code

def sqlserver_connection():
    return pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};Server=" + 'sqlserver.sample.com' + \
                                ";Database=" + 'master' + \
                                ";Trusted_Connection=yes")

if __name__ == '__main__':

    user_name = 'sampleuser'
    keytab_path = f'/home/sampleuser/{user_name}.keytab'
    domain_name = 'SAMPLE.COM'
    user_full_name = f'{user_name}@{domain_name}'

    createKerberosTicket(user_full_name, keytab_path)

    cur = sqlserver_connection().cursor()

    sql_text = 'SELECT @@VERSION'
    cur.execute(sql_text)
    row = cur.fetchone()

    print(row[0])

Troubleshooting

  • Error message

    pyodbc.OperationalError: ('HYT00', '[HYT00] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
    

    One of the reasons is your SQL Server name. Make sure that it is used Fully Qualified Domain Name (FQDN), for example, sqlserver.sample.com.

  • Check Kerberos ticket(s) created by an application. Open terminal and run commands.

    klist
    
  • Missing Kerberos ticket cache file variable.

    It might be requested to create KRB5CCNAME variable with location and name of Kerberos ticket cache file. See more details in Create Ticket Cache File for Kerberos Authentication in Linux article.

  • Missing krb5.conf Kerberos configuration file.

    The file contains default realm and Kerberos ticket settings. See more details in Create Ticket Cache File for Kerberos Authentication in Linux article.

Resources


Comments

comments powered by Disqus