Page 1 of 1

[SOLVED] Package to enable Touch ID with sudo on macOS

Published: November 28, 2024 - 2:09 PM
by bastien30
Good morning,

Here is the package I made to be able to validate sudo requests with Touch ID on macOS.

I based my work on this article: https://www.macg.co/macos/2023/08/macos ... -id-138763

Code: Select all

# -*- coding: utf-8 -*-
from setuphelpers import *
import re

template_file = r'/etc/pam.d/sudo_local.template'
target_file = r'/etc/pam.d/sudo_local'

enabled_pattern = r'^auth\ *sufficient\ *pam\_tid\.so$'
disabled_pattern = r'^#auth\ *sufficient\ *pam\_tid\.so$'

def is_sudo_tid_enabled():
    if not isfile(target_file):
        error(r'File %s does  not exists !' % target_file)
    else:
        with open(target_file) as f:
            for line in f:
                if re.match(enabled_pattern, line):
                    return True
                elif re.match(disabled_pattern, line):
                    return False
    return "NOTMATCHING"

def enable_sudo_tid():
    file_to_rewrite = []
    with open(target_file) as f:
        for line in f:
            if re.match(disabled_pattern, line):
                file_to_rewrite.append(line[1:])
            else:
                file_to_rewrite.append(line)
    with open(target_file, r'w') as f:
        f.writelines(file_to_rewrite)

def disable_sudo_tid():
    file_to_rewrite = []
    with open(target_file) as f:
        for line in f:
            if re.match(enabled_pattern, line):
                file_to_rewrite.append(r'#' + line)
            else:
                file_to_rewrite.append(line)
    with open(target_file, r'w') as f:
        f.writelines(file_to_rewrite)

def install():
    if not isfile(target_file):
        filecopyto(template_file, target_file)

    # Check if already enabled
    check = is_sudo_tid_enabled()
    if check == r'NOTMATCHING':
        error(r'Error matching pattern in %s file' % target_file)
    else:
        if check:
            print(r'TouchID support for sudo is already enabled.')
        else:
            print(r'Enabling TouchID support for sudo...')
            enable_sudo_tid()

def uninstall():
    print(r'Disabling TouchID support for sudo...')
    disable_sudo_tid()