]> git.saurik.com Git - apple/securityd.git/blob - src/pcscmonitor.cpp
securityd-67.tar.gz
[apple/securityd.git] / src / pcscmonitor.cpp
1 /*
2 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25 //
26 // pcscmonitor - use PCSC to monitor smartcard reader/card state for securityd
27 //
28 // PCSCMonitor is the "glue" between PCSC and the securityd objects representing
29 // smartcard-related things. Its job is to manage the daemon and translate real-world
30 // events (such as card and device insertions) into the securityd object web.
31 //
32 // PCSCMonitor uses multiple inheritance to the hilt. It is (among others)
33 // (*) A notification listener, to listen to pcscd state notifications
34 // (*) A MachServer::Timer, to handle timed actions
35 // (*) A NotificationPort::Receiver, to get IOKit notifications of device insertions
36 // (*) A Child, to watch and manage the pcscd process
37 //
38 #include "pcscmonitor.h"
39 #include <security_utilities/logging.h>
40 #include <IOKit/usb/IOUSBLib.h>
41
42
43 //
44 // Fixed configuration parameters
45 //
46 static const char PCSCD_EXEC_PATH[] = "/usr/sbin/pcscd"; // override with $PCSCDAEMON
47 static const char PCSCD_WORKING_DIR[] = "/var/run/pcscd"; // pcscd's working directory
48 static const Time::Interval PCSCD_IDLE_SHUTDOWN(120); // kill daemon if no devices present
49
50
51 //
52 // Construct a PCSCMonitor.
53 // We strongly assume there's only one of us around here.
54 //
55 // Note that this constructor may well run before the server loop has started.
56 // Don't call anything here that requires an active server loop (like Server::active()).
57 // In fact, you should push all the hard work into a timer, so as not to hold up the
58 // general startup process.
59 //
60 PCSCMonitor::PCSCMonitor(Server &srv, TokenCache &tc, ServiceLevel level)
61 : Listener(kNotificationDomainPCSC, SecurityServer::kNotificationAllEvents),
62 MachServer::Timer(true), // "heavy" timer task
63 server(srv), cache(tc),
64 mServiceLevel(level),
65 mTimerAction(&PCSCMonitor::initialSetup),
66 mGoingToSleep(false)
67 {
68 // do all the smartcard-related work once the event loop has started
69 server.setTimer(this, Time::now()); // ASAP
70 }
71
72
73 //
74 // Poll PCSC for smartcard status.
75 // We are enumerating all readers on each call.
76 //
77 void PCSCMonitor::pollReaders()
78 {
79 // open PCSC session if it's not already open
80 mSession.open();
81
82 // enumerate readers
83 vector<string> names; // will hold reader name C strings throughout
84 mSession.listReaders(names);
85 size_t count = names.size();
86 secdebug("pcsc", "%ld reader(s) in system", count);
87
88 // build the PCSC status inquiry array
89 vector<PCSC::ReaderState> states(count); // reader status array (PCSC style)
90 for (unsigned int n = 0; n < count; n++) {
91 PCSC::ReaderState &state = states[n];
92 ReaderMap::iterator it = mReaders.find(names[n]);
93 if (it == mReaders.end()) { // new reader
94 state.clearPod();
95 state.name(names[n].c_str());
96 // lastKnown(PCSC_STATE_UNKNOWN)
97 // userData<Reader>() = NULL
98 } else {
99 state = it->second->pcscState();
100 state.name(names[n].c_str()); // OUR pointer
101 state.lastKnown(state.state());
102 state.userData<Reader>() = it->second;
103 }
104 }
105
106 // now ask PCSC for status changes
107 mSession.statusChange(states);
108 #if DEBUGDUMP
109 if (Debug::dumping("pcsc"))
110 for (unsigned int n = 0; n < count; n++)
111 states[n].dump();
112 #endif
113
114 // make a set of previously known reader objects (to catch those who disappeared)
115 ReaderSet current;
116 copy_second(mReaders.begin(), mReaders.end(), inserter(current, current.end()));
117
118 // match state array against them
119 for (unsigned int n = 0; n < count; n++) {
120 PCSC::ReaderState &state = states[n];
121 if (Reader *reader = state.userData<Reader>()) {
122 // if PCSC flags a change, notify the Reader
123 if (state.changed())
124 reader->update(state);
125 // accounted for this reader
126 current.erase(reader);
127 } else {
128 RefPointer<Reader> newReader = new Reader(cache, state);
129 mReaders.insert(make_pair(state.name(), newReader));
130 Syslog::notice("Token reader %s inserted into system", state.name());
131 newReader->update(state); // initial state setup
132 }
133 }
134
135 // now deal with vanished readers
136 for (ReaderSet::iterator it = current.begin(); it != current.end(); it++) {
137 secdebug("pcsc", "removing reader %s", (*it)->name().c_str());
138 Syslog::notice("Token reader %s removed from system", (*it)->name().c_str());
139 (*it)->kill(); // prepare to die
140 mReaders.erase((*it)->name()); // remove from reader map
141 }
142 }
143
144
145 void PCSCMonitor::launchPcscd()
146 {
147 // launch pcscd
148 secdebug("pcsc", "launching pcscd to handle smartcard device(s)");
149 assert(Child::state() != alive);
150 Child::reset();
151 Child::fork();
152
153 // if pcscd doesn't report a reader found soon, we'll kill it off
154 scheduleTimer(true);
155 }
156
157
158 //
159 // Code to launch pcscd (run in child as a result of Child::fork())
160 //
161 void PCSCMonitor::childAction()
162 {
163 // move aside any old play area
164 const char *aside = tempnam("/tmp", "pcscd");
165 if (::rename(PCSCD_WORKING_DIR, aside))
166 switch (errno) {
167 case ENOENT: // no /tmp/pcsc (fine)
168 break;
169 default:
170 secdebug("pcsc", "failed too move %s - errno=%d", PCSCD_WORKING_DIR, errno);
171 _exit(101);
172 }
173 else
174 secdebug("pcsc", "old /tmp/pcsc moved to %s", aside);
175
176 // lessen the pain for debugging
177 #if !defined(NDEBUG)
178 freopen("/tmp/pcsc.debuglog", "a", stdout); // shut up pcsc dumps to stdout
179 #endif //NDEBUG
180
181 // execute the daemon
182 const char *pcscdPath = PCSCD_EXEC_PATH;
183 if (const char *env = getenv("PCSCDAEMON"))
184 pcscdPath = env;
185 secdebug("pcsc", "exec(%s,-f)", pcscdPath);
186 execl(pcscdPath, pcscdPath, "-f", NULL);
187 }
188
189
190 //
191 // Event notifier.
192 // These events are sent by pcscd for our (sole) benefit.
193 //
194 void PCSCMonitor::notifyMe(SecurityServer::NotificationDomain domain,
195 SecurityServer::NotificationEvent event, const CssmData &data)
196 {
197 Server::active().longTermActivity();
198 StLock<Mutex> _(*this);
199 assert(mServiceLevel == externalDaemon || Child::state() == alive);
200 pollReaders();
201 scheduleTimer(mReaders.empty() && !mGoingToSleep);
202 }
203
204
205 //
206 // Power event notifications
207 //
208 void PCSCMonitor::systemWillSleep()
209 {
210 StLock<Mutex> _(*this);
211 secdebug("pcsc", "setting sleep marker (%ld readers as of now)", mReaders.size());
212 mGoingToSleep = true;
213 server.clearTimer(this);
214 }
215
216 void PCSCMonitor::systemIsWaking()
217 {
218 StLock<Mutex> _(*this);
219 secdebug("pcsc", "clearing sleep marker (%ld readers as of now)", mReaders.size());
220 mGoingToSleep = false;
221 scheduleTimer(mReaders.empty());
222 }
223
224
225 //
226 // Timer action.
227 //
228 void PCSCMonitor::action()
229 {
230 StLock<Mutex> _(*this);
231 (this->*mTimerAction)();
232 mTimerAction = &PCSCMonitor::noDeviceTimeout;
233 }
234
235
236 //
237 // Update the timeout timer as requested (and indicated by context)
238 //
239 void PCSCMonitor::scheduleTimer(bool enable)
240 {
241 if (Child::state() == alive) // we ran pcscd; let's manage it
242 if (enable) {
243 secdebug("pcsc", "setting idle timer for %g seconds", PCSCD_IDLE_SHUTDOWN.seconds());
244 server.setTimer(this, PCSCD_IDLE_SHUTDOWN);
245 } else if (Timer::scheduled()) {
246 secdebug("pcsc", "clearing idle timer");
247 server.clearTimer(this);
248 }
249 }
250
251
252 //
253 // Perform the initial PCSC subsystem initialization.
254 // This runs (shortly) after securityd is fully functional and the
255 // server loop has started.
256 //
257 void PCSCMonitor::initialSetup()
258 {
259 switch (mServiceLevel) {
260 case forcedOff:
261 secdebug("pcsc", "smartcard operation is FORCED OFF");
262 break;
263
264 case forcedOn:
265 secdebug("pcsc", "pcscd launch is forced on");
266 launchPcscd();
267 break;
268
269 case externalDaemon:
270 secdebug("pcsc", "using external pcscd (if any); no launch operations");
271 break;
272
273 default:
274 secdebug("pcsc", "setting up automatic PCSC management in %s mode",
275 mServiceLevel == conservative ? "conservative" : "aggressive");
276
277 // receive Mach-based IOKit notifications through mIOKitNotifier
278 server.add(mIOKitNotifier);
279
280 // receive power event notifications (through our IOPowerWatcher personality)
281 server.add(this);
282
283 // ask for IOKit notifications for all new USB devices and process present ones
284 IOKit::DeviceMatch usbSelector(kIOUSBInterfaceClassName);
285 IOKit::DeviceMatch pcCardSelector("IOPCCard16Device");
286 mIOKitNotifier.add(usbSelector, *this); // this will scan existing USB devices
287 mIOKitNotifier.add(pcCardSelector, *this); // ditto for PC Card devices
288 if (mServiceLevel == aggressive) {
289 // catch custom non-composite USB devices - they don't have IOServices attached
290 IOKit::DeviceMatch customUsbSelector(::IOServiceMatching("IOUSBDevice"));
291 mIOKitNotifier.add(customUsbSelector, *this); // ditto for custom USB devices
292 }
293 break;
294 }
295
296 // we are NOT scanning for PCSC devices here. Pcscd will send us a notification when it's up
297 }
298
299
300 //
301 // This function is called (as a timer function) when there haven't been any (recognized)
302 // smartcard devicees in the system for a while.
303 //
304 void PCSCMonitor::noDeviceTimeout()
305 {
306 secdebug("pcsc", "killing pcscd (no smartcard devices present for %g seconds)",
307 PCSCD_IDLE_SHUTDOWN.seconds());
308 assert(mReaders.empty());
309 Child::kill(SIGTERM);
310 }
311
312
313 //
314 // IOKit device event notification.
315 // Here we listen for newly inserted devices and check whether to launch pcscd.
316 //
317 void PCSCMonitor::ioChange(IOKit::DeviceIterator &iterator)
318 {
319 assert(mServiceLevel != externalDaemon && mServiceLevel != forcedOff);
320 if (Child::state() == alive) {
321 secdebug("pcsc", "pcscd is alive; ignoring device insertion(s)");
322 return;
323 }
324 secdebug("pcsc", "processing device insertion notices");
325 while (IOKit::Device dev = iterator()) {
326 bool launch = false;
327 switch (deviceSupport(dev)) {
328 case definite:
329 launch = true;
330 break;
331 case possible:
332 launch = (mServiceLevel == aggressive);
333 break;
334 case impossible:
335 break;
336 }
337 if (launch) {
338 launchPcscd();
339 return;
340 }
341 }
342 secdebug("pcsc", "no relevant devices found");
343 }
344
345
346 //
347 // Check an IOKit device that's just come online to see if it's
348 // a smartcard device of some sort.
349 //
350 PCSCMonitor::DeviceSupport PCSCMonitor::deviceSupport(const IOKit::Device &dev)
351 {
352 try {
353 secdebug("scsel", "%s", dev.path().c_str());
354 if (CFRef<CFNumberRef> cfInterface = dev.property<CFNumberRef>("bInterfaceClass"))
355 switch (IFDEBUG(uint32 clas =) cfNumber(cfInterface)) {
356 case kUSBChipSmartCardInterfaceClass: // CCID smartcard reader - go
357 secdebug("scsel", " CCID smartcard reader recognized");
358 return definite;
359 case kUSBVendorSpecificInterfaceClass:
360 secdebug("scsel", " Vendor-specific interface - possible match");
361 return possible;
362 default:
363 secdebug("scsel", " interface class %ld is not a smartcard device", clas);
364 return impossible;
365 }
366 if (CFRef<CFNumberRef> cfDevice = dev.property<CFNumberRef>("bDeviceClass"))
367 if (cfNumber(cfDevice) == kUSBVendorSpecificClass) {
368 secdebug("scsel", " Vendor-specific device - possible match");
369 return possible;
370 }
371 return impossible;
372 } catch (...) {
373 secdebug("scsel", " exception while examining device - ignoring it");
374 return impossible;
375 }
376 }
377
378
379 //
380 // This gets called (by the Unix/Child system) when pcscd has died for any reason
381 //
382 void PCSCMonitor::dying()
383 {
384 Server::active().longTermActivity();
385 StLock<Mutex> _(*this);
386 assert(Child::state() == dead);
387 if (!mReaders.empty()) {
388 // uh-oh. We had readers connected when pcscd suddenly left
389 secdebug("pcsc", "%ld readers were present when pcscd died", mReaders.size());
390 for (ReaderMap::const_iterator it = mReaders.begin(); it != mReaders.end(); it++) {
391 Reader *reader = it->second;
392 secdebug("pcsc", "removing reader %s", reader->name().c_str());
393 reader->kill(); // prepare to die
394 }
395 mReaders.erase(mReaders.begin(), mReaders.end());
396 secdebug("pcsc", "orphaned readers cleared");
397 }
398 //@@@ this is where we would attempt a restart, if we wanted to...
399 }