Skip to content

Instantly share code, notes, and snippets.

@macshome
Created October 30, 2023 18:55
Show Gist options
  • Save macshome/4b22695c7038aa7891002ac8f14aefd9 to your computer and use it in GitHub Desktop.
Save macshome/4b22695c7038aa7891002ac8f14aefd9 to your computer and use it in GitHub Desktop.
Paste into a macOS Swift Playground to explore SecuritySession and CGSession attributes.
import Cocoa
// Security Session
//
// You can access bits about the security session to get some basic info. You can only get info about your own session.
// Other than the session id, the values are all Bools.
var sessionID = SecuritySessionId()
var sessionAttrs = SessionAttributeBits()
let result = SessionGetInfo(callerSecuritySession,
&sessionID,
&sessionAttrs)
if result != errSessionSuccess {
print("Could not get session info. Error \(result)")
} else {
print("SecuritySessionID: \(sessionID)")
print("Security Session has graphic access: \(sessionAttrs.contains(.sessionHasGraphicAccess))")
print("Security Session is running as root \(sessionAttrs.contains(.sessionIsRoot))")
print("Security Session has a TTY: \(sessionAttrs.contains(.sessionHasTTY))")
print("Security Session is remote: \(sessionAttrs.contains(.sessionIsRemote))\n")
}
// Window Server Session
//
// You can get a CFDictionary of all the current window server info. If there isn't any info it means there isn't a session.
// You can find a fair ammount of info abou the current session in the values of the CGSession dictionary.
// Note that the kCGSSessionAuditIDKey matches the SecuritySessionId.
//
// You can also listen for kCGNotifyGUIConsoleSessionChanged to tell you if the session has changed in some way.
// Listening for kCGNotifyGUISessionUserChanged will let you know when a login or logout has been completed.
if var cgSession = CGSessionCopyCurrentDictionary() as? [String: Any] {
for item in cgSession {
print("\(item.key): \(item.value)")
}
} else {
print("Could not get current CGSession.")
}
@macshome
Copy link
Author

This playground will print the available details about the current CGSession and the SecuritySession the code is running in. You can get some interesting details from here.

Sample output:

SecuritySessionID: 100022
Security Session has graphic access: true
Security Session is running as root false
Security Session has a TTY: true
Security Session is remote: false

kCGSSessionOnConsoleKey: 1
kCGSSessionLoginwindowSafeLogin: 0
kCGSSessionGroupIDKey: 20
kCGSSessionUserNameKey: josh.wisenbaker
kCGSessionLongUserNameKey: Josh Wisenbaker
kCGSessionLoginDoneKey: 1
kCGSSessionUserIDKey: 502
CGSSessionUniqueSessionUUID: 501EBA3D-1F7A-45FE-8195-AF9C1C08596F
kCGSSessionAuditIDKey: 100022
kCGSSessionSystemSafeBoot: 0
kSCSecuritySessionID: 100022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment