How to simulate keyboard and mouse events using CGEventPost on Mac OS login window?

I created a pre-logon agent that uses CGEventPost to simulate a keyboard. FYI I am developing a remote control application similar to teamviewer.

Keyboard

CGEventRef keyEvent = CGEventCreateKeyboardEvent( NULL, keyCode, down ) ; CGEventPost( kCGHIDEventTap, keyEvent ) ; CFRelease( keyEvent ) ; 

mouse

 CGEventRef event = CGEventCreateMouseEvent(eventSource, eventType, mouseLocation, mouseButton ); CGEventPost(kCGHIDEventTap, event); CFRelease(event); 

Launch Agent Before Login

 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>my app label</string> <key>LimitLoadToSessionType</key> <string>LoginWindow</string> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>My app directory</string> <key>ProgramArguments</key> <array> <string>app absolute path</string> <string>service</string> <string>myservice</string> </array> <key>KeepAlive</key> <true/> </dict> </plist> 

CGEventPost not working, I get the following in console logs after login

 Untrusted apps are not allowed to connect to Window Server before login. 

I was looking for o chrome remote control (which works with keyboard and mouse simulations). They use CGEventPost for the keyboard, but it works in the login window.

https://cs.chromium.org/chromium/src/remoting/host/input_injector_mac.cc?rcl=0&l=42

It seems that they use the sh file in the privileged helpers directory and use it to load the service, I tried to put our service in the privileged helpers tool, but still the event handling failed.

Deprecated CGPostMouseEvent API, CGPostKeyBoardEvent works without problems, but would really like to know how the non-deprecated keyboard API works in chrome.

+5
source share
1 answer

There is an undocumented (classic apple, security through obscurity) that you must add to binary partitions to make CGEventPost magically work when launched in the context of LoginWindow.

If you are using gcc, add the following to compilation flags

 gcc <YOUR SOURCES AND FLAGS> -sectcreate CGPreLoginApp __CGPreLoginApp /dev/null 

If you are using Xcode, add the following to the other linker flags in the project build settings:

 "-sectcreate" __CGPreLoginApp __cgpreloginapp /dev/null 

Refer to https://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-700/IOHIDFamily.xcodeproj/project.pbxproj for LDFLAGS

+5
source

Source: https://habr.com/ru/post/1262184/


All Articles