Apple App Sandbox Design Guide Manuel Apple sur Fnac.com - Pour voir la liste complète des manuels APPLE, cliquez ici

 

 

TELECHARGER LE PDF sur :

http://developer.apple.com/library/mac/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxDesignGuide.pdf

Commander un produit Apple sur Fnac.com

 

 

Voir également d'autres Guides APPLE :

Apple-Instrumentos_y_efectos_de_Logic_Studio.pdf-Manuel

Apple-ipod_nano_kayttoopas.pdf-Finlande-Manuel

Apple_ProRes_White_Paper_October_2012.pdf-Manuel

Apple-wp_osx_configuration_profiles.pdf-Manuel

Apple-UsingiTunesProducerFreeBooks.pdf-Manuel

Apple-ipad_manual_do_usuario.pdf-Portugais-Manuel

Apple-Instruments_et_effets_Logic_Studio.pdf-Manuel

Apple-ipod_touch_gebruikershandleiding.pdf-Neerlandais-Manuel

AppleiPod_shuffle_4thgen_Manual_del_usuario.pdf-Espagnol-Manuel

Apple-Premiers-contacts-avec-votre-PowerBook-G4-Manuel

Apple_Composite_AV_Cable.pdf-Manuel

Apple-iPod_shuffle_3rdGen_UG_DK.pdf-Danemark-Manuel

Apple-iPod_classic_160GB_Benutzerhandbuch.pdf-Allemand-Manuel

Apple-VoiceOver_GettingStarted-Manuel

Apple-iPod_touch_2.2_Benutzerhandbuch.pdf-Allemand-Manuel

Apple-Apple_TV_Opstillingsvejledning.pdf-Allemand-Manuel

Apple-iPod_shuffle_4thgen_Manuale_utente.pdf-Italie-Manuel

Apple-iphone_prirucka_uzivatela.pdf-Manuel

Apple-Aan-de-slag-Neerlandais-Manuel

Apple-airmac_express-80211n-2nd-gen_setup_guide.pdf-Thailande-Manuel

Apple-ipod_nano_benutzerhandbuch.pdf-Allemand-Manuel

Apple-aperture3.4_101.pdf-Manuel

Apple-Pages09_Anvandarhandbok.pdf-Manuel

Apple-nike_plus_ipod_sensor_ug_la.pdf-Mexique-Manuel

Apple-ResEdit-Reference-For-ResEdit02.1-Manuel

Apple-ipad_guide_de_l_utilisateur.pdf-Manuel

Apple-Compressor-4-Benutzerhandbuch-Allemand-Manuel

Apple-AirPort_Networks_Early2009_DK.pdf-Danemark-Manuel

Apple-MacBook_Pro_Mid2007_2.4_2.2GHz_F.pdf-Manuel

Apple-MacBook_13inch_Mid2010_UG_F.pdf-Manuel

Apple-Xserve-RAID-Presentation-technologique-Janvier-2004-Manuel

Apple-MacBook_Pro_15inch_Mid2010_F.pdf-Manuel

Apple-AirPort_Express-opstillingsvejledning.pdf-Danemark-Manuel

Apple-DEiPod_photo_Benutzerhandbuch_DE0190269.pdf-Allemand-Manuel

Apple-Final-Cut-Pro-X-Logic-Effects-Reference-Manuel

Apple-iPod_touch_2.1_Brugerhandbog.pdf-Danemark-Manuel

Apple-Remote-Desktop-Administratorhandbuch-Version-3.1-Allemand-Manuel

Apple-Qmaster-4-User-Manual-Manuel

Apple-Server_Administration_v10.5.pdf-Manuel

Apple-ipod_classic_features_guide.pdf-Manuel

Apple-Lecteur-Optique-Manuel

Apple-Carte-AirPort-Manuel

Apple-iPhone_Finger_Tips_Guide.pdf-Anglais-Manuel

Apple-Couvercle-Manuel

Apple-battery.cube.pdf-Manuel

Apple-Boitier-de-l-ordinateur-Manuel

Apple-Pile-Interne-Manuel

Apple-atacable.pdf-Manuel

Apple-videocard.pdf-Manuel

Apple-Guide_de_configuration_de_l_Airport_Express_5.1.pdf-Manuel

Apple-iMac_Mid2010_UG_F.pdf-Manuel

Apple-MacBook_13inch_Mid2009_F.pdf-Manuel

Apple-MacBook_Mid2007_UserGuide.F.pdf-Manuel

Apple-Designing_AirPort_Networks_10.5-Windows_F.pdf-Manuel

Apple-Administration_de_QuickTime_Streaming_et_Broadcasting_10.5.pdf-Manuel

Apple-Opstillingsvejledning_til_TimeCapsule.pdf-Danemark-Manuel

Apple-iPod_nano_5th_gen_Benutzerhandbuch.pdf-Manuel

Apple-iOS_Business.pdf-Manuel

Apple-AirPort_Extreme_Installationshandbuch.pdf-Manuel

Apple-Final_Cut_Express_4_Installation_de_votre_logiciel.pdf-Manuel

Apple-MacBook_Pro_15inch_2.53GHz_Mid2009.pdf-Manuel

Apple-Network_Services.pdf-Manuel

Apple-Aperture_Performing_Adjustments_f.pdf-Manuel

Apple-Supplement_au_guide_Premiers_contacts.pdf-Manuel

Apple-Administration_des_images_systeme_et_de_la_mise_a_jour_de_logiciels_10.5.pdf-Manuel

Apple-Mac_OSX_Server_v10.6_Premiers_contacts.pdf-Francais-Manuel

Apple-Designing_AirPort_Networks_10.5-Windows_F.pdf-Manuel

Apple-Mise_a_niveau_et_migration_v10.5.pdf-Manue

Apple-MacBookPro_Late_2007_2.4_2.2GHz_F.pdf-Manuel

Apple-Mac_mini_Late2009_SL_Server_F.pdf-Manuel

Apple-Mac_OS_X_Server_10.5_Premiers_contacts.pdf-Manuel

Apple-iPod_touch_2.0_Guide_de_l_utilisateur_CA.pdf-Manuel

Apple-MacBook_Pro_17inch_Mid2010_F.pdf-Manuel

Apple-Comment_demarrer_Leopard.pdf-Manuel

Apple-iPod_2ndGen_USB_Power_Adapter-FR.pdf-Manuel

Apple-Feuille_de_operations_10.4.pdf-Manuel

Apple-Time_Capsule_Installationshandbuch.pdf-Allemand-Manuel

Apple-F034-2262AXerve-grappe.pdf-Manuel

Apple-Mac_Pro_Early2009_4707_UG_F

Apple-imacg5_17inch_Power_Supply

Apple-Logic_Studio_Installieren_Ihrer_Software_Retail

Apple-IntroductionXserve1.0.1

Apple-Aperture_Getting_Started_d.pdf-Allemand

Apple-getting_started_with_passbook

Apple-iPod_mini_2nd_Gen_UserGuide.pdf-Anglais

Apple-Deploiement-d-iPhone-et-d-iPad-Reseaux-prives-virtuels

Apple-F034-2262AXerve-grappe

Apple-Mac_OS_X_Server_Glossaire_10.5

Apple-FRLogic_Pro_7_Guide_TDM

Apple-iphone_bluetooth_headset_userguide

Apple-Administration_des_services_reseau_10.5

Apple-imacg5_17inch_harddrive

Apple-iPod_nano_4th_gen_Manuale_utente

Apple-iBook-G4-Getting-Started

Apple-XsanGettingStarted

Apple-Mac_mini_UG-Early2006

Apple-Guide_des_fonctionnalites_de_l_iPod_classic

Apple-Guide_de_configuration_d_Xsan_2

Apple-MacBook_Late2006_UsersGuide

Apple-sur-Fnac.com

Apple-Mac_mini_Mid2010_User_Guide_F.pdf-Francais

Apple-PowerBookG3UserManual.PDF.Anglais

Apple-Installation_de_votre_logiciel_Logic_Studio_Retail

Apple-Pages-Guide-de-l-utilisateur

Apple-MacBook_Pro_13inch_Mid2009.pdf.Anglais

Apple-MacBook_Pro_15inch_Mid2009

Apple-Installation_de_votre_logiciel_Logic_Studio_Upgrade

Apple-FRLogic_Pro_7_Guide_TDM

Apple-airportextreme_802.11n_userguide

Apple-iPod_shuffle_3rdGen_UG

Apple-iPod_classic_160GB_User_Guide

Apple-iPod_nano_5th_gen_UserGuide

Apple-ipod_touch_features_guide

Apple-Wireless_Mighty_Mouse_UG

Apple-Advanced-Memory-Management-Programming-Guide

Apple-iOS-App-Programming-Guide

Apple-Concurrency-Programming-Guide

Apple-MainStage-2-User-Manual-Anglais

Apple-iMacG3_2002MultilingualUserGuide

Apple-iBookG3_DualUSBUserGuideMultilingual.PDF.Anglais

Apple-imacG5_20inch_AirPort

Apple-Guide_de_l_utilisateur_de_Mac_Pro_Early_2008

Apple-Installation_de_votre_logiciel_Logic_Express_8

Apple-iMac_Guide_de_l_utilisateur_Mid2007

Apple-imacg5_20inch_OpticalDrive

Apple-FCP6_Formats_de_diffusion_et_formats_HD

Apple-prise_en_charge_des_surfaces_de_controle_logic_pro_8

Apple-Aperture_Quick_Reference_f

Apple-Shake_4_User_Manual

Apple-aluminumAppleKeyboard_wireless2007_UserGuide

Apple-ipod_shuffle_features_guide

Apple-Color-User-Manual

Apple-XsanGettingStarted

Apple-Migration_10.4_2e_Ed

Apple-MacBook_Air_SuperDrive

Apple-MacBook_Late2007-f

ApplePowerMacG5_(Early_2005)_UserGuide

Apple-iSightUserGuide

Apple-MacBook_Pro_Early_2008_Guide_de_l_utilisateur

Apple-Nouvelles-fonctionnalites-aperture-1.5

Apple-premiers_contacts_2e_ed_10.4.pdf-Mac-OS-X-Server

Apple-premiers_contacts_2e_ed_10.4

Apple-eMac_2005UserGuide

Apple-imacg5_20inch_Inverter

Apple-Keynote2_UserGuide.pdf-Japon

Apple-Welcome_to_Tiger.pdf-Japon

Apple-XsanAdminGuide_j.pdf-Japon

Apple-PowerBookG4_UG_15GE.PDF-Japon

Apple-Xsan_Migration.pdf-Japon

Apple-Xserve_Intel_DIY_TopCover_JA.pdf-Japon

Apple-iPod_nano_6thgen_User_Guide_J.pdf-Japon

Apple-Aperture_Photography_Fundamentals.pdf-Japon

Apple-nikeipod_users_guide.pdf-Japon

Apple-QuickTime71_UsersGuide.pdf-Japon

Apple-iMacG5_iSight_UG.pdf-Japon

Apple-Aperture_Performing_Adjustments_j.pdf-Japon

Apple-iMacG5_17inch_HardDrive.pdf-Japon

Apple-iPod_shuffle_Features_Guide_J.pdf-Japon

Apple-MacBook_Air_User_Guide.pdf-Japon

Apple-MacBook_UsersGuide.pdf-Japon

Apple-iPad_iOS4_Brukerhandbok.pdf-Norge-Norvege

Apple-Apple_AirPort_Networks_Early2009_H.pd-Norge-Norvege

Apple-iPod_classic_120GB_no.pdf-Norge-Norvege

Apple-StoreKitGuide.pdf-Japon

Apple-Xserve_Intel_DIY_ExpansionCardRiser_JA.pdf-Japon

Apple-iMacG5_Battery.pdf-Japon

Apple-Logic_Pro_8_Getting_Started.pdf-Japon

Apple-PowerBook-handbok-Norge-Norveg

Apple-iWork09_formler_og_funksjoner.pdf-Norge-Norvege

Apple-MacBook_Pro_15inch_Mid2010_H.pdf-Norge-Norvege

Apple-MacPro_HardDrive_DIY.pdf-Japon

Apple-iPod_Fifth_Gen_Funksjonsoversikt.pdf-Norge-Norvege

Apple-MacBook_13inch_white_Early2009_H.pdf-Norge-Norvege

Apple-GarageBand_09_Komme_i_gang.pdf-Norge-Norvege

Apple-MacBook_Pro_15inch_Mid2009_H.pdf-Norge-Norvege

Apple-imac_mid2011_ug_h.pdf-Norge-Norvege

Apple-iDVD_08_Komme_i_gang.pdf-Norge-Norvege

Apple-MacBook_Air_11inch_Late2010_UG_H.pdf-Norge-Norvege

Apple-iMac_Mid2010_UG_H.pdf-Norge-Norvege

Apple-MacBook_13inch_Mid2009_H.pdf-Norge-Norvege

/Apple-iPhone_3G_Viktig_produktinformasjon_H-Norge-Norvege

Apple-MacBook_13inch_Mid2010_UG_H.pdf-Norge-Norvege

Apple-macbook_air_13inch_mid2011_ug_no.pdf-Norge-Norvege

Apple-Mac_mini_Early2009_UG_H.pdf-Norge-Norvege

Apple-ipad2_brukerhandbok.pdf-Norge-Norvege

Apple-iPhoto_08_Komme_i_gang.pdf-Norge-Norvege

Apple-MacBook_Air_Brukerhandbok_Late2008.pdf-Norge-Norvege

Apple-Pages09_Brukerhandbok.pdf-Norge-Norvege

Apple-MacBook_13inch_Late2009_UG_H.pdf-Norge-Norvege

Apple-iPhone_3GS_Viktig_produktinformasjon.pdf-Norge-Norvege

Apple-MacBook_13inch_Aluminum_Late2008_H.pdf-Norge-Norvege

Apple-Wireless_Keyboard_Aluminum_2007_H-Norge-Norvege

Apple-NiPod_photo_Brukerhandbok_N0190269.pdf-Norge-Norvege

Apple-MacBook_Pro_13inch_Mid2010_H.pdf-Norge-Norvege

Apple-MacBook_Pro_17inch_Mid2010_H.pdf-Norge-Norvege

Apple-Velkommen_til_Snow_Leopard.pdf-Norge-Norvege.htm

Apple-TimeCapsule_Klargjoringsoversikt.pdf-Norge-Norvege

Apple-iPhone_3GS_Hurtigstart.pdf-Norge-Norvege

Apple-Snow_Leopard_Installeringsinstruksjoner.pdf-Norge-Norvege

Apple-iMacG5_iSight_UG.pdf-Norge-Norvege

Apple-iPod_Handbok_S0342141.pdf-Norge-Norvege

Apple-ipad_brukerhandbok.pdf-Norge-Norvege

Apple-GE_Money_Bank_Handlekonto.pdf-Norge-Norvege

Apple-MacBook_Air_11inch_Late2010_UG_H.pdf-Norge-Norvege

Apple-iPod_nano_6thgen_Brukerhandbok.pdf-Norge-Norvege

Apple-iPod_touch_iOS4_Brukerhandbok.pdf-Norge-Norvege

Apple-MacBook_Air_13inch_Late2010_UG_H.pdf-Norge-Norvege

Apple-MacBook_Pro_15inch_Early2011_H.pdf-Norge-Norvege

Apple-Numbers09_Brukerhandbok.pdf-Norge-Norvege

Apple-Welcome_to_Leopard.pdf-Japon

Apple-PowerMacG5_UserGuide.pdf-Norge-Norvege

Apple-iPod_touch_2.1_Brukerhandbok.pdf-Norge-Norvege

Apple-Boot_Camp_Installering-klargjoring.pdf-Norge-Norvege

Apple-MacOSX10.3_Welcome.pdf-Norge-Norvege

Apple-iPod_shuffle_3rdGen_UG_H.pdf-Norge-Norvege

Apple-iPhone_4_Viktig_produktinformasjon.pdf-Norge-Norvege

Apple_TV_Klargjoringsoversikt.pdf-Norge-Norvege

Apple-iMovie_08_Komme_i_gang.pdf-Norge-Norvege

Apple-iPod_classic_160GB_Brukerhandbok.pdf-Norge-Norvege

Apple-Boot_Camp_Installering_10.6.pdf-Norge-Norvege

Apple-Network-Services-Location-Manager-Veiledning-for-nettverksadministratorer-Norge-Norvege

Apple-iOS_Business_Mar12_FR.pdf

Apple-PCIDualAttachedFDDICard.pdf

Apple-Aperture_Installing_Your_Software_f.pdf

Apple-User_Management_Admin_v10.4.pdf

Apple-Compressor-4-ユーザーズマニュアル Japon

Apple-Network_Services_v10.4.pdf

Apple-iPod_2ndGen_USB_Power_Adapter-DE

Apple-Mail_Service_v10.4.pdf

Apple-AirPort_Express_Opstillingsvejledning_5.1.pdf

Apple-MagSafe_Airline_Adapter.pdf

Apple-L-Apple-Multiple-Scan-20-Display

Apple-Administration_du_service_de_messagerie_10.5.pdf

Apple-System_Image_Admin.pdf

Apple-iMac_Intel-based_Late2006.pdf-Japon

Apple-iPhone_3GS_Finger_Tips_J.pdf-Japon

Apple-Power-Mac-G4-Mirrored-Drive-Doors-Japon

Apple-AirMac-カード取り付け手順-Japon

Apple-iPhone開発ガイド-Japon

Apple-atadrive_pmg4mdd.j.pdf-Japon

Apple-iPod_touch_2.2_User_Guide_J.pdf-Japon

Apple-Mac_OS_X_Server_v10.2.pdf

Apple-AppleCare_Protection_Plan_for_Apple_TV.pdf

Apple_Component_AV_Cable.pdf

Apple-DVD_Studio_Pro_4_Installation_de_votre_logiciel

Apple-Windows_Services

Apple-Motion_3_New_Features_F

Apple-g4mdd-fw800-lowerfan

Apple-MacOSX10.3_Welcome

Apple-Print_Service

Apple-Xserve_Setup_Guide_F

Apple-PowerBookG4_17inch1.67GHzUG

Apple-iMac_Intel-based_Late2006

Apple-Installation_de_votre_logiciel

Apple-guide_des_fonctions_de_l_iPod_nano

Apple-Administration_de_serveur_v10.5

Apple-Mac-OS-X-Server-Premiers-contacts-Pour-la-version-10.3-ou-ulterieure

Apple-boot_camp_install-setup

Apple-iBookG3_14inchUserGuideMultilingual

Apple-mac_pro_server_mid2010_ug_f

Apple-Motion_Supplemental_Documentation

Apple-imac_mid2011_ug_f

Apple-iphone_guide_de_l_utilisateur

Apple-macbook_air_11inch_mid2011_ug_fr

Apple-NouvellesfonctionnalitesdeLogicExpress7.2

Apple-QT_Streaming_Server

Apple-Web_Technologies_Admin

Apple-Mac_Pro_Early2009_4707_UG

Apple-guide_de_l_utilisateur_de_Numbers08

Apple-Decouverte_d_Aperture_2

Apple-Guide_de_configuration_et_d'administration

Apple-mac_integration_basics_fr_106.

Apple-iPod_shuffle_4thgen_Guide_de_l_utilisateur

Apple-ARA_Japan

Apple-081811_APP_iPhone_Japanese_v5.4.pdf-Japan

Apple-Recycle_Contract120919.pdf-Japan

Apple-World_Travel_Adapter_Kit_UG

Apple-iPod_nano_6thgen_User_Guide

Apple-RemoteSupportJP

Apple-Mac_mini_Early2009_UG_F.pdf-Manuel-de-l-utilisateur

Apple-Compressor_3_Batch_Monitor_User_Manual_F.pdf-Manuel-de-l-utilisateur

Apple-Premiers__contacts_avec_iDVD_08

Apple-Mac_mini_Intel_User_Guide.pdf

Apple-Prise_en_charge_des_surfaces_de_controle_Logic_Express_8

Apple-mac_integration_basics_fr_107.pdf

Apple-Final-Cut-Pro-7-Niveau-1-Guide-de-preparation-a-l-examen

Apple-Logic9-examen-prep-fr.pdf-Logic-Pro-9-Niveau-1-Guide-de-preparation-a-l-examen

Apple-aperture_photography_fundamentals.pdf-Manuel-de-l-utilisateu

Apple-emac-memory.pdf-Manuel-de-l-utilisateur

Apple-Apple-Installation-et-configuration-de-votre-Power-Mac-G4

Apple-Guide_de_l_administrateur_d_Xsan_2.pdf

Apple-premiers_contacts_avec_imovie6.pdf

Apple-Tiger_Guide_Installation_et_de_configuration.pdf

Apple-Final-Cut-Pro-7-Level-One-Exam-Preparation-Guide-and-Practice-Exam

Apple-Open_Directory.pdf

Apple-Nike_+_iPod_User_guide

Apple-ard_admin_guide_2.2_fr.pdf

Apple-systemoverviewj.pdf-Japon

Apple-Xserve_TO_J070411.pdf-Japon

Apple-Mac_Pro_User_Guide.pdf

Apple-iMacG5_iSight_UG.pdf

Apple-premiers_contacts_avec_iwork_08.pdf

Apple-services_de_collaboration_2e_ed_10.4.pdf

Apple-iPhone_Bluetooth_Headset_Benutzerhandbuch.pdf

Apple-Guide_de_l_utilisateur_de_Keynote08.pdf

APPLE/Apple-Logic-Pro-9-Effectsrfr.pdf

Apple-Logic-Pro-9-Effectsrfr.pdf

Apple-iPod_shuffle_3rdGen_UG_F.pdf

Apple-iPod_classic_160Go_Guide_de_l_utilisateur.pdf

Apple-iBookG4GettingStarted.pdf

Apple-Administration_de_technologies_web_10.5.pdf

Apple-Compressor-4-User-Manual-fr

Apple-MainStage-User-Manual-fr.pdf

Apple-Logic_Pro_8.0_lbn_j.pdf

Apple-PowerBookG4_15inch1.67-1.5GHzUserGuide.pdf

Apple-MacBook_Pro_15inch_Mid2010_CH.pdf

Apple-LED_Cinema_Display_27-inch_UG.pdf

Apple-MacBook_Pro_15inch_Mid2009_RS.pdf

Apple-macbook_pro_13inch_early2011_f.pdf

Apple-iMac_Mid2010_UG_BR.pdf

Apple-iMac_Late2009_UG_J.pdf

Apple-iphone_user_guide-For-iOS-6-Software

Apple-iDVD5_Getting_Started.pdf

Apple-guide_des_fonctionnalites_de_l_ipod_touch.pdf

Apple_iPod_touch_User_Guide

Apple_macbook_pro_13inch_early2011_f

Apple_Guide_de_l_utilisateur_d_Utilitaire_RAID

Apple_Time_Capsule_Early2009_Setup_F

Apple_iphone_4s_finger_tips_guide_rs

Apple_iphone_upute_za_uporabu

Apple_ipad_user_guide_ta

Apple_iPod_touch_User_Guide

apple_earpods_user_guide

apple_iphone_gebruikershandleiding

apple_iphone_5_info

apple_iphone_brukerhandbok

apple_apple_tv_3rd_gen_setup_tw

apple_macbook_pro-retina-mid-2012-important_product_info_ch

apple_Macintosh-User-s-Guide-for-Macintosh-PowerBook-145

Apple_ipod_touch_user_guide_ta

Apple_TV_2nd_gen_Setup_Guide_h

Apple_ipod_touch_manual_del_usuario

Apple_iphone_4s_finger_tips_guide_tu

Apple_macbook_pro_retina_qs_th

Apple-Manuel_de_l'utilisateur_de_Final_Cut_Server

Apple-iMac_G5_de_lutilisateur

Apple-Cinema_Tools_4.0_User_Manual_F

Apple-Personal-LaserWriter300-User-s-Guide

Apple-QuickTake-100-User-s-Guide-for-Macintosh

Apple-User-s-Guide-Macintosh-LC-630-DOS-Compatible

Apple-iPhone_iOS3.1_User_Guide

Apple-iphone_4s_important_product_information_guide

Apple-iPod_shuffle_Features_Guide_F

Liste-documentation-apple

Apple-Premiers_contacts_avec_iMovie_08

Apple-macbook_pro-retina-mid-2012-important_product_info_br

Apple-macbook_pro-13-inch-mid-2012-important_product_info

Apple-macbook_air-11-inch_mid-2012-qs_br

Apple-Manuel_de_l_utilisateur_de_MainStage

Apple-Compressor_3_User_Manual_F

Apple-Color_1.0_User_Manual_F

Apple-guide_de_configuration_airport_express_4.2

Apple-TimeCapsule_SetupGuide

Apple-Instruments_et_effets_Logic_Express_8

Apple-Manuel_de_l_utilisateur_de_WaveBurner

Apple-Macmini_Guide_de_l'utilisateur

Apple-PowerMacG5_UserGuide

Disque dur, ATA parallèle Instructions de remplacement

Apple-final_cut_pro_x_logic_effects_ref_f

Apple-Leopard_Installationshandbok

Manuale Utente PowerBookG4

Apple-thunderbolt_display_getting_started_1e

Apple-Compressor-4-Benutzerhandbuch

Apple-macbook_air_11inch_mid2011_ug

Apple-macbook_air-mid-2012-important_product_info_j

Apple-iPod-nano-Guide-des-fonctionnalites

Apple-iPod-nano-Guide-des-fonctionnalites

Apple-iPod-nano-Guide-de-l-utilisateur-4eme-generation

Apple-iPod-nano-Guide-de-l-utilisateur-4eme-generation

Apple-Manuel_de_l_utilisateur_d_Utilitaire_de_reponse_d_impulsion

Apple-Aperture_2_Raccourcis_clavier

AppleTV_Setup-Guide

Apple-livetype_2_user_manual_f

Apple-imacG5_17inch_harddrive

Apple-macbook_air_guide_de_l_utilisateur

Apple-MacBook_Early_2008_Guide_de_l_utilisateur

Apple-Keynote-2-Guide-de-l-utilisateur

Apple-PowerBook-User-s-Guide-for-PowerBook-computers

Apple-Macintosh-Performa-User-s-Guide-5200CD-and-5300CD

Apple-Macintosh-Performa-User-s-Guide

Apple-Workgroup-Server-Guide

Apple-iPod-nano-Guide-des-fonctionnalites

Apple-iPad-User-Guide-For-iOS-5-1-Software

Apple-Boot-Camp-Guide-d-installation-et-de-configuration

Apple-iPod-nano-Guide-de-l-utilisateur-4eme-generation

Power Mac G5 Guide de l’utilisateur APPLE

Guide de l'utilisateur PAGE '08 APPLE

Guide de l'utilisateur KEYNOTE '09 APPLE

Guide de l'Utilisateur KEYNOTE '3 APPLE

Guide de l'Utilisateur UTILITAIRE RAID

Guide de l'Utilisateur Logic Studio

Power Mac G5 Guide de l’utilisateur APPLE

Guide de l'utilisateur PAGE '08 APPLE

Guide de l'utilisateur KEYNOTE '09 APPLE

Guide de l'Utilisateur KEYNOTE '3 APPLE

Guide de l'Utilisateur UTILITAIRE RAID

Guide de l'Utilisateur Logic Studio

Guide de l’utilisateur ipad Pour le logiciel iOS 5.1

PowerBook G4 Premiers Contacts APPLE

Guide de l'Utilisateur iphone pour le logiciel ios 5.1 APPLE

Guide de l’utilisateur ipad Pour le logiciel iOS 4,3

Guide de l’utilisateur iPod nano 5ème génération

Guide de l'utilisateur iPod Touch 2.2 APPLE

Guide de l’utilisateur QuickTime 7  Mac OS X 10.3.9 et ultérieur Windows XP et Windows 2000

Guide de l'utilisateur MacBook 13 pouces Mi 2010

Guide de l’utilisateur iPhone (Pour les logiciels iOS 4.2 et 4.3)

Guide-de-l-utilisateur-iPod-touch-pour-le-logiciel-ios-4-3-APPLE

Guide-de-l-utilisateur-iPad-2-pour-le-logiciel-ios-4-3-APPLE

Guide de déploiement en entreprise iPhone OS

Guide-de-l-administrateur-Apple-Remote-Desktop-3-1

Guide-de-l-utilisateur-Apple-Xserve-Diagnostics-Version-3X103

Guide-de-configuration-AirPort-Extreme-802.11n-5e-Generation

Guide-de-configuration-AirPort-Extreme-802-11n-5e-Generation

Guide-de-l-utilisateur-Capteur-Nike-iPod

Guide-de-l-utilisateur-iMac-21-5-pouces-et-27-pouces-mi-2011-APPLE

Guide-de-l-utilisateur-Apple-Qadministrator-4

Guide-d-installation-Apple-TV-3-eme-generation

User-Guide-iPad-For-ios-5-1-Software

App Sandbox Design GuideContents About App Sandbox 5 At a Glance 5 How to Use This Document 6 Prerequisites 6 See Also 6 App Sandbox Quick Start 8 Create the Xcode Project 8 Enable App Sandbox 10 Create a Code Signing Certificate for Testing 10 Specify the Code Signing Identity 11 Confirm That the App Is Sandboxed 12 Resolve an App Sandbox Violation 13 App Sandbox in Depth 15 The Need for a Last Line of Defense 15 Container Directories and File System Access 16 The App Sandbox Container Directory 16 The Application Group Container Directory 17 Powerbox and File System Access Outside of Your Container 17 Open and Save Dialog Behavior with App Sandbox 19 Entitlements and System Resource Access 20 Security-Scoped Bookmarks and Persistent Resource Access 21 Two Distinct Types of Security-Scoped Bookmark 21 Using Security-Scoped Bookmarks 22 App Sandbox and Code Signing 24 External Tools, XPC Services, and Privilege Separation 26 Designing for App Sandbox 27 Six Steps for Adopting App Sandbox 27 Determine Whether Your App Is Suitable for Sandboxing 27 Design a Development and Distribution Strategy 29 Resolve API Incompatibilities 29 Opening, Saving, and Tracking Documents 29 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 2Retaining Access to File System Resources 29 Creating a Login Item for Your App 30 Accessing User Data 30 Accessing Preferences of Other Apps 30 Apply the App Sandbox Entitlements You Need 31 Add Privilege Separation Using XPC 32 Implement a Migration Strategy 32 Migrating an App to a Sandbox 33 Creating a Container Migration Manifest 34 Undoing a Migration for Testing 36 An Example Container Migration Manifest 36 Use Variables to Specify Support-File Directories 37 Document Revision History 39 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 3 ContentsTables and Listings App Sandbox in Depth 15 Table 2-1 The App Sandbox mindset 15 Table 2-2 Open and Save class inheritance with App Sandbox 20 Migrating an App to a Sandbox 33 Table 4-1 How system directory variables resolve depending on context 37 Table 4-2 Variables for support-file directories 38 Listing 4-1 An example container migration manifest 36 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 4App Sandbox provides a last line of defense against stolen, corrupted, or deleted user data if malicious code exploits your app. App Sandbox also minimizes the damage from coding errors in your app or in frameworks you link against. Your app All system resources All user data Unrestricted access Other system resources Other user data Your app Unrestricted access No access Without App Sandbox With App Sandbox Your sandbox App Sandbox is an access control technology provided in OS X, enforced at the kernel level. Its strategy is twofold: 1. App Sandbox enables you to describe how your app interacts with the system. The system then grants your app the access it needs to get its job done, and no more. 2. App Sandbox allows the user to transparently grant your app additional access by way of Open and Save dialogs, drag and drop, and other familiar user interactions. At a Glance Based on simple security principles, App Sandbox provides strong defense against damage from malicious code. The elements of App Sandbox are container directories, entitlements, user-determined permissions, privilege separation, and kernel enforcement. It’s up to you to understand these elements and then to use your understanding to create a plan for adopting App Sandbox. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 5 About App SandboxRelevant chapters: “App Sandbox Quick Start” (page 8), “App Sandbox in Depth” (page 15) After you understand the basics, look at your app in light of this security technology. First, determine if your app issuitable forsandboxing. Most apps are. Design your developmentstrategy, resolve API incompatibilities, determine which entitlements you need, and consider applying privilege separation to maximize the defensive value of App Sandbox. Relevant chapter: “Designing for App Sandbox” (page 27) Some file system locations that your app uses are different when you adopt App Sandbox. In particular, you gain a container directory to be used for app support files, databases, caches, and other files apart from user documents. OS X and Xcode support migration of files from their legacy locations to your container. Relevant chapter: “Migrating an App to a Sandbox” (page 33) How to Use This Document To get up and running with App Sandbox, perform the tutorial in “App Sandbox Quick Start” (page 8). Before sandboxing an app you intend to distribute, be sure you understand “App Sandbox in Depth” (page 15). When you’re ready to startsandboxing a new app, or to convert an existing app to adopt App Sandbox, read “Designing for App Sandbox” (page 27). If you’re providing a new, sandboxed version of your app to users already running a version that is not sandboxed, read “Migrating an App to a Sandbox” (page 33). Prerequisites Before you read this document, make sure you understand the place of App Sandbox and code signing in the overall OS X development process by reading Mac App Programming Guide . See Also To complement the damage containment provided by App Sandbox, you must provide a first line of defense by adopting secure coding practices throughout your app. To learn how, read Security Overview and Secure Coding Guide . About App Sandbox How to Use This Document 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 6An important step in adopting App Sandbox is requesting entitlements for your app. For details on all the available entitlements, see Entitlement Key Reference . You can enhance the benefits of App Sandbox in a full-featured app by implementing privilege separation. You do this using XPC, an OS X implementation of interprocess communication. To learn the details of using XPC, read Daemons and Services Programming Guide . About App Sandbox See Also 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 7In this Quick Start you get an OS X app up and running in a sandbox. You verify that the app isindeed sandboxed and then learn how to troubleshoot and resolve a typical App Sandbox error. The apps you use are Xcode, Keychain Access, Activity Monitor, and Console. Create the Xcode Project The app you create in this Quick Start uses a WebKit web view and consequently uses a network connection. Under App Sandbox, network connections don’t work unless you specifically allow them—making this a good example app for learning about sandboxing. To create the Xcode project for this Quick Start 1. In Xcode 4, create a new Xcode project for an OS X Cocoa application. ● Name the project AppSandboxQuickStart. ● Set a company identifier, such as com.yourcompany, if none is already set. ● Ensure that Use Automatic Reference Counting is selected and that the other checkboxes are unselected. 2. In the project navigator, click the MainMenu nib file. The Interface Builder canvas appears. 3. In the Xcode dock, click the Window object. The app’s window is now visible on the canvas. 4. In the object library (in the utilities area), locate the WebView object. 5. Drag a web view onto the window on the canvas. 6. (Optional) To improve the display of the web view in the running app, perform the following steps: ● Drag the sizing controls on the web view so that it completely fills the window’s main view. ● Using the size inspector for the web view, ensure that all of the inner and outer autosizing contraints are active. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 8 App Sandbox Quick Start7. Create and connect an outlet for the web view in the AppDelegate class. In Xcode, use the following specification: Outlet connection source The WebView object of the MainMenu nib file. Outlet variable location The interface block of the AppDelegate.h header file. Outlet name webView Storage weak At this point, if you were to build the app, Xcode would report an error because the project doesn’t yet use WebKit but does have a web view in the nib file. You take care of this in the next step. 8. Add the WebKit framework to the app. ● Import the WebKit framework by adding the following statement above the interface block in the AppDelegate.h header file: #import ● Link the WebKit framework to the Quick Start project as a required framework. 9. Add the following awakeFromNib method to the AppDelegate.m implementation file: - (void) awakeFromNib { [self.webView.mainFrame loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @"http://www.apple.com"]]]; } On application launch, this method requeststhe specified URL from the computer’s network connection and then sends the result to the web view for display. Now, build and run the app—which is not yet sandboxed and so has free access to system resources including its network sockets. Confirm that the app’s window displays the page you specified in the awakeFromNib method. When done, quit the app. App Sandbox Quick Start Create the Xcode Project 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 9Enable App Sandbox You enable App Sandbox by selecting a checkbox in the Xcode target editor. In Xcode, click the project file in the project navigator and click the AppSandboxQuickStart target, if they’re not already selected. View the Summary tab of the target editor. To enable App Sandbox for the project 1. In the Summary tab of the target editor, click Enable Entitlements. An entitlement is a key-value pair, defined in a property list file, that confers a specific capability or security permission to a target. When you click Enable Entitlements, Xcode automatically checks the Code Sign Application checkbox and the Enable App Sandboxing checkbox. Together, these are the essential projectsettingsfor enabling App Sandbox. When you click Enable Entitlements, Xcode also creates a .entitlements property list file, visible in the project navigator. As you use the graphical entitlementsinterface in the target editor, Xcode updates the property list file. 2. Clear the contents of the iCloud entitlement fields. This Quick Start doesn’t use iCloud. Because Xcode automatically adds iCloud entitlement values when you enable entitlements, delete them as follows: ● In the Summary tab of the target editor,select and then delete the content of the iCloud Key-Value Store field. ● Click the top row in the iCloud Containers field and click the minus button. At this point in the Quick Start, you have enabled App Sandbox but have not yet provided a code signing identity for the Xcode project. Consequently, if you attempt to build the project now, the build fails. You take care of this in the next two sections. Create a Code Signing Certificate for Testing To build a sandboxed app in Xcode, you must have a code signing certificate and its associated private key in your keychain, and then use that certificate’s code signing identity in the project. The entitlements you specify, including the entitlement that enables App Sandbox, become part of the app’s code signature when you build the project. App Sandbox Quick Start Enable App Sandbox 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 10In this section, you create a code signing certificate. This simplified process lets you stay focused on the steps for enabling a sandbox. Important: A code signing certificate that you create as described in this Quick Start is not appropriate to use with an app you intend to distribute. Before you work on sandboxing an app you plan to distribute, read “App Sandbox and Code Signing” (page 24). To create a code signing certificate for testing App Sandbox 1. In Keychain Access (available in Applications/Utilities), choose KeyChain Access > Certificate Assistant > Create a Certificate. Certificate Assistant opens. Note: Before you invoke the “Create a Certificate” menu command, ensure that no key is selected in the Keychain Access main window. If a key is selected, the menu command is not available. 2. In Certificate Assistant, name the certificate something like My Test Certificate. 3. Complete the configuration of the certificate as follows: Identity type Self Signed Root Certificate type Code Signing Let me override defaults unchecked 4. Click Create. 5. In the alert that appears, click Continue. 6. In the Conclusion window, click Done. Your new code signing certificate, and its associated public and private keys, are now available in Keychain Access. Specify the Code Signing Identity Now, configure the Xcode project to use the code signing identity from the certificate you created in the previous task. App Sandbox Quick Start Specify the Code Signing Identity 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 11To specify the code signing identity for the project 1. View the Build Settings tab in the project editor. Take care that you are using the project editor, not the target editor. 2. In the Code Signing section, locate the Code Signing Identity row. 3. Click the value area of the Code Signing Identity row. 4. In the popup menu that opens, choose Other. 5. In the text entry window that opens, enter the exact name of the newly created code signing certificate, then press . If you’re using the suggested name from thisQuick Start, the name you enter is My Test Certificate. Now, build the app. The codesign tool may display an alert asking for permission to use the new certificate. If you do see this alert, click Always Allow. Confirm That the App Is Sandboxed Build and run the Quick Start app. The window opens, but if the app issuccessfully sandboxed, no web content appears. This is because you have not yet conferred permission to access a network connection. Apart from blocked behavior, there are two specific signs that an OS X app is successfully sandboxed. To confirm that the Quick Start app is successfully sandboxed 1. In Finder, look at the contents of the ~/Library/Containers/ folder. If the Quick Start app is sandboxed, there is now a container folder named after your app. The name includes the company identifier for the project, so the complete folder name would be, for example, com.yourcompany.AppSandboxQuickStart. The system creates an app’s container folder, for a given user, the first time the user runs the app. 2. In Activity Monitor, check that the system recognizes the app as sandboxed. ● Launch Activity Monitor (available in /Applications/Utilities). ● In Activity Monitor, choose View > Columns. Ensure that the Sandbox menu item is checked. ● In the Sandbox column, confirm that the value for the Quick Start app is Yes. App Sandbox Quick Start Confirm That the App Is Sandboxed 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 12To make it easier to locate the app in Activity monitor, enter the name of the Quick Start app in the Filter field. Tip: If the app crashes when you attempt to run it,specifically by receiving an EXC_BAD_INSTRUCTION signal, the most likely reason is that you previously ran a sandboxed app with the same bundle identifier but a different code signature. This crashing upon launch is an App Sandbox security feature that prevents one app from masquerading as another and thereby gaining access to the other app’s container. You learn how to design and build your apps, in light of this security feature, in “App Sandbox and Code Signing” (page 24). Resolve an App Sandbox Violation An App Sandbox violation occurs if your app tries to do something that App Sandbox does not allow. For example, you have already seen in this Quick Start that the sandboxed app is unable to retrieve content from the web. Fine-grained restriction over access to system resources is the heart of how App Sandbox provides protection should an app become compromised by malicious code. The most common source of App Sandbox violations is a mismatch between the entitlement settings you specified in Xcode and the needs of your app. In this section you observe and then correct an App Sandbox violation. To diagnose an App Sandbox violation 1. Build and run the Quick Start app. The app starts normally, but fails to display the webpage specified in its awakeFromNib method (as you’ve previously observed in “Confirm That the App Is Sandboxed” (page 12)). Because displaying the webpage worked correctly before you sandboxed the app, it is appropriate in this case to suspect an App Sandbox violation. 2. Open Console (available in /Applications/Utilities/) and ensure that All Messages is selected in the sidebar. In the filter field of the Console window, enter sandboxd to display only App Sandbox violations. sandboxd is the name of the App Sandbox daemon that reports on sandbox violations. The relevant messages, as displayed in Console, look similar to the following: 3:56:16 pm sandboxd: ([4928]) AppSandboxQuickS(4928) deny network-outbound 111.30.222.15:80 3:56:16 pm sandboxd: ([4928]) AppSandboxQuickS(4928) deny system-socket App Sandbox Quick Start Resolve an App Sandbox Violation 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 13The problem that generates these console messages is that the Quick Start app does not yet have the entitlement for outbound network access. Tip: To see the full backtraces for either violation, click the paperclip icon near the right edge of the corresponding Console message. The steps in the previous task illustrate the general pattern to use for identifying App Sandbox violations: 1. Confirm that the violation occurs only with App Sandbox enabled in your project. 2. Provoke the violation (such as by attempting to use a network connection, if your app is designed to do that). 3. Look in Console for sandboxd messages. There is also a simple, general pattern to use for resolving such violations. To resolve the App Sandbox violation by adding the appropriate entitlement 1. Quit the Quick Start app. 2. In the Summary tab of the target editor, look for the entitlement that corresponds to the reported sandboxd violation. In this case, the primary error is deny network-outbound. The corresponding entitlement is Allow Outgoing Network Connections. 3. In the Summary tab of the target editor, select the Allow Outgoing Network Connections checkbox. Doing so applies a TRUE value, for the needed entitlement, to the Xcode project. 4. Build and run the app. The intended webpage now displays in the app. In addition, there are no new App Sandbox violation messages in Console. App Sandbox Quick Start Resolve an App Sandbox Violation 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 14The access control mechanisms used by App Sandbox to protect user data are small in number and easy to understand. But the specific steps for you to take, as you adopt App Sandbox, are unique to your app. To determine what those steps are, you must understand the key concepts for this technology. The Need for a Last Line of Defense You secure your app against attack from malware by following the practices recommended in Secure Coding Guide . But despite your best efforts to build an invulnerable barrier—by avoiding buffer overflows and other memory corruptions, preventing exposure of user data, and eliminating other vulnerabilities—your app can be exploited by malicious code. An attacker needs only to find a single hole in your defenses, or in any of the frameworks and libraries that you link against, to gain control of your app’s interactions with the system. App Sandbox is designed to confront this scenario head on by letting you describe your app’s intended interactions with the system. The system then grants your app only the access your app needs to get its job done. If malicious code gains control of a properly sandboxed app, it is left with access to only the files and resources in the app’s sandbox. To successfully adopt App Sandbox, use a different mindset than you might be accustomed to, as suggested in Table 2-1. Table 2-1 The App Sandbox mindset When developing… When adopting App Sandbox… Add features Minimize system resource use Take advantage of access throughout your app Partition functionality, then distrust each part Use the most convenient API Use the most secure API View restrictions as limitations View restrictions as safeguards 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 15 App Sandbox in DepthWhen designing for App Sandbox, you are planning for the following worst-case scenario: Despite your best efforts, malicious code breaches an unintended security hole—either in your code or in a framework you’ve linked against. Capabilities you’ve added to your app become capabilities of the hostile code. Keep this in mind as you read the rest of this document. Container Directories and File System Access When you adopt App Sandbox, the system provides a special directory for use by your app—and only by your app—called a container. Each user on a system gets an individual container for your app, within their home directory; your app has unfettered read/write access to the container for the current user. The App Sandbox Container Directory The container has the following characteristics: ● It is located at a system-defined path, within the user’s home directory, that you can obtain by calling the NSHomeDirectory function. ● Your app has unrestricted read/write access to the container and its subdirectories. ● OS X path-finding APIs (above the POSIX layer) refer to locations that are specific to your app. Most of these path-finding APIsrefer to locationsrelative to your app’s container. For example, the container includes an individual Library directory (specified by the NSLibraryDirectory search path constant) for use only by your app, with individual Application Support and Preferences subdirectories. Using your container forsupport filesrequires no code change (from the pre-sandbox version of your app) but may require one-time migration, as explained in “Migrating an App to a Sandbox” (page 33). Some path-finding APIs (above the POSIX layer) refer to app-specific locations outside of the user’s home directory. In a sandboxed app, for example, the NSTemporaryDirectory function provides a path to a directory that is outside of the user’s home directory but specific to your app and within your sandbox; you have unrestricted read/write access to it for the current user. The behavior of these path-finding APIs is suitably adjusted for App Sandbox and no code change is needed. ● OS X establishes and enforces the connection between your app and its container by way of your app’s code signature. ● The container isin a hidden location, and so users do not interact with it directly. Specifically, the container is not for user documents. It is for files that your app uses, along with databases, caches, and other app-specific data. For a shoebox-style app, in which you provide the only user interface to the user’s content, that content goes in the container and your app has full access to it. App Sandbox in Depth Container Directories and File System Access 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 16iOS Note: Because it is not for user documents, an OS X container differs from an iOS container—which, in iOS, is the one and only location for user documents. In addition, an iOS container contains the app itself. This is not so in OS X. iCloud Note: Apple’s iCloud technology, as described in “iCloud Storage”, uses the name “container” as well. There is no functional connection between an iCloud container and an App Sandbox container. Thanks to code signing, no other sandboxed app can gain access to your container, even if it attempts to masquerade as your app by using your bundle identifier. Future versions of your app, however—provided that you use the same code signature and bundle identifier—do reuse your app’s container. The time at which a container directory is created for an App Sandbox–enabled app is when the app is first run. Because a container is within a user’s home folder, each user on a system gets their own container for your app. A given user’s container is created when that user first runs your app. The Application Group Container Directory In addition to per-app containers, beginning in OS X v10.7.4, an application can use entitlements to request access to a shared container that is common to multiple applications produced by the same development team. This container is intended for content that is not user-facing, such as shared caches or databases. Applicationsthat are members of an application group also gain the ability to share Mach and POSIX semaphores and to use certain other IPC mechanisms in conjunction with other group members. These group containers are automatically created or added into each app’s sandbox container as determined by the existence of these keys, and are stored in ~/Library/Group Containers/, where can be whatever name you choose. Your app can obtain the path to the group containers by calling the containerURLForSecurityApplicationGroupIdentifier: method of NSURL. For more details, see “Adding an Application to an Application Group” in Entitlement Key Reference . Powerbox and File System Access Outside of Your Container Your sandboxed app can access file system locations outside of its container in the following three ways: ● At the specific direction of the user App Sandbox in Depth Container Directories and File System Access 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 17● By using entitlements for specific file-system locations (described in “Entitlements and System Resource Access” (page 20)) ● When the file system location is in certain directories that are world readable The OS X security technology that interacts with the user to expand yoursandbox is called Powerbox. Powerbox has no API. Your app uses Powerbox transparently when you use the NSOpenPanel and NSSavePanel classes. You enable Powerbox by setting an entitlement using Xcode, as described in “Enabling User-Selected File Access” in Entitlement Key Reference . When you invoke an Open or Save dialog from your sandboxed app, the window that appears is presented not by AppKit but by Powerbox. Using Powerbox is automatic when you adopt App Sandbox—it requires no code change from the pre-sandbox version of your app. Accessory panelsthat you’ve implemented for opening or saving are faithfully rendered and used. Note: When you adopt App Sandbox, there are some important behavioral differences for the NSOpenPanel and NSSavePanel classes, described in “Open and Save Dialog Behavior with App Sandbox” (page 19). The security benefit provided by Powerbox is that it cannot be manipulated programmatically—specifically, there is no mechanism for hostile code to use Powerbox for accessing the file system. Only a user, by interacting with Open and Save dialogs via Powerbox, can use those dialogs to reach portions of the file system outside of your previously established sandbox. For example, if a user saves a new document, Powerbox expands your sandbox to give your app read/write access to the document. When a user of your app specifies they want to use a file or a folder, the system adds the associated path to your app’s sandbox. Say, for example, a user drags the ~/Documents folder onto your app’s Dock tile (or onto your app’s Finder icon, or into an open window of your app), thereby indicating they want to use that folder. In response, the system makes the ~/Documents folder, its contents, and its subfolders available to your app. If a user instead opens a specific file, or saves to a new file, the system makes the specified file, and that file alone, available to your app. In addition, the system automatically permits a sandboxed app to: ● Connect to system input methods ● Invoke services chosen by the user from the Services menu (only those services flagged as “safe” by the service provider are available to a sandboxed app) ● Open files chosen by the user from the Open Recent menu ● Participate with other apps by way of user-invoked copy and paste App Sandbox in Depth Container Directories and File System Access 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 18● Read files that are world readable, in certain directories, including the following directories: ● /bin ● /sbin ● /usr/bin ● /usr/lib ● /usr/sbin ● /usr/share ● /System After a user hasspecified a file they want to use, that file is within your app’ssandbox. The file isthen vulnerable to attack if your app is exploited by malicious code: App Sandbox provides no protection. To provide protection for the files within your sandbox, follow the recommendations in Secure Coding Guide . A critical aspect of following user intent is that throughout OS X, simulation or alteration of user input is not allowed. This has implications for assistive apps, as described in “Determine Whether Your App Is Suitable for Sandboxing” (page 27). By default, files opened or saved by the user remain within your sandbox until your app terminates, except for files that were open at the time that your app terminates. Such files reopen automatically by way of the OS X Resume feature the next time your app launches, and are automatically added back to your app’ssandbox. To provide persistent access to resources located outside of your container, in a way that doesn’t depend on Resume, use security-scoped bookmarks as explained in “Security-Scoped Bookmarks and Persistent Resource Access” (page 21). Open and Save Dialog Behavior with App Sandbox Certain NSOpenPanel and NSSavePanel methods behave differently when App Sandbox is enabled for your app: ● You cannot invoke the OK button using the ok: method. ● You cannot rewrite the user’sselection using the panel:userEnteredFilename:confirmed: method from the NSOpenSavePanelDelegate protocol. In addition, the effective, runtime inheritance path for the NSOpenPanel and NSSavePanel classesis different with App Sandbox, as illustrated in Table 2-2. App Sandbox in Depth Container Directories and File System Access 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 19Table 2-2 Open and Save class inheritance with App Sandbox Without App Sandbox NSOpenPanel : NSSavePanel : NSPanel : NSWindow : NSResponder : NSObject With App Sandbox NSOpenPanel : NSSavePanel : NSObject Because of this runtime difference, an NSOpenPanel or NSSavePanel object inherits fewer methods with App Sandbox. If you attempt to send a message to an NSOpenPanel or NSSavePanel object, and that method is defined in the NSPanel, NSWindow, or NSResponder classes, the system raises an exception. The Xcode compiler does not issue a warning or error to alert you to this runtime behavior. Entitlements and System Resource Access An app that is notsandboxed has accessto all user-accessible system resources—including the built-in camera and microphone, network sockets, printing, and most of the file system. If successfully attacked by malicious code, such an app can behave as a hostile agent with wide-ranging potential to inflict harm. When you enable App Sandbox for your app, you remove all but a minimalset of privileges and then deliberately restore them, one-by-one, using entitlements. An entitlement is a key-value pair that identifies a specific capability, such as the capability to open an outbound network socket. One special entitlement—Enable App Sandboxing—turns on App Sandbox. When you enable sandboxing, Xcode creates a .entitlements property list file and shows it in the project navigator. If your app requires a capability, request it by adding the corresponding entitlement to your Xcode project using the Summary tab of the target editor. If you don’t require a capability, take care to not include the corresponding entitlement. You request entitlements on a target-by-target basis. If your app has a single target—the main application—you request entitlements only forthat target. If you design your app to use a main application along with helpers (in the form of XPC services), you request entitlements individually, and as appropriate, for each target. You learn more about this in “XPC and Privilege Separation” (page 26). You may require finer-grained control over your app’s entitlements than is available in the Xcode target editor. For example, you might request a temporary exception entitlement because App Sandbox does not support a capability your app needs, such as the ability to send Apple events. To work with temporary exception entitlements, use the Xcode property list editor to edit a target’s .entitlements property list file directly. App Sandbox in Depth Entitlements and System Resource Access 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 20Note: If you request a temporary exception entitlement, be sure to follow the guidance regarding entitlements provided on the iTunes Connect website. In particular, use the Review Notes field in iTunes Connect to explain why your app needs the temporary exception. OS X App Sandbox entitlements are described in “Enabling App Sandbox” in Entitlement Key Reference . For a walk-through of requesting an entitlement for a target in an Xcode project,see “App Sandbox Quick Start” (page 8). Security-Scoped Bookmarks and Persistent Resource Access Your app’s access to file-system locations outside of its container—as granted to your app by way of user intent, such as through Powerbox—does not automatically persist across app launches or system restarts. When your app reopens, you have to start over. (The one exception to this is for files open at the time that your app terminates, which remain in your sandbox thanks to the OS X Resume feature). Starting in OS X v10.7.3, you can retain access to file-system resources by employing a security mechanism, known as security-scoped bookmarks, that preserves user intent. Here are a few examples of app features that can benefit from this: ● A user-selected download, processing, or output folder ● An image browser library file, which points to user-specified images at arbitrary locations ● A complex document format that supports embedded media stored in other locations Two Distinct Types of Security-Scoped Bookmark Security-scoped bookmarks, available starting in OS X v10.7.3, support two distinct use cases: ● An app-scoped bookmark provides your sandboxed app with persistent access to a user-specified file or folder. For example, if your app employs a download or processing folder that is outside of the app container, obtain initial access by presenting an NSOpenPanel dialog to obtain the user’s intent to use a specific folder. Then, create an app-scoped bookmark for that folder and store it as part of the app’s configuration (perhaps in a property list file or using the NSUserDefaults class). With the app-scoped bookmark, your app can obtain future access to the folder. ● A document-scoped bookmark provides a specific document with persistent access to a file. App Sandbox in Depth Security-Scoped Bookmarks and Persistent Resource Access 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 21For example, a code editor typically supports the notion of a project document that refers to other files and needs persistent access to those files. Other examples are an image browser or editor that maintains an image library, in which the library file needs persistent accessto the imagesit owns; or a word processor that supports embedded images, multimedia, or font files in its document format. In these cases, you configure the document format (of the project file, library file, word processing document, and so on) to be able to store security-scoped bookmarks to the files a document refers to. Obtain initial access to a referred item by asking for user intent to use that item. Then, create a document-scoped bookmark for the item and store the bookmark as part of the document’s data. A document-scoped bookmark can be resolved by any app that has access to the bookmark data itself and to the document that owns the bookmark. This supports portability, allowing a user, for example, to send a document to another user; the document’s secure bookmarks remain usable for the recipient. The document can be a flat file or a document distributed as a bundle. A document-scoped bookmark can point only to a file, not a folder, and only to a file that is not in a location used by the system (such as /private or /Library). Using Security-Scoped Bookmarks To use either type of security-scoped bookmark requires you to perform five steps: 1. Set the appropriate entitlement in the target that needs to use security-scoped bookmarks. Do this once per target as part of configuring your Xcode project. 2. Create a security-scoped bookmark. Do this when a user has indicated intent (such as via Powerbox) to use a file-system resource outside of your app’s container, and you want to preserve your app’s ability to access the resource. 3. Resolve the security-scoped bookmark. Do this when your app later (for example, after app relaunch) needs access to a resource you bookmarked in step 2. The result of this step is a security-scoped URL. 4. Explicitly indicate that you want to use the file-system resource whose URL you obtained in step 3. Do this immediately after obtaining the security-scoped URL (or, when you later want to regain access to the resource after having relinquished your access to it). 5. When done using the resource, explicitly indicate that you want to stop using it. Do this as soon as you know that you no longer need access to the resource (typically, after you close it). After you relinquish access to a file-system resource, to use that resource again you must return to step 4 (to again indicate you want to use the resource). If your app is relaunched, you must return to step 3 (to resolve the security-scoped bookmark). App Sandbox in Depth Security-Scoped Bookmarks and Persistent Resource Access 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 22The first step in the preceding list, requesting entitlements, is the prerequisite for using either type of security-scoped bookmark. Perform this step as follows: ● To use app-scoped bookmarksin a target,setthe com.apple.security.files.bookmarks.app-scope entitlement value to true. ● To use document-scoped bookmarks in a target, set the com.apple.security.files.bookmarks.document-scope entitlement value to true. You can request either or both of these entitlements in a target, as needed. These entitlements are available starting in OS X v10.7.3 and are described in “Enabling Security-Scoped Bookmark and URL Access” in Entitlement Key Reference . With the appropriate entitlements, you can create a security-scoped bookmark by calling the bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error: method of the NSURL class (or its Core Foundation equivalent, the CFURLCreateBookmarkData function). When you later need access to a bookmarked resource, resolve its security-scoped bookmark by calling the the URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:method of the NSURL class (or its Core Foundation equivalent, the CFURLCreateByResolvingBookmarkData function). In a sandboxed app, you cannot access the file-system resource that a security-scoped URL points to until you call the startAccessingSecurityScopedResource method (or its Core Foundation equivalent, the CFURLStartAccessingSecurityScopedResource function) on the URL. When you no longer need access to a resource that you obtained using security scope (typically, after you close the resource) you must call the stopAccessingSecurityScopedResource method (or its Core Foundation equivalent, the CFURLStopAccessingSecurityScopedResource function) on the resource’s URL. Calls to start and stop access are nestable on a per-process basis. This means that if your app calls the start method on a URL twice, to fully relinquish access to the referenced resource you must call the corresponding stop method twice. If you call the stop method on a URL whose referenced resource you do not have access to, nothing happens. Warning: You must balance every call to the startAccessingSecurityScopedResource method with a corresponding call to the stopAccessingSecurityScopedResource method. If you fail to relinquish your access when you no longer need a file-system resource, your app leaks kernel resources. If sufficient kernel resources are leaked, your app loses its ability to add file-system locations to its sandbox, such as via Powerbox or security-scoped bookmarks, until relaunched. App Sandbox in Depth Security-Scoped Bookmarks and Persistent Resource Access 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 23For detailed descriptions of the methods, constants, and entitlementsto use for implementing security-scoped bookmarks in your app, read NSURL Class Reference or CFURL Reference , and read “Enabling Security-Scoped Bookmark and URL Access” in Entitlement Key Reference . App Sandbox and Code Signing After you enable App Sandbox and specify other entitlements for a target in your Xcode project, you must code sign the project. Take note of the distinction between how you set entitlements and how you set a code signing identity: ● Use the Xcode target editor to set entitlements on a target-by-target basis ● Use the Xcode project build settings to set the code signing identity for a project as a whole You must perform code signing because entitlements (including the special entitlement that enables App Sandbox) are built into an app’s code signature. From another perspective, an unsigned app is not sandboxed and has only default entitlements, regardless of settings you’ve applied in the Xcode target editor. OS X enforces a tie between an app’s container and the app’s code signature. This important security feature ensures that no other sandboxed app can access your container. The mechanism works as follows: After the system creates a container for an app, each time an app with the same bundle ID launches, the system checks that the app’s code signature matches a code signature expected by the container. If the system detects a mismatch, it prevents the app from launching. OS X’s enforcement of container integrity impacts your development and distribution cycle. This is because, in the course of creating and distributing an app, the app is code signed using various signatures. Here’s how the process works: 1. Before you create a project, you obtain two code signing certificatesfrom Apple: a development certificate and a distribution certificate. (To learn how to obtain code signing certificates, read “Creating Signing Certificates” in Tools Workflow Guide for Mac .) For development and testing, you sign your app with the development code signature. 2. When the Mac App Store distributes your app, it is signed with an Apple code signature. For testing and debugging, you may want to run both versions of your app: the version you sign and the version Apple signs. But OS X sees the Apple-signed version of your app as an intruder and won’t allow it to launch: Its code signature does not match the one expected by your app’s existing container. If you try to run the Apple-signed version of your app, you get a crash report containing a statement similar to this: App Sandbox in Depth App Sandbox and Code Signing 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 24Exception Type: EXC_BAD_INSTRUCTION (SIGILL) The solution is to adjust the access control list (ACL) on your app’s container to recognize the Apple-signed version of your app. Specifically, you add the designated code requirement of the Apple-signed version of your app to the app container’s ACL. To adjust an ACL to recognize an Apple-signed version of your app 1. Open Terminal (in /Applications/Utilities). 2. Open a Finder window that contains the Apple-signed version of your app. 3. In Terminal, enter the following command: asctl container acl add -file In place of the placeholder, substitute the path to the Apple-signed version of your app. Instead of manually typing the path, you can drag the app’s Finder icon to the Terminal window. The container’s ACL now includes the designated code requirements for both versions of your app. OS X then allows you to run either version of your app. You can use this same technique to share a container between (1) a version of an app that you initially signed with a self-generated code signature, such as the one you created in “App Sandbox Quick Start” (page 8), and (2) a later version that you signed with a development code signature from Apple. You can view the list of code requirements in a container’s ACL. For example, after adding the designated code requirement for the Apple-signed version of your app, you can confirm that the container’s ACL lists two permissible code requirements. To display the list of code requirements in a container’s ACL 1. Open Terminal (in /Applications/Utilities). 2. In Terminal, enter the following command: asctl container acl list -bundle In place of the placeholder,substitute the name of your app’s container directory. (The name of your app’s container directory is typically the same as your app’s bundle identifier.) App Sandbox in Depth App Sandbox and Code Signing 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 25For more information about working with App Sandbox container access control lists and their code requirements, read the man page for the asctl (App Sandbox control) tool. External Tools, XPC Services, and Privilege Separation Some app operations are more likely to be targets of malicious exploitation. Examples are the parsing of data received over a network, and the decoding of video frames. By using XPC, you can improve the effectiveness of the damage containment offered by App Sandbox by separating such potentially dangerous activities into their own address spaces. XPC is an OS X interprocess communication technology that complements App Sandbox by enabling privilege separation. Privilege separation, in turn, is a development strategy in which you divide an app into pieces according to the system resource access that each piece needs. The component pieces that you create are called XPC services. You create an XPC service as an individual target in your Xcode project. Each service gets its own sandbox—specifically, it gets its own container and its own set of entitlements. In addition, an XPC service that you include with your app is accessible only by your app. These advantages add up to making XPC the best technology for implementing privilege separation in an OS X app. By contrast, a child process created by using the posix_spawn function, by calling fork and exec (discouraged), or by using the NSTask class simply inherits the sandbox of the process that created it. You cannot configure a child process’s entitlements. For these reasons, child processes do not provide effective privilege separation. To use XPC with App Sandbox: ● Confer minimal privileges to each XPC service, according to its needs. ● Design the data transfers between the main app and each XPC service to be secure. ● Structure your app’s bundle appropriately. The life cycle of an XPC service, and its integration with Grand Central Dispatch (GCD), is managed entirely by the system. To obtain this support, you need only to structure your app’s bundle correctly. For more on XPC, see “Creating XPC Services” in Daemons and Services Programming Guide . App Sandbox in Depth External Tools, XPC Services, and Privilege Separation 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 26There’s a common, basic workflow for designing or converting an app for App Sandbox. The specific steps to take for your particular app, however, are as unique as your app. To create a work plan for adopting App Sandbox, use the process outlined here, along with the conceptual understanding you have from the earlier chapters in this document. Six Steps for Adopting App Sandbox The workflow to convert an OS X app to work in a sandbox typically consists of the following six steps: 1. Determine whether your app is suitable for sandboxing. 2. Design a development and distribution strategy. 3. Resolve API incompatibilities. 4. Apply the App Sandbox entitlements you need. 5. Add privilege separation using XPC. 6. Implement a migration strategy. Determine Whether Your App Is Suitable for Sandboxing Most OS X apps are fully compatible with App Sandbox. If you need behavior in your app that App Sandbox does not allow, consider an alternative approach. For example, if your app depends on hard-coded paths to locationsin the user’s home directory, consider the advantages of using Cocoa and Core Foundation path-finding APIs, which use the sandbox container instead. If you choose to not sandbox your app now, or if you determine that you need a temporary exception entitlement, use Apple’s bug reporting system to let Apple know what’s not working for you. Apple considers feature requests as it develops the OS X platform. Also, if you request a temporary exception, be sure to use the Review Notes field in iTunes Connect to explain why the exception is needed. The following app behaviors are incompatible with App Sandbox: ● Use of Authorization Services 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 27 Designing for App SandboxWith App Sandbox, you cannot do work with the functions described in Authorization Services C Reference . ● Use of accessibility APIs in assistive apps With App Sandbox, you can and should enable your app for accessibility, as described in Accessibility Overview for OS X . However, you cannot sandbox an assistive app such as a screen reader, and you cannot sandbox an app that controls another app. ● Sending Apple events to arbitrary apps With App Sandbox, you can receive Apple events and respond to Apple events, but you cannotsend Apple events to arbitrary apps. By using a temporary exception entitlement, you can enable the sending of Apple eventsto a list ofspecific apps that you specify, as described in Entitlement Key Reference . ● Sending user-info dictionaries in broadcast notifications to other tasks With App Sandbox, you cannot include a user-info dictionary when posting to an NSDistributedNotificationCenter object for messaging other tasks. (You can , as usual, include a user-info dictionary when messaging other parts of your app by way of posting to an NSNotificationCenter object.) ● Loading kernel extensions Loading of kernel extensions is prohibited with App Sandbox. ● Simulation of user input in Open and Save dialogs If your app depends on programmatically manipulating Open or Save dialogs to simulate or alter user input, your app is unsuitable for sandboxing. ● Setting preferences on other apps With App Sandbox, each app maintains its preferences inside its container. Your app has no access to the preferences of other apps. ● Configuring network settings With App Sandbox, your app cannot modify the system’s network configuration (whether with the System Configuration framework, the CoreWLAN framework, or other similar APIs) because doing so requires administrator privileges. ● Terminating other apps With App Sandbox, you cannot use the NSRunningApplication class to terminate other apps. Designing for App Sandbox Determine Whether Your App Is Suitable for Sandboxing 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 28Design a Development and Distribution Strategy During development, you may have occasion to run versions of your app that are signed with different code signatures. After you’ve run your app signed using one signature, the system won’t allow a second version of your app, signed with a second signature, to launch—unless you modify the app’s container. Be sure to understand how to handle this, as described in “App Sandbox and Code Signing” (page 24), as you design your development strategy. When a customer first launches a sandboxed version of your app, the system creates a container for your app. The access control list (ACL) for the container is established at that time, and the ACL istied to the code signature of that version of your app. The implication for you is that all future versions of the app that you distribute must use the same code signature. To learn how to obtain code signing certificatesfrom Apple, read “Creating Signing Certificates” in Tools Workflow Guide for Mac . Resolve API Incompatibilities If you are using OS X APIs in ways that were not intended, or in ways that expose user data to attack, you may encounter incompatibilities with App Sandbox. This section provides some examples of app design that are incompatible with App Sandbox and suggests what you can do instead. Opening, Saving, and Tracking Documents If you are managing documents using any technology other than the NSDocument class, you should convert to using this classto benefit from its built-in App Sandbox support. The NSDocument class automatically works with Powerbox. NSDocument also provides support for keeping documents within your sandbox if the user moves them using the Finder. Remember that the inheritance path of the NSOpenPanel and NSSavePanel classes is different when your app is sandboxed. See “Open and Save Dialog Behavior with App Sandbox” (page 19). If you don’t use the NSDocument class to manage your app’s documents, you can craft your own file-system support for App Sandbox by using the NSFileCoordinator class and the NSFilePresenter protocol. Retaining Access to File System Resources If your app depends on persistent access to file system resources outside of your app’s container, you need to adopt security-scoped bookmarks as described in “Security-Scoped Bookmarks and Persistent Resource Access” (page 21). Designing for App Sandbox Design a Development and Distribution Strategy 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 29Creating a Login Item for Your App To create a login item for your sandboxed app, use the SMLoginItemSetEnabled function (declared in ServiceManagement/SMLoginItem.h) as described in “Adding Login Items Using the Service Management Framework” in Daemons and Services Programming Guide . (With App Sandbox, you cannot create a login item using functions in the LSSharedFileList.h header file. For example, you cannot use the function LSSharedFileListInsertItemURL. Nor can you manipulate the state of launch services, such as by using the function LSRegisterURL.) Accessing User Data OS X path-finding APIs, above the POSIX layer, return paths relative to the container instead of relative to the user’s home directory. If your app, before you sandbox it, accesses locations in the user’s actual home directory (~) and you are using Cocoa or Core Foundation APIs, then, after you enable sandboxing, your path-finding code automatically uses your app’s container instead. For first launch of your sandboxed app, OS X automatically migrates your app’s main preferences file. If your app uses additional support files, perform a one-time migration of those files to the container, as described in “Migrating an App to a Sandbox” (page 33). If you are using a POSIX function such as getpwuid to obtain the path to the user’s actual home directory, consider instead using a Cocoa or Core Foundation symbol such as the NSHomeDirectory function. By using Cocoa or Core Foundation, you support the App Sandbox restriction against directly accessing the user’s home directory. If your app requires access to the user’s home directory in order to function, let Apple know about your needs using the Apple bug reporting system. In addition, be sure to follow the guidance regarding entitlements provided on the iTunes Connect website. Accessing Preferences of Other Apps Because App Sandbox directs path-finding APIs to the container for your app, reading or writing to the user’s preferencestakes place within the container. Preferencesfor othersandboxed apps are inaccessible. Preferences for appsthat are notsandboxed are placed in the ~/Library/Preferences directory, which is also inaccessible to your sandboxed app. If your app requires access to another app’s preferences in order to function—for example, if it requires access to the playlists that a user has defined for iTunes—let Apple know about your needs using the Apple bug reporting system. In addition, be sure to follow the guidance regarding entitlements provided on the iTunes Connect website. Designing for App Sandbox Resolve API Incompatibilities 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 30With these provisosin mind, you can use a path-based temporary exception entitlement to gain programmatic accessto the user’s ~/Library/Preferences folder. Use a read-only entitlement to avoid opening the user’s preferences to malicious exploitation. A POSIX function, such as getpwuid, can provide the file system path you need. For details on entitlements, see Entitlement Key Reference . Apply the App Sandbox Entitlements You Need To adopt App Sandbox for a target in an Xcode project, apply the value to the com.apple.security.app-sandbox entitlement key for that target. Do this in the Xcode target editor by selecting the Enable App Sandboxing checkbox. Apply other entitlements as needed. For a complete list, refer to Entitlement Key Reference . Important: App Sandbox protects user data most effectively when you minimize the entitlements you request. Take care not to request entitlements for privileges your app does not need. Consider whether making a change in your app could eliminate the need for an entitlement. Here’s a basic workflow to use to determine which entitlements you need: 1. Run your app and exercise its features. 2. In the Console app (available in /Applications/Utilities/), look for sandboxd violations in the All Messages system log query. Each such violation indicates that your app attempted to do something not allowed by your sandbox. Here’s what a sandboxd violation looks like in Console: 3:56:16 pm sandboxd: ([4928]) AppSandboxQuickS(4928) deny network-outbound 111.30.222.15:80 3:56:16 pm sandboxd: ([4928]) AppSandboxQuickS(4928) deny system-socket Click the paperclip icon to the right of a violation message to view the backtrace that shows what led to the violation. 3. For each sandboxd violation you find, determine how to resolve the problem. In same cases, a simple change to your app,such as using your Container instead of other file system locations,solvesthe problem. In other cases, applying an App Sandbox entitlement using the Xcode target editor is the best choice. 4. Using the Xcode target editor, enable the entitlement that you think will resolve the violation. 5. Run the app and exercise its features again. Either confirm that you have resolved the sandboxd violation, or investigate further. Designing for App Sandbox Apply the App Sandbox Entitlements You Need 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 31If you choose not to sandbox your app now or to use a temporary exception entitlement, use Apple’s bug reporting system to let Apple know about the issue you are encountering. Apple considers feature requests as it develops the OS X platform. Also, be sure use the Review Notes field in iTunes Connect to explain why the exception is needed. Add Privilege Separation Using XPC When developing for App Sandbox, look at your app’s behaviors in terms of privileges and access. Consider the potential benefitsto security and robustness ofseparating high-risk operationsinto their own XPC services. When you determine that a feature should be placed into an XPC service, do so by referring to “Creating XPC Services” in Daemons and Services Programming Guide . Implement a Migration Strategy Ensure that customers who are currently using a pre-sandbox version of your app experience a painless upgrade when they install the sandboxed version. For details on how to implement a container migration manifest, read “Migrating an App to a Sandbox” (page 33). Designing for App Sandbox Add Privilege Separation Using XPC 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 32An app that is not sandboxed places its support files in locations that are inaccessible to a sandboxed version of the same app. For example, the typical locations for support files are shown here: Path Description Legacy location ~/Library/Application Support// Sandbox location ~/Library/Containers//Data/Library/Application Support// As you can see, the sandbox location for the Application Support directory is within an app’s container—thus allowing the sandboxed app unrestricted read/write access to those files. If you previously distributed your app without sandboxing and you now want to provide a sandboxed version, you must move support files into their new, sandbox-accessible locations. Note: The system automatically migrates your app’s preferences file (~/Library/Preferences/com.yourCompany.YourApp.plist) on firstlaunch of yoursandboxed app. OS X provides support-file migration, on a per-user basis, when a user first launches the sandboxed version of your app. This support depends on a special property list file you create, called a container migration manifest. A container migration manifest consists of an array of strings that identify the support files and directories you want to migrate when a user first launches the sandboxed version of your app. The file’s name must be container-migration.plist. For each file or directory you specify for migration, you have a choice of allowing the system to place the item appropriately in your container, or explicitly specifying the destination location. OS X moves—it does not copy—the files and directories you specify in a container migration manifest. That is, the files and directories migrated into your app’s container no longer exist at their original locations. In addition, container migration is a one-way process: You are responsible for providing a way to undo it, should you need to do so during development or testing. The section “Undoing a Migration for Testing” (page 36) provides a suggestion about this. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 33 Migrating an App to a SandboxCreating a Container Migration Manifest To support migration of app support files when a user first launches the sandboxed version of your app, create a container migration manifest. To create and add a container migration manifest to an Xcode project 1. Add a property list file to the Xcode project. The Property List template is in the OS X “Resource” group in the file template dialog. Important: Be sure to name the file container-migration.plist spelled and lowercased exactly this way. 2. Add a Move property to the container migration manifest. The Move property is the lone top-level key in a container migration manifest. You add it to the empty file as follows: ● Right-click the empty editor for the new .plist file, then choose Add Row. ● In the Key column, enter Move as the name of the key. You must use this exact casing and spelling. ● In the Type column, choose Array. 3. Add a string to the Move array for the first file or folder you want to migrate. For example, suppose you want to migrate your Application Support directory (along with its contained files and subdirectories) to your container. If your directory is called App Sandbox Quick Start and is currently within the ~/Library/Application Support directory, use the following string as the value for the new property list item: ${ApplicationSupport}/App Sandbox Quick Start No trailing slash character is required, and space characters are permitted. The search-path constant in the path is equivalent to ~/Library/Application Support. This constant is described, along with other commonly used directories, in “Use Variables to Specify Support-File Directories” (page 37). Similarly, add additional strings to identify the original (before sandboxing) paths of additional files or folders you want to migrate. Migrating an App to a Sandbox Creating a Container Migration Manifest 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 34When you specify a directory to be moved, keep in mind that the move is recursive—it includes all the subdirectories and files within the directory you specify. Before you first test a migration manifest, provide a way to undo the migration, such as suggested in “Undoing a Migration for Testing” (page 36). To test a container migration manifest 1. In the Finder, open two windows as follows: ● In one window, view the contents of the ~/Library/Containers/ directory. ● In the other window, view the contents of the directory containing the support files named in the container migration manifest—that is, the files you want to migrate. 2. Build and run the Xcode project. Upon successful migration, the support files disappear from the original (nonsandbox) directory and appear in your app’s container. If you want to alter the arrangement ofsupport files during migration, use a slightly more complicated .plist structure. Specifically, for a file or directory whose migration destination you want to control, provide both a starting and an ending path. The ending path is relative to the Data directory in your container. In specifying an ending path, you can use any of the search-path constants described in “Use Variablesto Specify Support-File Directories” (page 37). If your destination path specifies a custom directory (one that isn’t part of a standard container), the system creates the directory during migration. The following task assumes that you’re using the Xcode property list editor and working with the container migration manifest you created earlier in this chapter. To control the destination of a migrated file or directory 1. In the container migration manifest, add a new item to the Move array. 2. In the Type column, choose Array. 3. Add two strings as children of the new array item. 4. In the top string of the pair, specify the origin path of the file or directory you want to migrate. 5. In the bottom string of the pair, specify the destination (sandbox) custom path for the file or directory you want to migrate. Migrating an App to a Sandbox Creating a Container Migration Manifest 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 35File migration proceeds from top-to-bottom through the container migration manifest. Take care to list items in an order that works. For example,suppose you want to move your entire Application Support directory as-is, except for one file. You want that file to go into a new directory parallel to Application Support in the container. For this approach to work, you must specify the individual file move before you specify the move of the Application Support directory—that is, specify the individual file move higher in the container migration manifest. (If Application Support were specified to be moved first, the individual file would no longer be at its original location at the time the migration process attempted to move it to its new, custom location in the container.) Undoing a Migration for Testing When testing migration of support files, you may find it necessary to perform migration more than once. To support this, you need a way to restore your starting directory structures—that is, the structures as they exist prior to migration. One way to do this is to make a copy of the directories to migrate, before you perform a first migration. Save this copy in a location unaffected by the migration manifest. The following task assumes you have created this sort of backup copy. To manually undo a container migration for testing purposes 1. Manually copy the files and directories—those specified in the manifest—from your backup copy to their original (premigration) locations. 2. Delete your app’s container. The next time you launch the app, the system recreates the container and migrates the support files according to the current version of the container migration manifest. An Example Container Migration Manifest Listing 4-1 shows an example manifest as viewed in a text editor. Listing 4-1 An example container migration manifest Migrating an App to a Sandbox Undoing a Migration for Testing 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 36 Move ${Library}/MyApp/MyConfiguration.plist ${Library}/MyApp/MyDataStore.xml ${ApplicationSupport}/MyApp/MyDataStore.xml This manifest specifies the migration of two items from the user’s Library directory to the app’s container. For the first item, MyConfiguration.plist, only the origin path is specified, leaving it to the migration process to place the file appropriately. For the second item, MyDataStore.xml, both an origin and a custom destination path are specified. The ${Library} and ${ApplicationSupport} portions of the paths are variables you can use as a convenience. For a list of variables you can use in a container migration manifest, see “Use Variables to Specify Support-File Directories” (page 37). Use Variables to Specify Support-File Directories When you specify a path in a container migration manifest, you can use certain variables that correspond to commonly used support file directories. These variables work in origin and destination paths, but the path that a variable resolves to depends on the context. Refer to Table 4-1. Table 4-1 How system directory variables resolve depending on context Context Variable resolves to Origin path Home-relative path (relative to the ~ directory) Destination path Container-relative path (relative to the Data directory in the container) Migrating an App to a Sandbox Use Variables to Specify Support-File Directories 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 37The variables you can use for specifying support-file directories are described in Table 4-2 (page 38). For an example of how to use these variables, see Listing 4-1 (page 36). You can also use a special variable that resolves to your app’s bundle identifier, allowing you to conveniently incorporate it into an origin or destination path. This variable is ${BundleId}. Table 4-2 Variables for support-file directories Variable Directory The directory containing application support files. Corresponds to the NSApplicationSupportDirectory search-path constant. ${ApplicationSupport} The directory containing the user’s autosaved documents. Corresponds to the NSAutosavedInformationDirectory search-path constant. ${AutosavedInformation} The directory containing discardable cache files. Corresponds to the NSCachesDirectory search-path constant. ${Caches} Each variable correspondsto the directory containing the user’s documents. Corresponds to the NSDocumentDirectory search-path constant. ${Document} ${Documents} The current user’s home directory. Corresponds to the directory returned by the NSHomeDirectory function. When in a destination path in a manifest, resolves to the Container directory. ${Home} The directory containing application-related support and configuration files. Corresponds to the NSLibraryDirectory search-path constant. ${Library} Migrating an App to a Sandbox Use Variables to Specify Support-File Directories 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 38This table describes the changes to App Sandbox Design Guide . Date Notes 2012-09-19 Clarified information about launching external tools. 2012-07-23 Added an explanation of app group containers. Improved the explanation of security-scoped bookmarks in “Security-Scoped Bookmarks and Persistent Resource Access” (page 21); updated that section for OS X v10.7.4. 2012-05-14 Added a brief section in the “Designing for App Sandbox” chapter: “Retaining Access to File System Resources” (page 29). Improved the discussion in “Opening, Saving, and Tracking Documents” (page 29), adding information about using file coordinators. Corrected the information in “Creating a Login Item for Your App” (page 30). Improved explanation ofsecurity-scoped bookmarksin “Security-Scoped Bookmarks and Persistent Resource Access” (page 21). 2012-03-14 Clarified the explanation of the container directory in “The App Sandbox Container Directory” (page 16) Updated for OS X v10.7.3, including an explanation of how to use security-scoped bookmarks. 2012-02-16 Added a section explaining how to provide persistent accessto file-system resources, “Security-Scoped Bookmarks and Persistent Resource Access” (page 21). 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 39 Document Revision HistoryDate Notes Expanded the discussion in “Powerbox and File System Access Outside of Your Container” (page 17) to better explain how user actions expand your app’s file system access. Added a section detailing the changes in behavior of Open and Save dialogs, “Open and Save Dialog Behavior with App Sandbox” (page 19). New document that explains Apple's security technology for damage containment, and how to use it. 2011-09-27 Portions of this document were previously published in Code Signing and Application Sandboxing Guide . Document Revision History 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 40Apple Inc. © 2012 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrievalsystem, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apple’s copyright notice. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Apple, the Apple logo, Cocoa, Finder, iTunes, Keychain, Mac, OS X, Sand, and Xcode are trademarks of Apple Inc., registered in the U.S. and other countries. QuickStart is a trademark of Apple Inc. iCloud is a service mark of Apple Inc., registered in the U.S. and other countries. App Store and Mac App Store are service marks of Apple Inc. iOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is used under license. Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.ASARESULT, THISDOCUMENT IS PROVIDED “AS IS,” AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state. iTunes Connect Sales and Trends Guide App Store  Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 1Apple Inc. © 2012 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apple’s copyright notice. The Apple logo is a trademark of Apple Inc. Use of the “keyboard” Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of Apple may constitute trademark infringement and unfair competition in violation of federal and state laws. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist partners in understanding the Sales and Trends module of iTunes Connect. Every effort has been made to ensure that the information in this document is accurate. Apple is not responsible for typographical errors. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED “AS IS,” AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 2Contents 1. Getting Started 4 2. Navigating and Viewing Your Sales and Trends Data 5 2.1. Dashboard View 6 2.2. Sales View 11 3. Downloading, Reading and Understanding Sales and Trends Data 13 3.1. Downloading Reports 13 3.2. Auto-Ingest Tool 14 3.3. Reading Reports 16 3.4. Understanding Units 18 4. Contact Us 19 Appendix A - Sales Report Field Definitions 20 Appendix B - Opt-In Report Field Definitions 21 Appendix C - Apple Fiscal Calendar 22 Appendix D - Definition of Day and Week 23 Appendix E – Product Type Identifiers 24 Appendix F – Country Codes 25 Appendix G – Promotional Codes 26 Appendix H – Currency Codes 27 Appendix I - Subscription and Period Field Values 28 Appendix J - FAQs 29 Appendix K - Sample Sales Report 30 Appendix L – Other Uses 32 Appendix M - Newsstand Report Field Definitions 33 Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 31. Getting Started iTunes Connect can be accessed at http://itunesconnect.apple.com. Once you login, you will be presented with the Welcome page below, which contains notifications at the top and module links to help you navigate through iTunes Connect. The Welcome page you will see is based on the modules applicable to you and may be different from what is shown below. This guide is primarily intended to cover the Sales and Trends module. The initial user who entered into the program license agreement has the “Admin” role, which provides access to all modules, including the ability to add other “Admin” users (using the Manage Users module). The “Admin” users associated with your account are expected to manage (add, modify, and delete) your users based on your needs. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 42. Navigating and Viewing Your Sales and Trends Data The iTunes Connect Sales and Trends module allows you to interact with your sales data in various ways: ■ A summary that provides total units, percent differences, graphs, top selling content and largest market information (Dashboard view). ■ Previews that provide the top 50 transactions of sales aggregated at the title level in descending sorted order (Sales view). ■ Download full transaction reports for import and further analysis (Sales view). When you are ready to access the Sales and Trends module, click on the following link located on the Welcome page: Upon selecting the Sales and Trends module, you will be taken to the Dashboard view. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 52.1. Dashboard View The Dashboard will load and display the most recent daily data available. The following identifies the various components of the dashboard. The “Selection” controls located above the graph allow you to change the information displayed. Vendor Selection The Vendor Selection display lists the legal entity name for the Sales and Trends that you are viewing. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 6View Selection The View Selection allows you to switch between different views. In addition to the Dashboard view, you can toggle to the Sales view (the Sales view is covered in section 2.2). Period Selection You can choose the type (daily or weekly), as well as the period of interest. The date menu will display all periods available up to the last 13 weeks or 14 days. Category Selection You can choose the specific category you wish to view in the Dashboard if you sell more than one type of content (i.e. iOS and MacOS). Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 7Type Selection You can choose the specific type of content within a category to view in the Dashboard’s graph, Top Products and Top Markets. The available types are the same for both the iOS and MacOS category. Refer to Appendix E for the complete product breakdown by product type. Graph Selection You can choose between a line graph and bar graph by clicking on the graph buttons located on the right top corner of the graph. Graph The data displayed in the graph is based on the period (specific day or week), category and type selected. When you hover over a specific day or week in the graph (bar or line), the date, number of units and type will be displayed. The following displays the graph for the period of August 30, 2010 and the Free Apps category while mousing over the August 30, 2010 bar. When viewing daily reports, the graph will also display the percentage change from the same day in the prior period. In the graph above you see the percentage change of free apps sold on 8/30 (Monday) to those sold on 8/24 (Monday of prior week) based on units. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 8Top Products Display The Top Products display is based on the period (specific day or week), category (iOS or Mac OS) and the type (Free Apps, Paid Apps, In Apps, Updates) selected. The section provides a summary of net units at the Product level. A Product can be reported as separate lines in your reports due to differences such as territories but will be reported as combined in terms of units in this display since the units are aggregated at the Product level world-wide based on unique product identifier. The “Change” column in the display shows units and percentage change from the prior period (selected day over same day of the prior week, or selected week over prior week). Top Markets Display The Top Markets display is based on the period (specific day or week), category (iOS and Mac OS) and the type (e.g. Free Apps) selected. This section provides a summary of net units for all products at the country (iTunes Storefront) level. The “Change” column in the display shows units and percentage change from the prior period (selected day over same day of the prior week, or selected week over prior week). See Appendix F for iTunes Storefront listing. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 9Resources At the bottom left of all pages you will find three links: ■ Fiscal Calendar - Opens a new window that displays Apple’s fiscal calendar ■ User Guide - Provides the most current version of this guide ■ Mobile Guide - Provides the user guide for the iTC Mobile Application. Done Button The “Done” button at the bottom right of all pages takes you to the Dashboard from the Sales view, and to the iTunes Connect Welcome page from the Dashboard. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 102.2. Sales View The Sales view allows you to analyze at the specific content level. You can preview the Top 50 products delivered based on transaction volume summarized and sorted descending by Units, and can download the available daily and weekly reports for additional information about all your transactions. You can also download detailed Newsstand reports or contact information for customers that have elected to “opt-in” when purchasing an In-App Purchase subscription. The following is an example of the Sales view. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 11Understanding The Sales Preview When you land on the Sales view, the Period presented is the latest daily data available. Using the Period Selection menu, you can preview all available daily and weekly data for all content types in all categories. Once you have selected a period, the Preview will be displayed. The Preview summarizes the data based on the columns displayed, including any promotional transactions indicated with (Promo Indicator). You can hover over the Promo Indicator to see the type of promotion. See Appendix G for Promotional Codes. Autorenewable subscription transactions are indicated with (Subscription Indicator). The preview functionality does not contain the full report. To view or analyze all transactions you must download the full reports. The previews summarize data differently than the reports based on the information available (i.e. the preview may summarize sales at a higher level as the downloaded report has more fields to consider). Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 123. Downloading, Reading and Understanding Sales and Trends Data 3.1. Downloading Reports You may download the Sales reports from the respective Sales view. To download a report (tab delimited zipped text file), you must select a report period (day of week or week ended) and press the download button to the right of the period selection menu. For a complete listing of fields please see Appendix A, B and M. If you are using Mac OS X the reports will automatically open when downloaded. If you are using a Windows OS you will need to download an application (for example WinZip) to decompress the “.gz” file prior to use. You can then import the tab delimited text file to a database or spreadsheet application (Numbers, MS Excel) and analyze or manipulate your data as needed. Weekly reports cover Monday through Sunday and are available on Mondays. The daily reports represent the 24 hour period in the time zone of the respective storefront (territory). Please refer to Appendix D for the definition of Day and Week. We do not store or regenerate the data after the periods have expired (14 rolling days and 13 rolling weeks); you will need to download and store this data on a regular basis if you intend to use it in the future. Downloading Customer Opt-In Information If your apps have auto-renewable subscriptions, you can download contact information for customers who have elected to “opt-in” to personal information sharing. To download the report (tab delimited zipped text file), you must select a weekly report period and click Opt-In Report next to Download Report. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 13To open the encrypted .zip file that is downloaded, you need to use the Opt-In Passkey. To obtain the Opt-In Passkey, click the Opt-In Passkey button in the upper right of the screen. The passkey will be displayed in a lightbox. Copy and paste this value to use it to unpack the .zip file and access the Opt-In Report. You will need to use a decompression tool like Stuff-It Expander or Winzip to open the encrypted file once you have downloaded it. Downloading Newsstand Reports If you have one or more Newsstand apps available for sale, you can download Newsstand reports by clicking Newsstand Detailed. Newsstand reports are also available via auto-ingest. 3.2. Auto-Ingest Tool Apple provides access to a Java based tool to allow you to automate the download of your iTunes Connect Sales and Trends reports. To use the auto-ingest tool, configuration on your part will be required. This tool allows you to automate the retrieval of: •Daily Summary Reports •Weekly Summary Reports •Opt-In Reports •Newsstand Reports As new reports become available we will modify and redeliver the java package or new parameters to use to download new products (i.e. we will modify the script for new features). We will communicate both the anticipated date of the report release and the date that the tool will be able to retrieve reports. You may not alter or disseminate the auto-ingest tool for any reason. We reserve the right to revoke access for usage or distribution beyond its intended use. Auto-Ingest Instructions You must have Java installed on the machine where you are running the auto-ingest tool. The tool will work as expected with Java version 1.6 or above. Follow the steps below to setup the environment for auto-ingestion: Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 141. Download and save the file Autoingestion.class to the directory where you want the reports delivered. http://www.apple.com/itunesnews/docs/Autoingestion.class.zip 2. To run the Java class file, change the command line directory to the directory where the class file is stored. 3. Invoke the following from the command line: java Autoingestion All items contained within “< >” are variable and will require you to define them. Of the 7 parameters only the date is optional. If you do not put a date in the parameter we will provide you the latest available report (the other parameters are mandatory). You will need to delimit the parameters with a space. Parameters Definitions Variable Value Notes username Your user name The user name you use to log into iTunes Connect password Your password The password you use to log into iTunes Connect vendorid 8####### (your unique number) Vendor ID for the entity which you want to download the report report_type Sales or Newsstand This is the report type you want to download. date_type Daily or Weekly Selecting Weekly will provide you the Weekly version of the report. Selecting Daily will provide you the Daily version of the report. report_subtype Summary, Detailed or Opt-In This is the parameter for the Sales Reports. Note: Detailed can only be used for Newsstand reports. Date (optional) YYYYMMDD This is the date of report you are requesting. If the value for Date parameter is not provided, you will get the latest report available. Example: You access iTunes Connect with user name “john@xyz.com” and your password is “letmein” for company 80012345, and you want to download a sales - daily - summary report for February 4, 2010. You will need to invoke the job by running the following command from the directory where the class file is stored: java Autoingestion john@xyz.com letmein 80012345 Sales Daily Summary 20100204 Newsstand Reports via Auto-Ingest If you are using auto-ingest, you can create the reports using the following auto-ingest parameters: Daily java Autoingestion Newsstand Daily Detailed java Autoingestion N D D java Autoingestion 5 2 1 Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 15Weekly java Autoingestion Newsstand Weekly Detailed java Autoingestion N W D java Autoingestion 5 1 1 3.3. Reading Reports Report File Names The file names for downloaded reports follow a standard naming convention. Please refer to the matrix below for details. Report Data Report Type Reporting Range Naming Convention Description Sales Summary Daily S_D__ Example: S_D_80000000_20111104 The first letter identifies that the report provides Sales data at a Summary level. Second letter denotes that it is a Daily report. This is followed by the Vendor Account Number and the Date of reporting data ('YYYYMMDD'). Sales Summary Weekly S_W__ Example: S_W_80000000_20111104 The first letter identifies that the report provides Sales data at a Summary level. Second letter denotes that it is a Weekly report. This is followed by the Vendor Account Number and the Date of reporting data ('YYYYMMDD'). Opt_in Summary Weekly O_S_W__ Example: O_S_W_80000000_20111104 The first and second letters identify that the report provides customer Opt-in data at a Summary level. The third letter identifies that it is a Weekly report. This is followed by the Vendor Account Number and the Date of reporting data ('YYYYMMDD'). Newsstand Detailed Daily N_D_D__ Example: N_D_D_80000000_20111104 The first and second letters identify that the report provides customer Newsstand data at a Detailed level. The third letter identifies that it is a Daily report. This is followed by the Vendor Account Number and the Date of reporting data ('YYYYMMDD'). Newsstand Detailed Weekly N_D_W__ Example: N_D_W_80000000_20111104 The first and second letters identify that the report provides customer Newsstand data at a Detailed level. The third letter identifies that it is a Weekly report. This is followed by the Vendor Account Number and the Date of reporting data ('YYYYMMDD'). Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 16Report Field Names All reports have a header row which contains the field names of each column. The reports present transactions that can be tracked with your SKU and/or the Apple Identifier. For a complete listing of fields please see Appendix A, B and M. Key Field Mapping The following table and screenshots will help you understand which fields in the report were setup by you in iTunes Connect and where they are in the App Store: Reference Field Name In Report Field in iTunes Connect Field in App Store 1 Developer Company Name Displayed after genre 2 Title App Name Displayed at top of product page 3 SKU SKU Number Not displayed on App Store Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 17Apple Identifier The Apple Identifier is the unique product identifier assigned by Apple. It is always included in each row of your sales reports. We recommend you provide the Apple Identifier of your app whenever you contact us for support so that your request can be expedited. You can also access the Apple Identifier by using the links in the App Store: The menu will offer an option for “Copy Link”. The link will look like the link below. The string of numbers highlighted is the Apple Identifier of the app. http://itunes.apple.com/us/app/remote/id284417350?mt=85 3.4. Understanding Units The reports are designed to provide valuable information about the activity of your product on the App Store. This can result in many lines for a given product. For each product with a unique Apple Identifier and SKU, units are split by: ■ Storefront / Country Code (US, UK) ■ Sales vs. Refunds ■ Product Type ■ Price ■ Promo Code ■ App Version Here are some examples of how units are grouped and displayed in both Preview and downloaded reports. Example 1: If you have one product and you are selling the product in the US, you will see 1 row (1 for US sales) assuming there are no refunds, price changes and promo codes during the period. Example 2: If you are selling 30 products in the US, and 10 of the products have refunds, then the preview and the downloaded report will have 40 rows and you will see a row for sales and a row for refunds. Example 3: If you are selling 30 products in the US, and 5 products have a price change in the middle of the week, then your full report and your previews will have 35 rows and you will see 2 lines per app with a price change. Example 4: If 10 new customers purchase your app and 10 existing customers update to the latest version of your app in the US, then your preview and downloaded report will have 1 row for purchases and 1 row for updates. Example 5: If 10 customers purchase version 1.1 of your product in the US, and those customers then update to version 1.2 of the same product, then your preview and downloaded report will have 2 rows, 1 row for purchases of version 1.1 and 1 row for updates to version 1.2. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 184. Contact Us If you have any questions or have difficulties viewing or downloading your sales and trends information, please do not hesitate to contact us. The easiest way to ensure your request is routed correctly is to use the Contact Us module. A Contact Us link is available on all pages as part of the footer. You can also find the Contact Us module on the iTunes Connect Homepage: The link will take you to a page that allows you to select the topic you need help with and will ask a series of questions and provide answers where available. For Sales and Trends inquiries, select the “Sales and Trends” topic. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 19Appendix A - Sales Report Field Definitions The definitions apply to Daily and Weekly Reports. Report Field Report Data Type Values Notes Provider CHAR(5) - APPLE Up to 5 Characters The service provider in your reports will typically be Apple Provider Country CHAR(2) - US Up to 2 Characters The service provider country code will typically be US SKU VARCHAR(100) Up to 100 Characters This is a product identifier provided by you when the app is set up ∇ Developer VARCHAR(4000) Up to 4000 Characters You provided this on initial setup . ∇ Title VARCHAR(600) Up to 600 Characters You provided this when setting up the app ∇ Version VARCHAR(100) Up to 100 Characters You provided this when setting up the app ∇ Product Type Identifier VARCHAR(20) Up to 20 Characters This field defines the type of transaction (e.g. initial download, update, etc) – See Appendix E Units DECIMAL(18,2) Up to 18 Characters This is the aggregated number of units Developer Proceeds (per item) DECIMAL(18,2) Up to 18 Characters Your proceeds for each item delivered Begin Date Date Date in MM/DD/YYYY Date of beginning of report End Date Date Date in MM/DD/YYYY Date of end of report Customer Currency CHAR(3) Up to 3 Characters Three character ISO code indicates the currency the customer paid in - See Appendix H Country Code CHAR(2) Up to 2 Characters Two character ISO country code indicates what App Store the purchase occurred in – See Appendix F Currency of Proceeds CHAR(3) Up to 3 Characters Currency your proceeds are earned in – See Appendix H Apple Identifier DECIMAL(18,0) Up to 18 Characters This is Apple's unique identifier. If you have questions about a product, it is best to include this identifier. Customer Price DECIMAL(18,2) Up to 18 Characters Retail Price displayed on the App Store and charged to the customer. Promo Code VARCHAR(10) Up to 10 Characters If the transaction was part of a promotion this field will contain a value. For all non-promotional items this field will be blank - See Appendix G Parent Identifier VARCHAR(100) Up to 100 Characters For In-App Purchases this will be populated with the SKU from the originating app. Subscription VARCHAR(10) Up to 10 Characters This field defines whether an autorenewable subscription purchase is a new purchase or a renewal. See Appendix I. Period VARCHAR(30) Up to 30 Characters This field defines the duration of an auto-renewable subscription purchase. See Appendix I. ∇ Apple generally does not modify this field. What you provided when setting up your app is passed through on the report. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 20Appendix B - Opt-In Report Field Definitions The definitions apply to Weekly Opt-In Reports. Report Field Report Data Type Values Notes First Name VARCHAR(100) Up to 100 Characters First Name of Customer Last Name VARCHAR(100) Up to 100 Characters Last Name of Customer Email Address VARCHAR(100) Up to 100 Characters Email Address of Customer Postal Code VARCHAR(50) Up to 50 Characters Postal Code of Customer Apple Identifier DECIMAL(18,0) Up to 18 Characters This is Apple's unique identifier. If you have questions about a product, it is best to include this identifier. Report Start Date DATE Date in MM/DD/YYYY Date of beginning of report Report End Date DATE Date in MM/DD/YYYY Date of end of report Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 21Appendix C - Apple Fiscal Calendar Monthly Financial Reports are based on Apple’s reporting calendar shown below. Months represent either four (4) or five (5) weeks (the first month of each quarter has an extra week) and the weeks run from Sunday through Saturday. All months start on Sunday and end on Saturday. Monthly reports are also distributed on iTunes Connect and available based on the contractually agreed timeframes. Sales and Trends reports are generated using different time frames and represent near immediate feedback of transactions. Finance Reports are based on customer invoicing and financial processing. Reconciliation between the reports is not recommended due to the timing and reporting differences. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 22Appendix D - Definition of Day and Week What is a Day? 12:00:00 AM to 11:59:59 PM in the time zone used for that territory (see table below). What is a Week? Monday 12:00:00 AM to Sunday 11:59:59 PM What time is the report date based on? Territory Time Zone US, Canada, Latin America Pacific Time (PT) Europe, Middle East, Africa, Asia Pacific Central Europe Time (CET) Japan Japan Standard Time (JST) Australia, New Zealand Western Standard Time (WST) When are reports available? Reports are generated after the close of business in the final time zone (which is PT). As such, all reports are generally available by 8:00 AM PT for the prior day or week. Earlier access to reporting for other time zones (where the close of business is earlier) is not available. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 23Appendix E – Product Type Identifiers Product Type Identifier Type Description 1 Free or Paid Apps iPhone and iPod Touch, iOS 7 Updates iPhone and iPod Touch, iOS IA1 In Apps Purchase, iOS IA9 In Apps Subscription, iOS IAY In Apps Auto-Renewable Subscription, iOS IAC In Apps Free Subscription, iOS 1F Free or Paid Apps Universal, iOS 7F Updates Universal, iOS 1T Free or Paid Apps iPad, iOS 7T Updates iPad, iOS F1 Free or Paid Apps Mac OS F7 Updates Mac OS FI1 In Apps Mac OS 1E Paid Apps Custom iPhone and iPod Touch, iOS 1EP Paid Apps Custom iPad, iOS 1EU Paid Apps Custom Universal, iOS Dashboard Types Type Product Type Identifier Description Free Apps 1, 1F, 1T, F1 Where price = ‘0’ Paid Apps 1, 1F, 1T, F1 Where price > ‘0’ In Apps IA1, IA9, IAY. FI1 Updates 7, 7F, 7T, F7 Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 24Appendix F – Country Codes Country Code Country Name Country Code Country Name Country Code Country Name AE United Arab Emirates GD Grenada NG Nigeria AG Antigua and Barbuda GH Ghana NI Nicaragua AI Anguilla GR Greece NL Netherlands AM Armenia GT Guatemala NO Norway AO Angola GY Guyana NZ New Zealand AR Argentina HK Hong Kong OM Oman AT Austria HN Honduras PA Panama AU Australia HR Croatia PE Peru AZ Azerbaijan HU Hungary PH Philippines BB Barbados ID Indonesia PK Pakistan BE Belgium IE Ireland PL Poland BG Bulgaria IL Israel PT Portugal BH Bahrain IN India PY Paraguay BM Bermuda IS Iceland QA Qatar BN Brunei IT Italy RO Romania BO Bolivia JM Jamaica RU Russia BR Brazil JO Jordan SA Saudi Arabia BS Bahamas JP Japan SE Sweden BW Botswana KE Kenya SG Singapore BY Belarus KN St. Kitts and Nevis SI Slovenia BZ Belize KR Republic Of Korea SK Slovakia CA Canada KW Kuwait SN Senegal CH Switzerland KY Cayman Islands SR Suriname CL Chile KZ Kazakstan SV El Salvador CN China LB Lebanon TC Turks and Caicos CO Colombia LC St. Lucia TH Thailand CR Costa Rica LK Sri Lanka TN Tunisia CY Cyprus LT Lithuania TR Turkey CZ Czech Republic LU Luxembourg TT Trinidad and Tobago DE Germany LV Latvia TW Taiwan DK Denmark MD Republic Of Moldova TZ Tanzania DM Dominica MG Madagascar UG Uganda DO Dominican Republic MK Macedonia US United States DZ Algeria ML Mali UY Uruguay EC Ecuador MO Macau UZ Uzbekistan EE Estonia MS Montserrat VC St. Vincent and The Grenadines EG Egypt MT Malta VE Venezuela ES Spain MU Mauritius VG British Virgin Islands FI Finland MX Mexico VN Vietnam FR France MY Malaysia YE Yemen GB United Kingdom NE Niger ZA South Africa Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 25Appendix G – Promotional Codes The promo code field contains different values depending on the type of promotion. The following definitions describe the possible values that may appear in the field other than null (null means the item is a standard transaction). Only one value is possible per line in the report: Promo Code Description CR - RW Promotional codes where the proceeds have been waived (The customer price will be 0 and the proceeds will be 0). These transactions are the result of iTunes Connect Developer Code redemptions. GP Purchase of a Gift by the giver GR Redemption of a Gift by the receiver EDU Education Store transaction Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 26Appendix H – Currency Codes Currency Code Currency Country AUD Australian Dollar CAD Canadian Dollar CHF Swiss Franc DKK Danish Kroner EUR European Euro GBP British Pound JPY Japanese Yen MXN Mexican Peso NOK Norwegian Kroner NZD New Zealand Dollar SEK Swedish Kronor USD United States Dollar Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 27Appendix I - Subscription and Period Field Values The Subscription field indicates whether the auto-renewable subscription purchase is a new purchase or a renewal. Subscription Field Value New Renewal The Period field indicates the duration of the auto-renewable subscription purchase or renewal. Period Field Value 7 Days 1 Month 2 Months 3 Months 6 Months 1 Year Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 28Appendix J - FAQs What does each column represent in my reports? Please refer to Appendix A and B. I am seeing differences between Financial Reports and Sales and Trends reports, why? The daily and weekly reports are based on customer interaction (clicks) and are coming from real-time systems while the monthly reports are based on settled financial transactions and are coming from our financial systems. There are intentional differences in processing and time-frames between those two types of reports. For example, the weekly reports are from Monday to Sunday, while the Financial Reports are based on the Apple Fiscal Calendar and always end on Saturday. Reconciliation between the reports is not recommended due to the timing and reporting differences. Do weekly reports reconcile with the daily reports? Yes. Both daily and weekly reports are coming from the same system and they are based on customer interaction (clicks). They will reconcile. I see a high volume of sales for a short period of time (could be up to a week) and the sales drop down, what does this mean? It is very common that some items get a high amount of sales for a short period of time and the numbers get back to normal. It is generally due to a particular promotion related with a web blog or a sales campaign that includes an item that might be associated with iTunes or the content. There is also a very common case where a content's sales drop to zero.  In this case, this might be an indication of content being unavailable in iTunes due to number of reasons. I don’t see any sales for a particular item, why? This can be an indication of an item not being available in the store for different reasons. Check the product availability in iTunes Connect and ensure that the latest contracts are agreed to and in place. How can I identify refunds? Sales and Trends reports expose refunds to allow you to monitor refund rate by product. You will see a negative unit value for refund transactions. Why there are refunds on my reports? We will provide a refund if the customer experience was in our opinion unsatisfactory (generally quality issues). One thing you can monitor on your reports is the rate of refunds and the content that is refunded since it is an indication of quality issues with your content. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 29Appendix K - Sample Sales Report The following is a sample Sales report to help you interpret its contents. Price fields are dependent on the storefront 1 from which the customer purchases the app, and the price of the app at the time of purchase 2 . (For complete field definitions see Appendix A) Reading the Report The example above is the most likely scenario you will see: ■ SKU – “SKU1” is the SKU attached to this app by the developer. ■ Developer – “Vendor” is the name that the app is sold under on the store ■ Title – “App-1” is the name of the app ■ Product Type Identifier – “1” denotes the type of transaction (initial download) ■ Units – “352” is the number of units sold for a given day/week ■ Developer Proceeds – “3.65” is proceeds, net of commission, you will receive for each sale of the app ■ Customer Currency – “GBP” (Great Britain Pounds) is the currency in which the customer purchased the app ■ Currency of Proceeds – “GBP” (Great Britain Pounds) is the currency in which your proceeds were earned for the app ■ Customer Price – “5.99” is the price paid by the customer for the app Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 30 1 As new territories are added, storefronts will further differentiate records 2 If you change your price during the reporting period, the report will show multiple price points for the same countryAdditional Reporting Scenarios We have provided some additional scenarios and sample extract to help you further understand your reports. In your reports the Product Type Identifier denotes the type of transaction (See Appendix E for a list of all types). The Product Type Identifier must be taken into account in all of the following scenarios. Scenario 1 (Product Type Identifier=1; Units=16; Developer Proceeds=4.86) This is similar to the first line; the Developer Proceeds value will always be greater than zero for all paid apps and zero for free apps. Scenario 2 (Product Type Identifier=7; Units=1; Developer Proceeds=0) Certain line items will have 0 in the Developer Proceeds field. Even if you only have paid apps on the store, the Developer Proceeds will be 0 for all updates (Product Type Identifier = 7). Scenario 3 (Product Type Identifier=1; Units=-1; Developer Proceeds=7; Customer Price=-9.99) You may see negative units when a customer returns a product. All returns will have a Product Type Identifier of 1 and both Units and Customer Price will be a negative value. Refer to Appendix J for additional information on returns. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 31Appendix L – Other Uses Below you will see some sample ideas that the data can be used for on a daily basis. 1. Business Health Monitoring By tracking volume of sales per unit or revenue, the health of your business can be tracked. Sudden drop in sales may indicate issues such as top seller being not available any more. 2. Content Quality Issues By tracking the refunds, you can identify and replace the asset that is being refunded to the customer if the refunds are specific to one or more items. Typical ratio of refunds to overall sales shall not exceed 0.10%. 3. Pricing Issues When organizations get larger, it is always challenging to have fast/efficient communication between the operational teams that are providing the metadata to iTunes and the Management, Marketing, Finance and Business Development team. Tracking pricing will indicate any disconnect between different groups and will provide opportunity to fix issues sooner and minimize the impact. 4. Price Elasticity We believe that careful management of price can increase your sales. By using the reports you can monitor percent change in sales in correlation with a percent change in customer price. If applied correctly this type of analysis will help you set the best price for your product to maximize your revenue. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 32Appendix M - Newsstand Report Field Definitions The definitions apply to Newsstand reports. Report Field Report Data Type Values Notes Provider CHAR(5) - APPLE Up to 5 Characters The service provider in your reports will typically be Apple Provider Country CHAR(2) - US Up to 2 Characters The service provider country code will typically be US SKU VARCHAR(100) Up to 100 Characters This is a product identifier provided by you when the app is set up Developer VARCHAR(4000) Up to 4000 Characters You provided this on initial setup. Title VARCHAR(600) Up to 600 Characters You provided this when setting up the app Version VARCHAR(100) Up to 100 Characters You provided this when setting up the app Product Type Identifier VARCHAR(20) Up to 20 Characters This field defines the type of transaction (e.g. initial download, update, etc) – See Appendix E Units DECIMAL(18,2) Up to 18 Characters This is the aggregated number of units Developer Proceeds (per item) DECIMAL(18,2) Up to 18 Characters Your proceeds for each item delivered Customer Currency CHAR(3) Up to 3 Characters Three character ISO code indicates the currency the customer paid in - See Appendix H Country Code CHAR(2) Up to 2 Characters Two character ISO country code indicates what App Store the purchase occurred in – See Appendix F Currency of Proceeds CHAR(3) Up to 3 Characters Currency your proceeds are earned in – See Appendix H Apple Identifier DECIMAL(18,0) Up to 18 Characters This is Apple's unique identifier. If you have questions about a product, it is best to include this identifier. Customer Price DECIMAL(18,2) Up to 18 Characters Retail Price displayed on the App Store and charged to the customer. Promo Code VARCHAR(10) Up to 10 Characters If the transaction was part of a promotion this field will contain a value. For all non-promotional items this field will be blank - See Appendix G Parent Identifier VARCHAR(100) Up to 100 Characters For In-App Purchases this will be populated with the SKU from the originating app. Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 33Subscription VARCHAR(10) Up to 10 Characters This field defines whether an auto-renewable subscription purchase is a new purchase or a renewal. See Appendix I. Period VARCHAR(30) Up to 30 Characters This field defines the duration of an auto-renewable subscription purchase. See Appendix I. Download Date (PST) TIMESTAMP(0) Date in MM/DD/YYYY Download Date Customer Identifier DECIMAL(18,0) Up to 18 Characters Customer Identification Report Date (Local) DATE Date in MM/DD/YYYY Report Date Sales/Return CHAR(1) Up to 1 character S or R; R is always a refund, R is not a reversal Apple Inc. iTunes Connect Sales and Trends Guide, App Store Version 5.3  iTunes Connect Sales and Trends Guide, App Store (Version 5.3, August 2012) 34 Secure Coding GuideContents Introduction to Secure Coding Guide 7 At a Glance 7 Hackers, Crackers, and Attackers 7 No Platform Is Immune 8 How to Use This Document 9 See Also 10 Types of Security Vulnerabilities 11 Buffer Overflows 11 Unvalidated Input 12 Race Conditions 13 Interprocess Communication 13 Insecure File Operations 13 Access Control Problems 14 Secure Storage and Encryption 15 Social Engineering 16 Avoiding Buffer Overflows and Underflows 17 Stack Overflows 18 Heap Overflows 20 String Handling 22 Calculating Buffer Sizes 25 Avoiding Integer Overflows and Underflows 27 Detecting Buffer Overflows 28 Avoiding Buffer Underflows 29 Validating Input and Interprocess Communication 33 Risks of Unvalidated Input 33 Causing a Buffer Overflow 33 Format String Attacks 34 URLs and File Handling 36 Code Insertion 37 Social Engineering 37 Modifications to Archived Data 38 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 2Fuzzing 39 Interprocess Communication and Networking 40 Race Conditions and Secure File Operations 43 Avoiding Race Conditions 43 Time of Check Versus Time of Use 44 Signal Handling 46 Securing Signal Handlers 46 Securing File Operations 47 Check Result Codes 47 Watch Out for Hard Links 48 Watch Out for Symbolic Links 49 Case-Insensitive File Systems Can Thwart Your Security Model 49 Create Temporary Files Correctly 50 Files in Publicly Writable Directories Are Dangerous 51 Other Tips 57 Elevating Privileges Safely 59 Circumstances Requiring Elevated Privileges 59 The Hostile Environment and the Principle of Least Privilege 60 Launching a New Process 61 Executing Command-Line Arguments 61 Inheriting File Descriptors 61 Abusing Environment Variables 62 Modifying Process Limits 62 File Operation Interference 63 Avoiding Elevated Privileges 63 Running with Elevated Privileges 63 Calls to Change Privilege Level 64 Avoiding Forking Off a Privileged Process 65 authopen 65 launchd 66 Limitations and Risks of Other Mechanisms 67 Factoring Applications 69 Example: Preauthorizing 69 Helper Tool Cautions 71 Authorization and Trust Policies 72 Security in a KEXT 72 Designing Secure User Interfaces 73 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 3 ContentsUse Secure Defaults 73 Meet Users’ Expectations for Security 74 Secure All Interfaces 75 Place Files in Secure Locations 75 Make Security Choices Clear 76 Fight Social Engineering Attacks 78 Use Security APIs When Possible 79 Designing Secure Helpers and Daemons 81 Avoid Puppeteering 81 Use Whitelists 82 Use Abstract Identifiers and Structures 82 Use the Smell Test 83 Treat Both App and Helper as Hostile 83 Run Daemons as Unique Users 84 Start Other Processes Safely 84 Security Development Checklists 86 Use of Privilege 86 Data, Configuration, and Temporary Files 88 Network Port Use 89 Audit Logs 91 Client-Server Authentication 93 Integer and Buffer Overflows 97 Cryptographic Function Use 97 Installation and Loading 98 Use of External Tools and Libraries 100 Kernel Security 101 Third-Party Software Security Guidelines 103 Respect Users’ Privacy 103 Provide Upgrade Information 103 Store Information in Appropriate Places 103 Avoid Requiring Elevated Privileges 104 Implement Secure Development Practices 104 Test for Security 104 Helpful Resources 105 Document Revision History 106 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 4 ContentsGlossary 107 Index 110 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 5 ContentsFigures, Tables, and Listings Avoiding Buffer Overflows and Underflows 17 Figure 2-1 Schematic view of the stack 19 Figure 2-2 Stack after malicious buffer overflow 20 Figure 2-3 Heap overflow 21 Figure 2-4 C string handling functions and buffer overflows 22 Figure 2-5 Buffer overflow crash log 29 Table 2-1 String functions to use and avoid 23 Table 2-2 Avoid hard-coded buffer sizes 25 Table 2-3 Avoid unsafe concatenation 26 Race Conditions and Secure File Operations 43 Table 4-1 C file functions to avoid and to use 55 Elevating Privileges Safely 59 Listing 5-1 Non-privileged process 70 Listing 5-2 Privileged process 71 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 6Secure coding is the practice of writing programs that are resistant to attack by malicious or mischievous people or programs. Secure coding helps protect a user’s data from theft or corruption. In addition, an insecure program can provide accessfor an attacker to take control of a server or a user’s computer, resulting in anything from a denial of service to a single user to the compromise of secrets, loss of service, or damage to the systems of thousands of users. Secure coding is important for all software; if you write any code that runs on Macintosh computers or on iOS devices, from scripts for your own use to commercial software applications, you should be familiar with the information in this document. At a Glance Every program is a potential target. Attackers will try to find security vulnerabilities in your applications or servers. They will then try to use these vulnerabilities to steal secrets, corrupt programs and data, and gain control of computer systems and networks. Your customers’ property and your reputation are at stake. Security is notsomething that can be added to software as an afterthought; just as a shed made out of cardboard cannot be made secure by adding a padlock to the door, an insecure tool or application may require extensive redesign to secure it. You must identify the nature of the threats to your software and incorporate secure coding practices throughout the planning and development of your product. This chapter explains the types of threatsthat yoursoftware may face. Other chaptersin this document describe specific types of vulnerabilities and give guidance on how to avoid them. Hackers, Crackers, and Attackers Contrary to the usage by most news media, within the computer industry the term hacker refers to an expert programmer—one who enjoyslearning about the intricacies of code or an operating system. In general, hackers are not malicious. When most hackers find security vulnerabilities in code, they inform the company or organization that’s responsible for the code so that they can fix the problem. Some hackers—especially if they feel their warnings are being ignored—publish the vulnerabilities or even devise and publish exploits (code that takes advantage of the vulnerability). 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 7 Introduction to Secure Coding GuideThe malicious individuals who break into programs and systems in order to do damage or to steal something are referred to as crackers, attackers, or black hats. Most attackers are not highly skilled, but take advantage of published exploit code and known techniques to do their damage. People (usually, though not always, young men) who use published code (scripts) to attack software and computer systems are sometimes called script kiddies. Attackers may be motivated by a desire to steal money, identities, and othersecretsfor personal gain; corporate secrets for their employer’s or their own use; or state secrets for use by hostile governments or terrorist organizations. Some crackers break into applications or operating systems just to show that they can do it; nevertheless, they can cause considerable damage. Because attacks can be automated and replicated, any weakness, no matter how slight, can be exploited. The large number of insiders who are attacking systems is of importance to security design because, whereas malicious hackers and script kiddies are most likely to rely on remote access to computers to do their dirty work, insiders might have physical access to the computer being attacked. Your software must be resistant to both attacks over a network and attacks by people sitting at the computer keyboard—you cannot rely on firewalls and server passwords to protect you. No Platform Is Immune So far, OS X has not fallen prey to any major, automated attack like the MyDoom virus. There are several reasons for this. One is that OS X is based on open source software such as BSD; many hackers have searched this software over the years looking for security vulnerabilities, so that not many vulnerabilities remain. Another is that the OS X turns off all routable networking services by default. Also, the email and internet clients used most commonly on OS X do not have privileged access to the operating system and are less vulnerable to attack than those used on some other common operating systems. Finally, Apple actively reviewsthe operating system and applications for security vulnerabilities, and issues downloadable security updates frequently. iOS is based on OS X and shares many of its security characteristics. In addition, it is inherently more secure than even OS X because each application is restricted in the files and system resources it can access. Beginning in version 10.7, Mac apps can opt into similar protection. That’s the good news. The bad news is that applications and operating systems are constantly under attack. Every day, black hat hackers discover new vulnerabilities and publish exploit code. Criminals and script kiddies then use that exploit code to attack vulnerable systems. Also, security researchers have found many vulnerabilities on a variety of systems that, if exploited, could have resulted in loss of data, allowing an attacker to steal secrets, or enabling an attacker to run code on someone else’s computer. Introduction to Secure Coding Guide At a Glance 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 8A large-scale, widespread attack is not needed to cause monetary and other damages; a single break-in is sufficient if the system broken into contains valuable information. Although major attacks of viruses or worms get a lot of attention from the media, the destruction or compromising of data on a single computer is what matters to the average user. For your users’sake, you should take every security vulnerability seriously and work to correct known problems quickly. If every Macintosh and iOS developer followsthe advice in this document and other books on electronic security, and if the owner of each Macintosh takes common-sense precautions such as using strong passwords and encrypting sensitive data, then OS X and iOS will maintain their reputationsfor being safe, reliable operating systems, and your company’s products will benefit from being associated with OS X or iOS. How to Use This Document This document assumes that you have already read Security Overview. The document begins with “Types of Security Vulnerabilities” (page 11), which gives a brief introduction to the nature of each of the types of security vulnerability commonly found in software. This chapter provides background information that you should understand before reading the other chapters in the document. If you’re not sure what a race condition is, for example, or why it poses a security risk, this chapter is the place to start. The remaining chapters in the document discuss specific types of security vulnerabilities in some detail. These chapters can be read in any order, or as suggested by the software development checklist in “Security Development Checklists” (page 86). ● “Avoiding Buffer Overflows And Underflows” (page 17) describes the various types of buffer overflows and explains how to avoid them. ● “Validating Input And Interprocess Communication” (page 33) discusses why and how you must validate every type of input your program receives from untrusted sources. ● “Race Conditions and Secure File Operations” (page 43) explains how race conditions occur, discusses ways to avoid them, and describes insecure and secure file operations. ● “Elevating Privileges Safely” (page 59) describes how to avoid running code with elevated privileges and what to do if you can’t avoid it entirely. ● “Designing Secure User Interfaces” (page 73) discusses how the user interface of a program can enhance or compromise security and gives some guidance on how to write a security-enhancing UI. ● “Designing Secure Helpers And Daemons” (page 81) describes how to design helper applications in ways that are conducive to privilege separation. Introduction to Secure Coding Guide How to Use This Document 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 9In addition, the appendix “Security Development Checklists” (page 86) provides a convenient list of tasks that you should perform before shipping an application, and the appendix “Third-Party Software Security Guidelines” (page 103) provides a list of guidelines for third-party applications bundled with OS X. See Also This document concentrates on security vulnerabilities and programming practices of special interest to developers using OS X or iOS. For discussions of secure programming of interest to all programmers, see the following books and documents: ● See Viega and McGraw, Building Secure Software , Addison Wesley, 2002; for a general discussion of secure programming, especially as it relates to C programming and writing scripts. ● SeeWheeler, Secure Programming for Linux andUnixHOWTO, available athttp://www.dwheeler.com/secureprograms/; for discussions ofseveral types ofsecurity vulnerabilities and programming tipsfor UNIX-based operating systems, most of which apply to OS X. ● See Cranor and Garfinkel, Security and Usability: Designing Secure Systems that People Can Use , O’Reilly, 2005; for information on writing user interfaces that enhance security. For documentation of security-related application programming interfaces (APIs) for OS X (and iOS, where noted), see the following Apple documents: ● For an introduction to some security concepts and to learn about the security features available in OS X, see Security Overview. ● For information on secure networking, see Cryptographic Services Guide , Secure Transport Reference and CFNetwork Programming Guide . ● For information on OS X authorization and authentication APIs, see Authentication, Authorization, and Permissions Guide , Authorization Services Programming Guide , Authorization Services C Reference , and Security Foundation Framework Reference . ● If you are using digital certificates for authentication, see Cryptographic Services Guide , Certificate, Key, and Trust Services Reference (iOS version available) and Certificate, Key, and Trust Services Programming Guide . ● For secure storage of passwords and other secrets, see Cryptographic Services Guide , Keychain Services Reference (iOS version available) and Keychain Services Programming Guide . For information about security in web application design, visit http://www.owasp.org/. Introduction to Secure Coding Guide See Also 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 10Most software security vulnerabilities fall into one of a small set of categories: ● buffer overflows ● unvalidated input ● race conditions ● access-control problems ● weaknesses in authentication, authorization, or cryptographic practices This chapter describes the nature of each type of vulnerability. Buffer Overflows A buffer overflow occurs when an application attempts to write data past the end (or, occasionally, past the beginning) of a buffer. Buffer overflows can cause applications to crash, can compromise data, and can provide an attack vector for further privilege escalation to compromise the system on which the application is running. Books on software security invariably mention buffer overflows as a major source of vulnerabilities. Exact numbers are hard to come by, but as an indication, approximately 20% of the published exploits reported by the United States Computer Emergency Readiness Team (US-CERT) for 2004 involved buffer overflows. Any application or system software that takes input from the user, from a file, or from the network has to store that input, at least temporarily. Except in special cases, most application memory isstored in one of two places: ● stack—A part of an application’s addressspace thatstores data that isspecific to a single call to a particular function, method, block, or other equivalent construct. ● heap—General purpose storage for an application. Data stored in the heap remains available as long as the application is running (or until the application explicitly tells the operating system that it no longer needs that data). Class instances, data allocated with malloc, core foundation objects, and most other application data resides on the heap. (Note, however, that the local variables that actually point to the data are stored in the stack.) 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 11 Types of Security VulnerabilitiesBuffer overflow attacks generally occur by compromising either the stack, the heap, or both. For more information, read “Avoiding Buffer Overflows And Underflows” (page 17) Unvalidated Input As a general rule, you should check all input received by your program to make sure that the data isreasonable. For example, a graphics file can reasonably contain an image that is 200 by 300 pixels, but cannot reasonably contain an image that is 200 by -1 pixels. Nothing prevents a file from claiming to contain such an image, however (apart from convention and common sense). A naive program attempting to read such a file would attempt to allocate a buffer of an incorrect size, leading to the potential for a heap overflow attack or other problem. For this reason, you must check your input data carefully. This process is commonly known as input validation or sanity checking. Any input received by your program from an untrusted source is a potential target for attack. (In this context, an ordinary user is an untrusted source.) Examples of input from an untrusted source include (but are not restricted to): ● text input fields ● commands passed through a URL used to launch the program ● audio, video, or graphics files provided by users or other processes and read by the program ● command line input ● any data read from an untrusted server over a network ● any untrusted data read from a trusted server over a network (user-submitted HTML or photos on a bulletin board, for example) Hackers look at every source of input to the program and attempt to pass in malformed data of every type they can imagine. If the program crashes or otherwise misbehaves, the hacker then triesto find a way to exploit the problem. Unvalidated-input exploits have been used to take control of operating systems, steal data, corrupt users’ disks, and more. One such exploit was even used to “jail break” iPhones. “Validating Input And Interprocess Communication” (page 33) describes common types of input-validation vulnerabilities and what to do about them. Types of Security Vulnerabilities Unvalidated Input 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 12Race Conditions A race condition exists when changes to the order of two or more events can cause a change in behavior. If the correct order of execution is required for the proper functioning of the program, this is a bug. If an attacker can take advantage of the situation to insert malicious code, change a filename, or otherwise interfere with the normal operation of the program, the race condition is a security vulnerability. Attackers can sometimes take advantage of small time gaps in the processing of code to interfere with the sequence of operations, which they then exploit. For more information about race conditions and how to prevent them, read “Race Conditions and Secure File Operations” (page 43). Interprocess Communication Separate processes—either within a single program or in two different programs—sometimes have to share information. Common methods include using shared memory or using some messaging protocol, such as Sockets, provided by the operating system. These messaging protocols used for interprocess communication are often vulnerable to attack; thus, when writing an application, you must always assume that the process at the other end of your communication channel could be hostile. For more information on how to perform secure interprocess communication, read “Validating Input And Interprocess Communication” (page 33). Insecure File Operations In addition to time-of-check–time-of-use problems, many other file operations are insecure. Programmers often make assumptions about the ownership, location, or attributes of a file that might not be true. For example, you might assume that you can always write to a file created by your program. However, if an attacker can change the permissions or flags on that file after you create it, and if you fail to check the result code after a write operation, you will not detect the fact that the file has been tampered with. Examples of insecure file operations include: ● writing to or reading from a file in a location writable by another user ● failing to make the right checks for file type, device ID, links, and other settings before using a file ● failing to check the result code after a file operation ● assuming that if a file has a local pathname, it has to be a local file These and other insecure file operations are discussed in more detail in “Securing File Operations” (page 47). Types of Security Vulnerabilities Race Conditions 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 13Access Control Problems Access control is the process of controlling who is allowed to do what. This ranges from controlling physical access to a computer—keeping your servers in a locked room, for example—to specifying who has access to a resource (a file, for example) and what they are allowed to do with that resource (such as read only). Some access control mechanisms are enforced by the operating system,some by the individual application orserver, some by a service (such as a networking protocol) in use. Many security vulnerabilities are created by the careless or improper use of access controls, or by the failure to use them at all. Much of the discussion of security vulnerabilities in the software security literature is in terms of privileges, and many exploits involve an attacker somehow gaining more privileges than they should have. Privileges, also called permissions, are access rights granted by the operating system, controlling who is allowed to read and write files, directories, and attributes of files and directories (such as the permissions for a file), who can execute a program, and who can perform other restricted operations such as accessing hardware devices and making changes to the network configuration. File permissions and access control in OS X are discussed in File System Programming Guide . Of particular interest to attackers is the gaining of root privileges, which refers to having the unrestricted permission to perform any operation on the system. An application running with root privileges can access everything and change anything. Many security vulnerabilities involve programming errors that allow an attacker to obtain root privileges. Some such exploits involve taking advantage of buffer overflows or race conditions, which in some special circumstances allow an attacker to escalate their privileges. Others involve having access to system files that should be restricted or finding a weakness in a program—such as an application installer—that is already running with root privileges. For this reason, it’s important to always run programs with as few privileges as possible. Similarly, when it is necessary to run a program with elevated privileges, you should do so for as short a time as possible. Much access control is enforced by applications, which can require a user to authenticate before granting authorization to perform an operation. Authentication can involve requesting a user name and password, the use of a smart card, a biometric scan, or some other method. If an application calls the OS X Authorization Services application interface to authenticate a user, it can automatically take advantage of whichever authentication method is available on the user’s system. Writing your own authentication code is a less secure alternative, as it might afford an attacker the opportunity to take advantage of bugs in your code to bypass your authentication mechanism, or it might offer a less secure authentication method than the standard one used on the system. Authorization and authentication are described further in Security Overview. Digital certificates are commonly used—especially over the Internet and with email—to authenticate users and servers, to encrypt communications, and to digitally sign data to ensure that it has not been corrupted and was truly created by the entity that the user believes to have created it. Incorrect or careless use of digital certificates can lead to security vulnerabilities. For example, a server administration program shipped with a Types of Security Vulnerabilities Access Control Problems 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 14standard self-signed certificate, with the intention that the system administrator would replace it with a unique certificate. However, many system administrators failed to take this step, with the result that an attacker could decrypt communication with the server. [CVE-2004-0927] It’s worth noting that nearly all access controls can be overcome by an attacker who has physical access to a machine and plenty of time. For example, no matter what you set a file’s permissions to, the operating system cannot prevent someone from bypassing the operating system and reading the data directly off the disk. Only restricting access to the machine itself and the use of robust encryption techniques can protect data from being read or corrupted under all circumstances. The use of access controls in your program is discussed in more detail in “Elevating Privileges Safely” (page 59). Secure Storage and Encryption Encryption can be used to protect a user’s secrets from others, either during data transmission or when the data is stored. (The problem of how to protect a vendor’s data from being copied or used without permission is not addressed here.) OS X provides a variety of encryption-based security options, such as ● FileVault ● the ability to create encrypted disk images ● keychain ● certificate-based digital signatures ● encryption of email ● SSL/TLS secure network communication ● Kerberos authentication The list of security options in iOS includes ● passcode to prevent unauthorized use of the device ● data encryption ● the ability to add a digital signature to a block of data ● keychain ● SSL/TLS secure network communication Types of Security Vulnerabilities Secure Storage and Encryption 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 15Each service has appropriate uses, and each haslimitations. For example, FileVault, which encryptsthe contents of a user’s root volume (in OS X v10.7 and later) or home directory (in earlier versions), is a very important security feature for shared computers or computers to which attackers might gain physical access, such as laptops. However, it is not very helpful for computers that are physically secure but that might be attacked over the network while in use, because in that case the home directory is in an unencrypted state and the threat is from insecure networks or shared files. Also, FileVault is only as secure as the password chosen by the user—if the userselects an easily guessed password, or writesit down in an easily found location, the encryption is useless. It is a serious mistake to try to create your own encryption method or to implement a published encryption algorithm yourself unless you are already an expert in the field. It is extremely difficult to write secure, robust encryption code that generates unbreakable ciphertext, and it is almost always a security vulnerability to try. For OS X, if you need cryptographic services beyond those provided by the OS X user interface and high-level programming interfaces, you can use the open-source CSSM Cryptographic Services Manager. See the documentation provided with the Open Source security code, which you can download at http://developer.apple.com/darwin/projects/security/. For iOS, the development APIs should provide all the services you need. For more information about OS X and iOS security features, read Authentication, Authorization, and Permissions Guide . Social Engineering Often the weakest link in the chain ofsecurity features protecting a user’s data and software isthe user himself. As developers eliminate buffer overflows, race conditions, and othersecurity vulnerabilities, attackersincreasingly concentrate on fooling users into executing malicious code or handing over passwords, credit-card numbers, and other private information. Tricking a user into giving up secrets or into giving access to a computer to an attacker is known as social engineering. For example, in February of 2005, a large firm that maintains credit information, Social Security numbers, and other personal information on virtually all U.S. citizens revealed that they had divulged information on at least 150,000 people to scam artists who had posed as legitimate businessmen. According to Gartner (www.gartner.com), phishing attacks cost U.S. banks and credit card companies about $1.2 billion in 2003, and this number is increasing. They estimate that between May 2004 and May 2005, approximately 1.2 million computer users in the United States suffered losses caused by phishing. Software developers can counter such attacks in two ways: through educating their users, and through clear and well-designed user interfaces that give users the information they need to make informed decisions. For more advice on how to design a user interface that enhances security, see “Designing Secure User Interfaces” (page 73). Types of Security Vulnerabilities Social Engineering 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 16Buffer overflows, both on the stack and on the heap, are a major source of security vulnerabilities in C, Objective-C, and C++ code. This chapter discusses coding practicesthat will avoid buffer overflow and underflow problems, lists tools you can use to detect buffer overflows, and provides samples illustrating safe code. Every time your program solicits input (whether from a user, from a file, over a network, or by some other means), there is a potential to receive inappropriate data. For example, the input data might be longer than what you have reserved room for in memory. When the input data islonger than will fit in the reserved space, if you do not truncate it, that data will overwrite other data in memory. When this happens, it is called a buffer overflow. If the memory overwritten contained data essential to the operation of the program, this overflow causes a bug that, being intermittent, might be very hard to find. If the overwritten data includes the address of other code to be executed and the user has done this deliberately, the user can point to malicious code that your program will then execute. Similarly, when the input data is or appearsto be shorter than the reserved space (due to erroneous assumptions, incorrect length values, or copying raw data as a C string), this is called a buffer underflow. This can cause any number of problems from incorrect behavior to leaking data that is currently on the stack or heap. Although most programming languages check input againststorage to prevent buffer overflows and underflows, C, Objective-C, and C++ do not. Because many programs link to C libraries, vulnerabilities in standard libraries can cause vulnerabilities even in programs written in “safe” languages. For thisreason, even if you are confident that your code isfree of buffer overflow problems, you should limit exposure by running with the least privileges possible. See “Elevating Privileges Safely” (page 59) for more information on this topic. Keep in mind that obvious forms of input, such as strings entered through dialog boxes, are not the only potential source of malicious input. For example: 1. Buffer overflowsin one operating system’s help system could be caused by maliciously prepared embedded images. 2. A commonly-used media player failed to validate a specific type of audio files, allowing an attacker to execute arbitrary code by causing a buffer overflow with a carefully crafted audio file. [ 1 CVE-2006-1591 2 CVE-2006-1370] There are two basic categories of overflow: stack overflows and heap overflows. These are described in more detail in the sections that follow. 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 17 Avoiding Buffer Overflows and UnderflowsStack Overflows In most operating systems, each application has a stack (and multithreaded applications have one stack per thread). This stack contains storage for locally scoped data. The stack is divided up into units called stack frames. Each stack frame contains all data specific to a particular call to a particular function. This data typically includes the function’s parameters, the complete set of local variables within that function, and linkage information—that is, the address of the function call itself, where execution continues when the function returns). Depending on compiler flags, it may also contain the address of the top of the next stack frame. The exact content and order of data on the stack depends on the operating system and CPU architecture. Each time a function is called, a new stack frame is added to the top of the stack. Each time a function returns, the top stack frame is removed. At any given point in execution, an application can only directly access the data in the topmost stack frame. (Pointers can get around this, but it is generally a bad idea to do so.) This design makes recursion possible because each nested call to a function gets its own copy of local variables and parameters. Avoiding Buffer Overflows and Underflows Stack Overflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 18Figure 2-1 illustrates the organization of the stack. Note that this figure is schematic only; the actual content and order of data put on the stack depends on the architecture of the CPU being used. See OS X ABI Function Call Guide for descriptions of the function-calling conventions used in all the architectures supported by OS X. Figure 2-1 Schematic view of the stack Function A Function B Function C Function A data Parameters for call to function B Function A return address Function B data Parameters for call to function C Function B return address Function C data Space for parameters for next subroutine call Function C return address In general, an application should check all input data to make sure it is appropriate for the purpose intended (for example, making sure that a filename is of legal length and contains no illegal characters). Unfortunately, in many cases, programmers do not bother, assuming that the user will not do anything unreasonable. This becomes a serious problem when the application stores that data into a fixed-size buffer. If the user is malicious (or opens a file that contains data created by someone who is malicious), he or she might provide data that is longer than the size of the buffer. Because the function reserves only a limited amount of space on the stack for this data, the data overwrites other data on the stack. As shown in Figure 2-2, a clever attacker can use this technique to overwrite the return address used by the function, substituting the address of his own code. Then, when function C completes execution, rather than returning to function B, it jumps to the attacker’s code. Avoiding Buffer Overflows and Underflows Stack Overflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 19Because the application executes the attacker’s code, the attacker’s code inherits the user’s permissions. If the user islogged on as an administrator (the default configuration in OS X), the attacker can take complete control of the computer, reading data from the disk, sending emails, and so forth. (In iOS, applications are much more restricted in their privileges and are unlikely to be able to take complete control of the device.) Figure 2-2 Stack after malicious buffer overflow Function A Function B Function C Function A data Parameters for call to function B Function A return address Function B data Parameters for call to function C Function B return address Function C data Space for parameters for next subroutine call Function C return address Parameter overflow Address of attackerʼs code In addition to attacks on the linkage information, an attacker can also alter program operation by modifying local data and function parameters on the stack. For example, instead of connecting to the desired host, the attacker could modify a data structure so that your application connects to a different (malicious) host. Heap Overflows As mentioned previously, the heap is used for all dynamically allocated memory in your application. When you use malloc, new, or equivalent functions to allocate a block of memory or instantiate an object, the memory that backs those pointers is allocated on the heap. Avoiding Buffer Overflows and Underflows Heap Overflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 20Because the heap is used to store data but is not used to store the return address value of functions and methods, and because the data on the heap changes in a nonobvious way as a program runs, it is less obvious how an attacker can exploit a buffer overflow on the heap. To some extent, it is this nonobviousness that makes heap overflows an attractive target—programmers are less likely to worry about them and defend against them than they are for stack overflows. Figure 2-1 illustrates a heap overflow overwriting a pointer. Figure 2-3 Heap overflow Buffer overflow Data Buffer Data Pointer Data Data Data Data In general, exploiting a buffer overflow on the heap is more challenging than exploiting an overflow on the stack. However, many successful exploits have involved heap overflows. There are two ways in which heap overflows are exploited: by modifying data and by modifying objects. An attacker can exploit a buffer overflow on the heap by overwriting critical data, either to cause the program to crash or to change a value that can be exploited later (overwriting a stored user ID to gain additional access, for example). Modifying this data is known as a non-control-data attack. Much of the data on the heap is generated internally by the program rather than copied from user input;such data can be in relatively consistent locations in memory, depending on how and when the application allocates it. Avoiding Buffer Overflows and Underflows Heap Overflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 21An attacker can also exploit a buffer overflow on the heap by overwriting pointers. In many languages such as C++ and Objective-C, objects allocated on the heap contain tables of function and data pointers. By exploiting a buffer overflow to change such pointers, an attacker can potentially substitute different data or even replace the instance methods in a class object. Exploiting a buffer overflow on the heap might be a complex, arcane problem to solve, but crackers thrive on just such challenges. For example: 1. A heap overflow in code for decoding a bitmap image allowed remote attackersto execute arbitrary code. 2. A heap overflow vulnerability in a networking server allowed an attacker to execute arbitrary code by sending an HTTP POST request with a negative “Content-Length” header. [ 1 CVE-2006-0006 2 CVE-2005-3655] String Handling Strings are a common form of input. Because many string-handling functions have no built-in checks for string length, strings are frequently the source of exploitable buffer overflows. Figure 2-4 illustrates the different ways three string copy functions handle the same over-length string. Figure 2-4 C string handling functions and buffer overflows L A R G E R \0 L A R G E L A R G \0 Char destination[5]; char *source = “LARGER”; strcpy(destination, source); strncpy(destination, source, sizeof(destination)); strlcpy(destination, source, sizeof(destination)); As you can see, the strcpy function merely writes the entire string into memory, overwriting whatever came after it. The strncpy function truncates the string to the correct length, but without the terminating null character. When this string is read, then, all of the bytes in memory following it, up to the next null character, might be read as part of the string. Although this function can be used safely, it is a frequent source of programmer Avoiding Buffer Overflows and Underflows String Handling 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 22mistakes, and thus is regarded as moderately unsafe. To safely use strncpy, you must either explicitly zero the last byte of the buffer after calling strncpy or pre-zero the buffer and then pass in a maximum length that is one byte smaller than the buffer size. Only the strlcpy function is fully safe, truncating the string to one byte smaller than the buffer size and adding the terminating null character. Table 2-1 summarizes the common C string-handling routines to avoid and which to use instead. Table 2-1 String functions to use and avoid Don’t use these functions Use these instead strcat strlcat strcpy strlcpy strncat strlcat strncpy strlcpy snprintf or asprintf (See note) sprintf vsnprintf or vasprintf (See note) vsprintf fgets (See note) gets Avoiding Buffer Overflows and Underflows String Handling 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 23Security Note for snprintf and vsnprintf: The functions snprintf, vsnprintf, and variants are dangerous if used incorrectly. Although they do behave functionally like strlcat and similar in that they limit the bytes written to n-1, the length returned by these functions is the length that would have been printed if n were infinite . For this reason, you must not use this return value to determine where to null-terminate the string or to determine how many bytes to copy from the string at a later time. Security Note for fgets: Although the fgets function provides the ability to read a limited amount of data, you must be careful when using it. Like the other functions in the “safer” column, fgets alwaysterminatesthe string. However, unlike the other functionsin that column, it takes a maximum number of bytes to read, not a buffer size. In practical terms, this means that you must always pass a size value that is one fewer than the size of the buffer to leave room for the null termination. If you do not, the fgets function will dutifully terminate the string past the end of your buffer, potentially overwriting whatever byte of data follows it. You can also avoid string handling buffer overflows by using higher-level interfaces. ● If you are using C++, the ANSI C++ string class avoids buffer overflows, though it doesn’t handle non-ASCII encodings (such as UTF-8). ● If you are writing code in Objective-C, use the NSString class. Note that an NSString object has to be converted to a C string in order to be passed to a C routine, such as a POSIX function. ● If you are writing code in C, you can use the Core Foundation representation of a string, referred to as a CFString, and the string-manipulation functions in the CFString API. The Core Foundation CFString is “toll-free bridged” with its Cocoa Foundation counterpart, NSString. This means that the Core Foundation type is interchangeable in function or method calls with its equivalent Foundation object. Therefore, in a method where you see an NSString * parameter, you can pass in a value of type CFStringRef, and in a function where you see a CFStringRef parameter, you can pass in an NSString instance. This also applies to concrete subclasses of NSString. See CFString Reference , Foundation Framework Reference , and Carbon-Cocoa IntegrationGuide formore details on using these representations of strings and on converting between CFString objects and NSString objects. Avoiding Buffer Overflows and Underflows String Handling 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 24Calculating Buffer Sizes When working with fixed-length buffers, you should always use sizeof to calculate the size of a buffer, and then make sure you don’t put more data into the buffer than it can hold. Even if you originally assigned a static size to the buffer, either you or someone else maintaining your code in the future might change the buffer size but fail to change every case where the buffer is written to. The first example, Table 2-2, shows two ways of allocating a character buffer 1024 bytes in length, checking the length of an input string, and copying it to the buffer. Table 2-2 Avoid hard-coded buffer sizes Instead of this: Do this: #define BUF_SIZE 1024 ... char buf[BUF_SIZE]; ... if (size < BUF_SIZE) { ... } char buf[1024]; ... if (size <= 1023) { ... } char buf[1024]; ... if (size < sizeof(buf)) { ... } char buf[1024]; ... if (size < 1024) { ... } The two snippets on the left side are safe as long as the original declaration of the buffer size is never changed. However, if the buffer size gets changed in a later version of the program without changing the test, then a buffer overflow will result. The two snippets on the right side show safer versions of this code. In the first version, the buffer size is set using a constant that is set elsewhere, and the check uses the same constant. In the second version, the buffer is set to 1024 bytes, but the check calculates the actual size of the buffer. In either of these snippets, changing the original size of the buffer does not invalidate the check. TTable 2-3, shows a function that adds an .ext suffix to a filename. Avoiding Buffer Overflows and Underflows Calculating Buffer Sizes 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 25Table 2-3 Avoid unsafe concatenation Instead of this: Do this: { char file[MAX_PATH]; ... addsfx(file, sizeof(file)); ... } static *suffix = ".ext"; size_t addsfx(char *buf, uint size) { size_t ret = strlcat(buf, suffix, size); if (ret >= size) { fprintf(stderr, "Buffer too small....\n"); } return ret; } { char file[MAX_PATH]; ... addsfx(file); ... } static *suffix = ".ext"; char *addsfx(char *buf) { return strcat(buf, suffix); } Both versions use the maximum path length for a file as the buffer size. The unsafe version in the left column assumes that the filename does not exceed this limit, and appends the suffix without checking the length of the string. The safer version in the right column uses the strlcat function, which truncates the string if it exceeds the size of the buffer. Important: You should always use an unsigned variable (such as size_t) when calculating sizes of buffers and of data going into buffers. Because negative numbers are stored as large positive numbers, if you use signed variables, an attacker might be able to cause a miscalculation in the size of the buffer or data by writing a large number to your program. See “Avoiding Integer Overflows And Underflows” (page 27) for more information on potential problems with integer arithmetic. For a further discussion of this issue and a list of more functions that can cause problems, see Wheeler, Secure Programming for Linux and Unix HOWTO (http://www.dwheeler.com/secure-programs/). Avoiding Buffer Overflows and Underflows Calculating Buffer Sizes 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 26Avoiding Integer Overflows and Underflows If the size of a buffer is calculated using data supplied by the user, there is the potential for a malicious user to enter a number that is too large for the integer data type, which can cause program crashes and other problems. In two’s-complement arithmetic (used forsigned integer arithmetic by most modern CPUs), a negative number is represented by inverting all the bits of the binary number and adding 1. A 1 in the most-significant bit indicates a negative number. Thus, for 4-byte signed integers, 0x7fffffff = 2147483647, but 0x80000000 = -2147483648 Therefore, int 2147483647 + 1 = - 2147483648 If a malicious user specifies a negative number where your program is expecting only unsigned numbers, your program might interpret it as a very large number. Depending on what that number is used for, your program might attempt to allocate a buffer of thatsize, causing the memory allocation to fail or causing a heap overflow if the allocation succeeds. In an early version of a popular web browser, for example, storing objects into a JavaScript array allocated with negative size could overwrite memory. [CVE-2004-0361] In other cases, if you use signed values to calculate buffer sizes and test to make sure the data is not too large for the buffer, a sufficiently large block of data will appear to have a negative size, and will therefore pass the size test while overflowing the buffer. Depending on how the buffer size is calculated, specifying a negative number could result in a buffer too small for its intended use. For example, if your program wants a minimum buffer size of 1024 bytes and adds to that a number specified by the user, an attacker might cause you to allocate a buffer smaller than the minimum size by specifying a large positive number, as follows: 1024 + 4294966784 = 512 0x400 + 0xFFFFFE00 = 0x200 Also, any bits that overflow past the length of an integer variable (whether signed or unsigned) are dropped. For example, when stored in a 32-bit integer, 2**32 == 0. Because it is not illegal to have a buffer with a size of 0, and because malloc(0) returns a pointer to a small block, your code might run without errors if an attacker specifies a value that causes your buffer size calculation to be some multiple of 2**32. In other words, for any values of n and m where (n * m) mod 2**32 == 0, allocating a buffer of size n*m results in a valid pointer to a buffer of some very small (and architecture-dependent) size. In that case, a buffer overflow is assured. Avoiding Buffer Overflows and Underflows Avoiding Integer Overflows and Underflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 27To avoid such problems, when performing buffer math, you should always include checks to make sure no integer overflow occurred. A common mistake when performing these tests is to check the result of the multiplication or other operation: size_t bytes = n * m; if (bytes < n || bytes < m) { /* BAD BAD BAD */ ... /* allocate "bytes" space */ } Unfortunately, the C language specification allows the compiler to optimize out such tests [CWE-733, CERT VU#162289]. Thus, the only correct way to test for integer overflow is to divide the maximum allowable result by the multiplier and comparing the result to the multiplicand or vice-versa. If the result is smaller than the multiplicand, the product of those two values would cause an integer overflow. For example: size_t bytes = n * m; if (n > 0 && m > 0 && SIZE_MAX/n >= m) { ... /* allocate "bytes" space */ } Detecting Buffer Overflows To test for buffer overflows, you should attempt to enter more data than is asked for wherever your program accepts input. Also, if your program accepts data in a standard format, such as graphics or audio data, you should attempt to pass it malformed data. This process is known as fuzzing. If there are buffer overflows in your program, it will eventually crash. (Unfortunately, it might not crash until some time later, when it attempts to use the data that was overwritten.) The crash log might provide some clues that the cause of the crash was a buffer overflow. If, for example, you enter a string containing the Avoiding Buffer Overflows and Underflows Detecting Buffer Overflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 28uppercase letter “A” several times in a row, you might find a block of data in the crash log that repeats the number 41, the ASCII code for “A” (see Figure 2-2). If the program is trying to jump to a location that is actually an ASCII string, that’s a sure sign that a buffer overflow was responsible for the crash. Figure 2-5 Buffer overflow crash log Exception: EXC_BAD_ACCESS (0x0001) Codes: KERN_INVALID_ADDRESS (0x0001) at 0x41414140 Thread 0 Crashed: Thread 0 crashed with PPC Thread State 64: srr0: 0x0000000041414140 srr1: 0x000000004200f030 vrsave: 0x0000000000000000 cr: 0x48004242 xer: 0x0000000020000007 1r: 0x0000000041414141 ctr: 0x000000009077401c r0: 0x0000000041414141 r1: 0x00000000bfffe660 r2: 0x0000000000000000 r3: 000000000000000001 r4: 0x0000000000000041 r5: 0x00000000bfffdd50 r6: 0x0000000000000052 r7: 0x00000000bfffe638 r8: 0x0000000090774028 r9: 0x00000000bfffddd8 r10: 0x00000000bfffe380 r11: 0x0000000024004248 r12: 0x000000009077401c r13: 0x00000000a365c7c0 r14: 0x0000000000000100 r15: 0x0000000000000000 r16: 0x00000000a364c75c r17: 0x00000000a365c75c r18: 0x00000000a365c75c r19: 0x00000000a366c75c r20: 0x0000000000000000 r21: 0x0000000000000000 r22: 0x00000000a365c75c r23: 0x000000000034f5b0 r24: 0x00000000a3662aa4 r25: 0x000000000054c840 r26: 0x00000000a3662aa4 r27: 0x0000000000002f44 r28: 0x000000000034c840 r29: 0x0000000041414141 r30: 0x0000000041414141 r31: 0x0000000041414141 If there are any buffer overflows in your program, you should always assume that they are exploitable and fix them. It is much harder to prove that a buffer overflow is not exploitable than to just fix the bug. Also note that, although you can test for buffer overflows, you cannot test for the absence of buffer overflows; it is necessary, therefore, to carefully check every input and every buffer size calculation in your code. For more information on fuzzing, see “Fuzzing” (page 39) in “Validating Input And Interprocess Communication” (page 33). Avoiding Buffer Underflows Fundamentally, buffer underflows occur when two parts of your code disagree about the size of a buffer or the data in that buffer. For example, a fixed-length C string variable might have room for 256 bytes, but might contain a string that is only 12 bytes long. Buffer underflow conditions are not always dangerous; they become dangerous when correct operation depends upon both parts of your code treating the data in the same way. This often occurs when you read the buffer to copy it to another block of memory, to send it across a network connection, and so on. There are two broad classes of buffer underflow vulnerabilities: short writes, and short reads. Avoiding Buffer Overflows and Underflows Avoiding Buffer Underflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 29A short write vulnerability occurs when a short write to a buffer fails to fill the buffer completely. When this happens, some of the data that was previously in the buffer is still present after the write. If the application later performs an operation on the entire buffer (writing it to disk or sending it over the network, for example), that existing data comes along for the ride. The data could be random garbage data, but if the data happens to be interesting, you have an information leak. Further, when such an underflow occurs, if the values in those locations affect program flow, the underflow can potentially cause incorrect behavior up to and including allowing you to skip past an authentication or authorization step by leaving the existing authorization data on the stack from a previous call by another user, application, or other entity. Short write example (systemcall): For example, consider a UNIX system call that requires a command data structure, and includes an authorization token in that data structure. Assume that there are multiple versions of the data structure, with different lengths, so the system call takes both the structure and the length. Assume that the authorization token is fairly far down in the structure. Suppose a malicious application passesin a command structure, and passes a size that encompasses the data up to, but not including, the authorization token. The kernel’s system call handler calls copyin, which copies a certain number of bytes from the application into the data structure in the kernel’s address space. If the kernel does not zero-fill that data structure, and if the kernel does not check to see if the size is valid, there is a narrow possibility that the stack might still contain the previous caller’s authorization token at the same address in kernel memory. Thus, the attacker is able to perform an operation that should have been disallowed. A short read vulnerability occurs when a read from a buffer fails to read the complete contents of a buffer. If the program then makes decisions based on that short read, any number of erroneous behaviors can result. This usually occurs when a C string function is used to read from a buffer that does not actually contain a valid C string. A C string is defined as a string containing a series of bytes that ends with a null terminator. By definition, it cannot contain any null bytes prior to the end of the string. As a result, C-string-based functions, such as strlen, strlcpy, and strdup, copy a string until the first null terminator, and have no knowledge of the size of the original source buffer. By contrast, strings in other formats (a CFStringRef object, a Pascal string, or a CFDataRef blob) have an explicit length and can contain null bytes at arbitrary locations in the data. If you convert such a string into a C string and then evaluate that C string, you get incorrect behavior because the resulting C string effectively ends at the first null byte. Avoiding Buffer Overflows and Underflows Avoiding Buffer Underflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 30Short read example (SSL verification): An example of a short read vulnerability occurred in many SSL stacks a few years ago. By applying for an SSL cert for a carefully crafted subdomain of a domain that you own, you could effectively create a certificate that was valid for arbitrary domains. Consider a subdomain in the form targetdomain.tld[null_byte].yourdomain.tld. Because the certificate signing request contains a Pascalstring, assuming that the certificate authority interprets it correctly, the certificate authority would contact the owner of yourdomain.tld and would ask for permission to deliver the certificate. Because you own the domain, you would agree to it. You would then have a certificate that is valid for the rather odd-looking subdomain in question. When checking the certificate for validity, however, many SSL stacksincorrectly converted that Pascal string into a C string without any validity checks. When this happened, the resulting C string contained only the targetdomain.tld portion. The SSL stack then compared that truncated version with the domain the user requested, and interpreted the certificate as being valid for the targeted domain. In some cases, it was even possible to construct wildcard certificatesthat were valid for every possible domain in such browsers (*.com[null].yourdomain.tld would match every .com address, for example). If you obey the following rules, you should be able to avoid most underflow attacks: ● Zero-fill all buffers before use. A buffer that contains only zeros cannot contain stale sensitive information. ● Always check return values and fail appropriately. ● If a call to an allocation or initialization function fails (AuthorizationCopyRights, for example), do not evaluate the resulting data, as it could be stale. ● Use the value returned from read system calls and other similar calls to determine how much data was actually read. Then either: ● Use that result to determine how much data is present instead of using a predefined constant or ● fail if the function did not return the expected amount of data. ● Display an error and fail if a write call, printf call, or other output call returns without writing all of the data, particularly if you might later read that data back. ● When working with data structures that contain length information, always verify that the data is the size you expected. ● Avoid converting non-C strings (CFStringRef objects, NSString objects, Pascal strings, and so on) into C strings if possible. Instead, work with the strings in their original format. If this is not possible, always perform length checks on the resulting C string or check for null bytes in the source data. Avoiding Buffer Overflows and Underflows Avoiding Buffer Underflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 31● Avoid mixing buffer operations and string operations. If this is not possible, always perform length checks on the resulting C string or check for null bytes in the source data. ● Save files in a fashion that prevents malicious tampering or truncation. (See “Race Conditions and Secure File Operations” (page 43) for more information.) ● Avoid integer overflows and underflows. (See “Calculating Buffer Sizes” (page 25) for details.) Avoiding Buffer Overflows and Underflows Avoiding Buffer Underflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 32A major, and growing, source of security vulnerabilities is the failure of programs to validate all input from outside the program—that is, data provided by users, from files, over the network, or by other processes. This chapter describes some of the ways in which unvalidated input can be exploited, and some coding techniques to practice and to avoid. Risks of Unvalidated Input Any time your program accepts input from an uncontrolled source, there is a potential for a user to pass in data that does not conform to your expectations. If you don’t validate the input, it might cause problems ranging from program crashes to allowing an attacker to execute his own code. There are a number of ways an attacker can take advantage of unvalidated input, including: ● Buffer overflows ● Format string vulnerabilities ● URL commands ● Code insertion ● Social engineering Many Apple security updates have been to fix input vulnerabilities, including a couple of vulnerabilities that hackers used to “jailbreak” iPhones. Input vulnerabilities are common and are often easily exploitable, but are also usually easily remedied. Causing a Buffer Overflow If your application takesinput from a user or other untrusted source, itshould never copy data into a fixed-length buffer without checking the length and truncating it if necessary. Otherwise, an attacker can use the input field to cause a buffer overflow. See “Avoiding Buffer Overflows And Underflows” (page 17) to learn more. 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 33 Validating Input and Interprocess CommunicationFormat String Attacks If you are taking input from a user or other untrusted source and displaying it, you need to be careful that your display routines do not processformatstringsreceived from the untrusted source. For example, in the following code the syslog standard C library function is used to write a received HTTP request to the system log. Because the syslog function processes format strings, it will process any format strings included in the input packet: /* receiving http packet */ int size = recv(fd, pktBuf, sizeof(pktBuf), 0); if (size) { syslog(LOG_INFO, "Received new HTTP request!"); syslog(LOG_INFO, pktBuf); } Many formatstrings can cause problemsfor applications. For example,suppose an attacker passesthe following string in the input packet: "AAAA%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%n" This string retrieves eight items from the stack. Assuming that the format string itself is stored on the stack, depending on the structure of the stack, this might effectively move the stack pointer back to the beginning of the format string. Then the %n token would cause the print function to take the number of bytes written so far and write that value to the memory address stored in the next parameter, which happens to be the format string. Thus, assuming a 32-bit architecture, the AAAA in the format string itself would be treated as the pointer value 0x41414141, and the value at that address would be overwritten with the number 76. Doing this will usually cause a crash the next time the system has to access that memory location, but by using a string carefully crafted for a specific device and operating system, the attacker can write arbitrary data to any location. See the manual page for printf(3) for a full description of format string syntax. To prevent format string attacks, make sure that no input data is ever passed as part of a format string. To fix this, just include your own format string in each such function call. For example, the call printf(buffer) may be subject to attack, but the call printf("%s", buffer) is not. In the second case, all characters in the buffer parameter—including percent signs (%)—are printed out rather than being interpreted as formatting tokens. Validating Input and Interprocess Communication Risks of Unvalidated Input 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 34This situation can be made more complicated when a string is accidentally formatted more than once. In the following example, the informativeTextWithFormat argument of the NSAlert method alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat: calls the NSString method stringWithFormat:GetLocalizedString rather than simply formatting the message string itself. As a result, the string is formatted twice, and the data from the imported certificate is used as part of the format string for the NSAlert method: alert = [NSAlert alertWithMessageText:"Certificate Import Succeeded" defaultButton:"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:[NSString stringWithFormat: @"The imported certificate \"%@\" has been selected in the certificate pop-up.", [selectedCert identifier]]]; [alert setAlertStyle:NSInformationalAlertStyle]; [alert runModal]; Instead, the string should be formatted only once, as follows: [alert informativeTextWithFormat:@"The imported certificate \"%@\" has been selected in the certificate pop-up.", [selectedCert identifier]]; The following commonly-used functions and methods are subject to format-string attacks: ● Standard C ● printf and other functions listed on the printf(3) manual page ● scanf and other functions listed on the scanf(3) manual page ● syslog and vsyslog ● Carbon ● CFStringCreateWithFormat ● CFStringCreateWithFormatAndArguments ● CFStringAppendFormat ● AEBuildDesc Validating Input and Interprocess Communication Risks of Unvalidated Input 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 35● AEBuildParameters ● AEBuildAppleEvent ● Cocoa ● [NSString stringWithFormat:] and other NSString methods that take formatted strings as arguments ● [NSString initWithFormat:] and other NSStringmethodsthattake formatstrings as arguments ● [NSMutableString appendFormat:] ● [NSAlert alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat:] ● [NSPredicate predicateWithFormat:] and [NSPredicate predicateWithFormat:arguments:] ● [NSException raise:format:] and [NSException raise:format:arguments:] ● NSRunAlertPanel and other Application Kit functions that create or return panels or sheets URLs and File Handling If your application has registered a URL scheme, you have to be careful about how you process commands sent to your application through the URL string. Whether you make the commands public or not, hackers will try sending commandsto your application. If, for example, you provide a link or linksto launch your application from your web site, hackers will look to see what commands you’re sending and will try every variation on those commands they can think of. You must be prepared to handle, or to filter out, any commands that can be sent to your application, not only those commands that you would like to receive. For example, if you accept a command that causes your application to send credentials back to your web server, don’t make the function handler general enough so that an attacker can substitute the URL of their own web server. Here are some examples of the sorts of commands that you should not accept: ● myapp://cmd/run?program=/path/to/program/to/run ● myapp://cmd/set_preference?use_ssl=false ● myapp://cmd/sendfile?to=evil@attacker.com&file=some/data/file ● myapp://cmd/delete?data_to_delete=my_document_ive_been_working_on ● myapp://cmd/login_to?server_to_send_credentials=some.malicious.webserver.com In general, don’t accept commands that include arbitrary URLs or complete pathnames. Validating Input and Interprocess Communication Risks of Unvalidated Input 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 36If you accept text or other data in a URL command that you subsequently include in a function or method call, you could be subject to a format string attack (see “Format String Attacks” (page 34)) or a buffer overflow attack (see “Causing a Buffer Overflow” (page 33)). If you accept pathnames, be careful to guard againststrings that might redirect a call to another directory; for example: myapp://use_template?template=/../../../../../../../../some/other/file Code Insertion Unvalidated URL commands and textstringssometimes allow an attacker to insert code into a program, which the program then executes. For example, if your application processes HTML and Javascript when displaying text, and displays strings received through a URL command, an attacker could send a command something like this: myapp://cmd/adduser='>"> Similarly, HTML and other scripting languages can be inserted through URLs, text fields, and other data inputs, such as command lines and even graphics or audio files. You should either not execute scripts in data from an untrusted source, or you should validate all such data to make sure it conforms to your expectations for input. Never assume that the data you receive is well formed and valid; hackers and malicious users will try every sort of malformed data they can think of to see what effect it has on your program. Social Engineering Social engineering—essentially tricking the user—can be used with unvalidated input vulnerabilities to turn a minor annoyance into a major problem. For example, if your program accepts a URL command to delete a file, but first displays a dialog requesting permission from the user, you might be able to send a long-enough string to scroll the name of the file to be deleted past the end of the dialog. You could trick the user into thinking he was deleting something innocuous, such as unneeded cached data. For example: myapp://cmd/delete?file=cached data that is slowing down your system.,realfile The user then might see a dialog with the text “Are you sure you want to delete cached data that is slowing down your system.” The name of the real file, in this scenario, is out of sight below the bottom of the dialog window. When the user clicks the “OK” button, however, the user’s real data is deleted. Other examples of social engineering attacks include tricking a user into clicking on a link in a malicious web site or following a malicious URL. For more information about social engineering, read “Designing Secure User Interfaces” (page 73). Validating Input and Interprocess Communication Risks of Unvalidated Input 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 37Modifications to Archived Data Archiving data, also known as object graph serialization, refers to converting a collection of interconnected objects into an architecture-independent stream of bytes that preserves the identity of and the relationships between the objects and values. Archives are used for writing data to a file, transmitting data between processes or across a network, or performing other types of data storage or exchange. For example, in Cocoa, you can use a coder object to create and read from an archive, where a coder object is an instance of a concrete subclass of the abstract class NSCoder. Object archives are problematic from a security perspective for several reasons. First, an object archive expands into an object graph that can contain arbitrary instances of arbitrary classes. If an attacker substitutes an instance of a different class than you were expecting, you could get unexpected behavior. Second, because an application must know the type of data stored in an archive in order to unarchive it, developers typically assume that the values being decoded are the same size and data type as the values they originally coded. However, when the data is stored in an insecure manner before being unarchived, this is not a safe assumption. If the archived data is not stored securely, it is possible for an attacker to modify the data before the application unarchives it. If your initWithCoder: method does not carefully validate all the data it’s decoding to make sure it is well formed and does not exceed the memory space reserved for it, then by carefully crafting a corrupted archive, an attacker can cause a buffer overflow or trigger another vulnerability and possibly seize control of the system. Third, some objects return a different object during unarchiving (see the NSKeyedUnarchiverDelegate method unarchiver:didDecodeObject:) or when they receive the message awakeAfterUsingCoder:. NSImage is one example of such a class—it may register itself for a name when unarchived, potentially taking the place of an image the application uses. An attacker might be able to take advantage of this to insert a maliciously corrupt image file into an application. It’s worth keeping in mind that, even if you write completely safe code, there mightstill be security vulnerabilities in libraries called by your code. Specifically, the initWithCoder: methods of the superclasses of your classes are also involved in unarchiving. To be completely safe, you should avoid using archived data as a serialization format for data that could potentially be stored or transmitted in an insecure fashion or that could potentially come from an untrusted source. Note that nib files are archives, and these cautions apply equally to them. A nib file loaded from a signed application bundle should be trustable, but a nib file stored in an insecure location is not. Validating Input and Interprocess Communication Risks of Unvalidated Input 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 38See “Risks of Unvalidated Input” (page 33) for more information on the risks of reading unvalidated input, “Securing File Operations” (page 47) for techniques you can use to keep your archive files secure, and the other sections in this chapter for details on validating input. Fuzzing Fuzzing, or fuzz testing, is the technique of randomly or selectively altering otherwise valid data and passing it to a program to see what happens. If the program crashes or otherwise misbehaves, that’s an indication of a potential vulnerability that might be exploitable. Fuzzing is a favorite tool of hackers who are looking for buffer overflows and the other types of vulnerabilities discussed in this chapter. Because it will be employed by hackers against your program, you should use it first, so you can close any vulnerabilities before they do. Although you can never prove that your program is completely free of vulnerabilities, you can at least get rid of any that are easy to find this way. In this case, the developer’s job is much easier than that of the hacker. Whereas the hacker has to not only find input fields that might be vulnerable, but also must determine the exact nature of the vulnerability and then craft an attack that exploits it, you need only find the vulnerability, then look at the source code to determine how to close it. You don’t need to prove that the problem is exploitable—just assume that someone will find a way to exploit it, and fix it before they get an opportunity to try. Fuzzing is best done with scripts orshort programsthat randomly vary the input passed to a program. Depending on the type of input you’re testing—text field, URL, data file, and so forth—you can try HTML, javascript, extra long strings, normally illegal characters, and so forth. If the program crashes or does anything unexpected, you need to examine the source code that handles that input to see what the problem is, and fix it. For example, if your program asksfor a filename, you should attempt to enter a string longer than the maximum legal filename. Or, if there is a field that specifies the size of a block of data, attempt to use a data block larger than the one you indicated in the size field. The most interesting valuesto try when fuzzing are usually boundary values. For example, if a variable contains a signed integer, try passing the maximum and minimum values allowed for a signed integer of thatsize, along with 0, 1, and -1. If a data field should contain a string with no fewer than 1 byte and no more than 42 bytes, try zero bytes, 1 byte, 42 bytes, and 43 bytes. And so on. In addition to boundary values, you should also try values that are way, way outside the expected values. For example, if your application is expecting an image that is up to 2,000 pixels by 3,000 pixels, you might modify the size fields to claim that the image is 65,535 pixels by 65,535 pixels. Using large values can uncover integer overflow bugs (and in some cases, NULL pointer handling bugs when a memory allocation fails). See “Avoiding Integer Overflows And Underflows” (page 27) in “Avoiding Buffer Overflows And Underflows” (page 17) for more information about integer overflows. Validating Input and Interprocess Communication Fuzzing 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 39Inserting additional bytes of data into the middle or end of a file can also be a useful fuzzing technique in some cases. For example, if a file’s header indicates that it contains 1024 bytes after the header, the fuzzer could add a 1025th byte. The fuzzer could add an additional row or column of data in an image file. And so on. Interprocess Communication and Networking When communicating with another process, the most important thing to remember isthat you cannot generally verify that the other process has not been compromised. Thus, you must treat it as untrusted and potentially hostile. All interprocess communication is potentially vulnerable to attacks if you do not properly validate input, avoid race conditions, and perform any other tests that are appropriate when working with data from a potentially hostile source. Above and beyond these risks, however,some forms of interprocess communication have specific risksinherent to the communication mechanism. This section describes some of those risks. Mach messaging When working with Mach messaging, it is important to never give the Mach task port of your process to any other. If you do, you are effectively allowing that process to arbitrarily modify the address space your process, which makes it trivial to compromise your process. Instead, you should create a Mach port specifically for communicating with a given client. Note: Mach messaging in OS X is not a supported API. No backwards compatibility guarantees are made for applications that use it anyway. Remote procedure calls (RPC) and Distributed Objects: If your application uses remote procedure calls or Distributed Objects, you are implicitly saying that you fully trust whatever processis at the other end of the connection. That process can call arbitrary functions within your code, and may even be able to arbitrarily overwrite portions of your code with malicious code. For thisreason, you should avoid using remote procedure calls or DistributedObjects when communicating with potentially untrusted processes, and in particular, you should never use these communication technologies across a network boundary. Shared Memory: If you intend to share memory across applications, be careful to allocate any memory on the heap in page-aligned, page-sized blocks. If you share a block of memory that is not a whole page (or worse, if you share some portion of your application’s stack), you may be providing the process at the other end Validating Input and Interprocess Communication Interprocess Communication and Networking 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 40with the ability to overwrite portions of your code,stack, or other data in waysthat can produce incorrect behavior, and may even allow injection of arbitrary code. In addition to these risks, some forms of shared memory can also be subject to race condition attacks. Specifically, memory mapped files can be replaced with other files between when you create the file and when you open it. See “Securing File Operations” (page 47) for more details. Finally, named shared memory regions and memory mapped files can be accessed by any other process running as the user. For this reason, it is not safe to use non-anonymous shared memory for sending highly secret information between processes. Instead, allocate your shared memory region prior to creating the child processthat needsto share that region, then pass IPC_PRIVATE asthe key for shmget to ensure that the shared memory identifier is not easy to guess. Note: Shared memory regions are detached if you call exec or other similar functions. If you need to pass data in a secure way across an exec boundary, you must pass the shared memory ID to the child process. Ideally, you should do this using a secure mechanism, such as a pipe created using a call to pipe. After the last child process that needs to use a particular shared memory region is running, the process that created the region should call shmctl to remove the shared memory region. Doing so ensures that no further processes can attach to that region even if they manage to guess the region ID. shmctl(id, IPC_RMID, NULL); Signals: A signal, in this context, is a particular type of content-free message sent from one process to another in a UNIX-based operating system such as OS X. Any program can register a signal handler function to perform specific operations upon receiving a signal. In general, it is not safe to do a significant amount of work in a signal handler. There are only a handful of library functions and system callsthat are safe to use in a signal handler (referred to as async-signal-safe calls), and this makes it somewhat difficult to safely perform work inside a call. More importantly, however, as a programmer, you are not in control of when your application receives a signal. Thus, if an attacker can cause a signal to be delivered to your process (by overflowing a socket buffer, for example), the attacker can cause your signal handler code to execute at any time, between any two lines of code in your application. This can be problematic if there are certain places where executing that code would be dangerous. For example, in 2004, a signal handler race condition was found in open-source code present in many UNIX-based operating systems. This bug made it possible for a remote attacker to execute arbitrary code Validating Input and Interprocess Communication Interprocess Communication and Networking 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 41or to stop the FTP daemon from working by causing it to read data from a socket and execute commands while it was still running as the root user. [CVE-2004-0794] For this reason, signal handlers should do the minimum amount of work possible, and should perform the bulk of the work at a known location within the application’s main program loop. For example, in an application based on Foundation or Core Foundation, you can create a pair of connected sockets by calling socketpair, call setsockopt to set the socket to non-blocking, turn one end into a CFStream object by calling CFStreamCreatePairWithSocket, and then schedule that stream on your run loop. Then, you can install a minimal signal handler that uses the write system call (which is async-signal-safe according to POSIX.1) to write data into the other socket. When the signal handler returns, your run loop will be woken up by data on the other socket, and you can then handle the signal at your convenience. Important: If you are writing to a socket in a signal handler and reading from it in a run loop on your main program thread, you must set the socket to non-blocking. If you do not, it is possible to cause your application to hang by sending it too many signals. The queue for a socket is of finite size. When it fills up, if the socket is set to non-blocking, the write call fails, and the global variable errno is set to EAGAIN. If the socket is blocking, however, the write call blocks until the queue empties enough to write the data. If a write call in a signal handler blocks, this prevents the signal handler from returning execution to the run loop. If that run loop is responsible for reading data from the socket, the queue will never empty, the write call will never unblock, and your application will basically hang (at least until the write call isinterrupted by anothersignal). Validating Input and Interprocess Communication Interprocess Communication and Networking 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 42When working with shared data, whether in the form of files, databases, network connections,shared memory, or other forms of interprocess communication, there are a number of easily made mistakesthat can compromise security. This chapter describes many such pitfalls and how to avoid them. Avoiding Race Conditions A race condition exists when changes to the order of two or more events can cause a change in behavior. If the correct order of execution is required for the proper functioning of the program, this is a bug. If an attacker can take advantage of the situation to insert malicious code, change a filename, or otherwise interfere with the normal operation of the program, the race condition is a security vulnerability. Attackers can sometimes take advantage of small time gaps in the processing of code to interfere with the sequence of operations, which they then exploit. OS X, like all modern operating systems, is a multitasking OS; that is, it allows multiple processes to run or appear to run simultaneously by rapidly switching among them on each processor. The advantagesto the user are many and mostly obvious; the disadvantage, however, is that there is no guarantee that two consecutive operations in a given process are performed without any other process performing operations between them. In fact, when two processes are using the same resource (such as the same file), there is no guarantee that they will access that resource in any particular order unless both processes explicitly take steps to ensure it. For example, if you open a file and then read from it, even though your application did nothing else between these two operations, some other process might alter the file after the file was opened and before it was read. If two different processes (in the same or different applications) were writing to the same file, there would be no way to know which one would write first and which would overwrite the data written by the other. Such situations cause security vulnerabilities. There are two basic types of race condition that can be exploited: time of check–time of use (TOCTOU), and signal handling. 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 43 Race Conditions and Secure File OperationsTime of Check Versus Time of Use It is fairly common for an application to need to check some condition before undertaking an action. For example, it might check to see if a file exists before writing to it, or whether the user has access rights to read a file before opening it for reading. Because there is a time gap between the check and the use (even though it might be a fraction of a second), an attacker can sometimes use that gap to mount an attack. Thus, this is referred to as a time-of-check–time-of-use problem. Temporary Files A classic example isthe case where an application writestemporary filesto publicly accessible directories. You can set the file permissions of the temporary file to prevent another user from altering the file. However, if the file already exists before you write to it, you could be overwriting data needed by another program, or you could be using a file prepared by an attacker, in which case it might be a hard link or symbolic link, redirecting your output to a file needed by the system or to a file controlled by the attacker. To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opensthe file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists. An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn’t exist and when it opens it for writing. The application then opensthe attacker’sfile and writesto it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file). The attacker’s file might have different access permissions than the application’s temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in. For a real-world example, in a vulnerability in a directory server, a server script wrote private and public keys into temporary files, then read those keys and put them into a database. Because the temporary files were in a publicly writable directory, an attacker could have created a race condition by substituting the attacker’s own files (or hard links or symbolic links to the attacker’s files) before the keys were reread, thus causing the script to insert the attacker’s private and public keys instead. After that, anything Race Conditions and Secure File Operations Avoiding Race Conditions 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 44encrypted or authenticated using those keys would be under the attacker’s control. Alternatively, the attacker could have read the private keys, which can be used to decrypt encrypted data. [CVE-2005-2519] Similarly, if an application temporarily relaxes permissions on files or folders in order to perform some operation, an attacker might be able to create a race condition by carefully timing his or her attack to occur in the narrow window in which those permissions are relaxed. To learn more about creating temporary files securely, read “Create Temporary Files Correctly” (page 50). Interprocess Communication Time-of-check–time-of-use problems do not have to involve files, of course. They can apply to any data storage or communications mechanism that does not perform operations atomically. Suppose, for example, that you wrote a program designed to automatically count the number of people entering a sports stadium for a game. Each turnstile talks to a web service running on a server whenever someone walks through. Each web service instance inherently runs as a separate process. Each time a turnstile sends a signal, an instance of the web service starts up, retrievesthe gate count from a database, increments it by one, and writes it back to the database. Thus, multiple processes are keeping a single running total. Now suppose two people enter different gates at exactly the same time. The sequence of events might then be as follows: 1. Server process A receives a request from gate A. 2. Server process B receives a request from gate B. 3. Server process A reads the number 1000 from the database. 4. Server process B reads the number 1000 from the database. 5. Server process A increments the gate count by 1 so that Gate == 1001. 6. Server process B increments the gate count by 1 so that Gate == 1001. 7. Server process A writes 1001 as the new gate count. 8. Server process B writes 1001 as the new gate count. Because server process B read the gate count before process A had time to increment it and write it back, both processesread the same value. After process A incrementsthe gate count and writesit back, process B overwrites the value of the gate count with the same value written by process A. Because of this race condition, one of the two people entering the stadium was not counted. Since there might be long lines at each turnstile, this condition might occur many times before a big game, and a dishonest ticket clerk who knew about this undercount could pocket some of the receipts with no fear of being caught. Other race conditions that can be exploited, like the example above, involve the use of shared data or other interprocess communication methods. If an attacker can interfere with important data after it is written and before it isre-read, he orshe can disrupt the operation of the program, alter data, or do other Race Conditions and Secure File Operations Avoiding Race Conditions 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 45mischief. The use of non-thread-safe calls in multithreaded programs can result in data corruption. If an attacker can manipulate the program to cause two such threads to interfere with each other, it may be possible to mount a denial-of-service attack. In some cases, by using such a race condition to overwrite a buffer in the heap with more data than the buffer can hold, an attacker can cause a buffer overflow. As discussed in “Avoiding Buffer Overflows And Underflows” (page 17), buffer overflows can be exploited to cause execution of malicious code. The solution to race conditions involving shared data is to use a locking mechanism to prevent one process from changing a variable until another is finished with it. There are problems and hazards associated with such mechanisms, however, and they must be implemented carefully. And, of course, locking mechanisms only apply to processes that participate in the locking scheme. They cannot prevent an untrusted application from modifying the data maliciously. For a full discussion, see Wheeler, Secure Programming for Linux and Unix HOWTO, at http://www.dwheeler.com/secure-programs/. Time-of-check–time-of-use vulnerabilities can be prevented in different ways, depending largely on the domain of the problem. When working with shared data, you should use locking to protect that data from other instances of your code. When working with data in publicly writable directories, you should also take the precautions described in “Files In Publicly Writable Directories Are Dangerous” (page 51). Signal Handling Because signal handlers execute code at arbitrary times, they can be used to cause incorrect behavior. In daemons running as root, running the wrong code at the wrong time can even cause privilege escalation. “Securing Signal Handlers” (page 46) describes this problem in more detail. Securing Signal Handlers Signal handlers are another common source of race conditions. Signalsfrom the operating system to a process or between two processes are used for such purposes as terminating a process or causing it to reinitialize. If you include signal handlers in your program, they should not make any system calls and should terminate as quickly as possible. Although there are certain system calls that are safe from within signal handlers, writing a safe signal handler that does so is tricky. The best thing to do is to set a flag that your program checks periodically, and do no other work within the signal handler. Thisis because the signal handler can be interrupted by a new signal before it finishes processing the first signal, leaving the system in an unpredictable state or, worse, providing a vulnerability for an attacker to exploit. Race Conditions and Secure File Operations Securing Signal Handlers 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 46For example, in 1997, a vulnerability wasreported in a number of implementations of the FTP protocol in which a user could cause a race condition by closing an FTP connection. Closing the connection resulted in the near-simultaneous transmission of two signals to the FTP server: one to abort the current operation, and one to log out the user. The race condition occurred when the logout signal arrived just before the abort signal. When a user logged onto an FTP server as an anonymous user, the server would temporarily downgrade its privilegesfrom root to nobody so that the logged-in user had no privilegesto write files. When the user logged out, however, the server reassumed root privileges. If the abort signal arrived at just the right time, it would abort the logout procedure after the server had assumed root privileges but before it had logged out the user. The user would then be logged in with root privileges, and could proceed to write files at will. An attacker could exploit this vulnerability with a graphical FTP client simply by repeatedly clicking the “Cancel” button. [CVE-1999-0035] For a brief introduction to signal handlers, see the Little Unix Programmers Group site at http://users.actcom.co.il/~choo/lupg/tutorials/signals/signals-programming.html. For a discourse on how signal handler race conditions can be exploited,see the article by Michal Zalewski at http://www.bindview.com/Services/razor/Papers/2001/signals.cfm. Securing File Operations Insecure file operations are a major source of security vulnerabilities. In some cases, opening or writing to a file in an insecure fashion can give attackers the opportunity to create a race condition (see “Time of Check Versus Time of Use” (page 44)). Often, however, insecure file operations give an attacker the ability to read confidential information, perform a denial of service attack, take control of an application, or even take control of the entire system. This section discusses what you should do to make your file operations more secure. Check Result Codes Always check the result codes of every routine that you call. Be prepared to handle the situation if the operation fails. Most file-based security vulnerabilities could have been avoided if the developers of the programs had checked result codes. Some common mistakes are listed below. When writing to files or changing file permissions A failure when change permissions on a file or to open a file for writing can be caused by many things, including: ● Insufficient permissions on the file or enclosing directory. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 47● The immutable flag (set with the chflags utility or the chflags system call). ● A network volume becoming unavailable. ● An external drive getting unplugged. ● A drive failure. Depending on the nature of your software, any one of these could potentially be exploited if you do not properly check error codes. See the manual pages for the chflags, chown, and chgrp commands and the chflags and chown functions for more information. When removing files Although the rm command can often ignore permissions if you pass the -f flag, it can still fail. For example, you can’t remove a directory that has anything inside it. If a directory is in a location where other users have access to it, any attempt to remove the directory might fail because another process might add new files while you are removing the old ones. The safest way to fix this problem is to use a private directory that no one else has access to. If that’s not possible, check to make sure the rm command succeeded and be prepared to handle failures. Watch Out for Hard Links A hard link is a second name for a file—the file appears to be in two different locations with two different names. If a file has two (or more) hard links and you check the file to make sure that the ownership, permissions, and so forth are all correct, but fail to check the number of links to the file, an attacker can write to or read from the file through their own link in their own directory. Therefore, among other checks before you use a file, you should check the number of links. Do not, however, simply fail if there’s a second link to a file, because there are some circumstances where a link is okay or even expected. For example, every directory islinked into at least two placesin the hierarchy—the directory name itself and the special . record from the directory that links back to itself. Also, if that directory contains other directories, each of those subdirectories contains a .. record that points to the outer directory. You need to anticipate such conditions and allow for them. Even if the link is unexpected, you need to handle the situation gracefully. Otherwise, an attacker can cause denial of service just by creating a link to the file. Instead, you should notify the user of the situation, giving them as much information as possible so they can try to track down the source of the problem. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 48Watch Out for Symbolic Links A symbolic link is a special type of file that contains a path name. Symbolic links are more common than hard links. Functions that follow symbolic links automatically open, read, or write to the file whose path name is in the symbolic link file rather than the symbolic link file itself. Your application receives no notification that a symbolic link was followed; to your application, it appears as if the file addressed is the one that was used. An attacker can use a symbolic link, for example, to cause your application to write the contents intended for a temporary file to a critical system file instead, thus corrupting the system. Alternatively, the attacker can capture data you are writing or can substitute the attacker’s data for your own when you read the temporary file. In general, you should avoid functions,such as chown and stat, that follow symbolic links(see Table 4-1 (page 55) for alternatives). As with hard links, your program should evaluate whether a symbolic link is acceptable, and if not, should handle the situation gracefully. Case-Insensitive File Systems Can Thwart Your Security Model In OS X, any partition (including the boot volume) can be either case-sensitive, case-insensitive but case-preserving, or, for non-boot volumes, case-insensitive. For example, HFS+ can be either case-sensitive or case-insensitive but case-preserving. FAT32 is case-insensitive but case-preserving. FAT12, FAT16, and ISO-9660 (without extensions) are case-insensitive. An application that is unaware of the differences in behavior between these volume formats can cause serious security holes if you are not careful. In particular: ● If your program uses its own permission model to provide or deny access (for example, a web server that allows access only to files within a particular directory), you must either enforce this with a chroot jail or be vigilant about ensuring that you correctly identify paths even in a case-insensitive world. Among other things, this meansthat you should ideally use a whitelisting scheme rather than a blacklisting scheme (with the default behavior being “deny”). If this is not possible, for correctness, you must compare each individual path part against your blacklist using case-sensitive or case-insensitive comparisons, depending on what type of volume the file resides on. For example, if your program has a blacklist that prevents users from uploading or downloading the file /etc/ssh_host_key, if your software is installed on a case-insensitive volume, you must also reject someone who makes a request for /etc/SSH_host_key, /ETC/SSH_HOST_KEY, or even /ETC/ssh_host_key. ● If your program periodically accesses a file on a case-sensitive volume using the wrong mix of uppercase and lowercase letters, the open call will fail... until someone creates a second file with the name your program is actually asking for. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 49If someone creates such a file, your application will dutifully load data from the wrong file. If the contents of that file affect your application’s behavior in some important way, this represents a potential attack vector. This also presents a potential attack vector if that file is an optional part of your application bundle that gets loaded by dyld when your application is launched. Create Temporary Files Correctly The temporary directories in OS X are shared among multiple users. This requires that they be writable by multiple users. Any time you work on files in a location to which others have read/write access, there’s the potential for the file to be compromised or corrupted. The following list explains how to create temporary files using APIs at various layers of OS X. POSIX Layer In general, you should always use the mkstemp function to create temporary files at the POSIX layer. The mkstemp function guarantees a unique filename and returns a file descriptor, thus allowing you skip the step of checking the open function result for an error, which might require you to change the filename and call open again. If you must create a temporary file in a public directory manually, you can use the open function with the O_CREAT and O_EXCL flags set to create the file and obtain a file descriptor. The O_EXCL flag causes this function to return an error if the file already exists. Be sure to check for errors before proceeding. After you’ve opened the file and obtained a file descriptor, you can safely use functions that take file descriptors, such as the standard C functions write and read, for as long as you keep the file open. See the manual pages for open(2), mkstemp(3), write(2), and read(2) for more on these functions, and see Wheeler, Secure Programming for Linux and Unix HOWTO for advantages and shortcomings to using these functions. Carbon To find the default location to store temporary files, you can call the FSFindFolder function and specify a directory type of kTemporaryFolderType. This function checks to see whether the UID calling the function owns the directory and, if not, returns the user home directory in ~/Library. Therefore, this function returns a relatively safe place to store temporary files. Thislocation is not assecure as a directory that you created and that is accessible only by your program. The FSFindFolder function is documented in Folder Manager Reference . If you’ve obtained the file reference of a directory (from the FSFindFolder function, for example), you can use the FSRefMakePath function to obtain the directory’s path name. However, be sure to check the function result, because if the FSFindFolder function fails, it returns a null string. If you don’t Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 50check the function result, you might end up trying to create a temporary file with a pathname formed by appending a filename to a null string. Cocoa There are no Cocoa methods that create a file and return a file descriptor. However, you can call the standard C open function from an Objective-C program to obtain a file descriptor (see “Working With Publicly Writable Files Using POSIX Calls” (page 54)). Or you can call the mkstemp function to create a temporary file and obtain a file descriptor. Then you can use the NSFileHandle method initWithFileDescriptor: to initialize a file handle, and other NSFileHandle methods to safely write to or read from the file. Documentation for the NSFileHandle class is in Foundation Framework Reference . To obtain the path to the default location to store temporary files (stored in the $TMPDIR environment variable), you can use the NSTemporaryDirectory function, which calls the FSFindFolder and FSRefMakePath functions for you (see “Working With Publicly Writable Files Using Carbon” (page 55)). Note that NSTemporaryDirectory can return /tmp under certain circumstances such as if you link on a pre-OS X v10.3 development target. Therefore, if you’re using NSTemporaryDirectory, you either have to be sure that using /tmp is suitable for your operation or, if not, you should consider that an error case and create a more secure temporary directory if that happens. The changeFileAttributes:atPath: method in the NSFileManager class is similar to chmod or chown, in that it takes a file path rather than a file descriptor. You shouldn’t use this method if you’re working in a public directory or a user’s home directory. Instead, call the fchown or fchmod function (see Table 4-1 (page 55)). You can call the NSFileHandle class’s fileDescriptor method to get the file descriptor of a file in use by NSFileHandle. In addition, when working with temporary files, you should avoid the writeToFile:atomically methods of NSString and NSData. These are designed to minimize the risk of data loss when writing to a file, but do so in a way that is not recommended for use in directories that are writable by others. See “Working With Publicly Writable Files Using Cocoa” (page 56) for details. Files in Publicly Writable Directories Are Dangerous Files in publicly writable directories must be treated as inherently untrusted. An attacker can delete the file and replace it with another file, replace it with a symbolic link to another file, create the file ahead of time, and so on. There are ways to mitigate each of these attacks to some degree, but the best way to prevent them is to not read or write files in a publicly writable directory in the first pace. If possible, you should create a subdirectory with tightly controlled permissions, then write your files inside that subdirectory. If you must work in a directory to which your process does not have exclusive access, however, you must check to make sure a file does not exist before you create it. You must also verify that the file you intend to read from or write to is the same file that you created. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 51To this end, you should always use routines that operate on file descriptors rather than pathnames wherever possible, so that you can be certain you’re always dealing with the same file. To do this, pass the O_CREAT and O_EXCL flags to the open system call. This creates a file, but fails if the file already exists. Note: If you cannot use file descriptors directly for some reason, you should explicitly create files as a separate step from opening them. Although this does not prevent someone from swapping in a new file between those operations, at least it narrows the attack window by making it possible to detect if the file already exists. Before you create the file, however, you should first set your process’s file creation mask (umask). The file creation mask is a bitmask that alters the default permissions of all new files and directories created by your process. This bitmask is typically specified in octal notation, which means that it must begin with a zero (not 0x). For example, if you set the file creation mask to 022, any new files created by your process will have rw-r--r-- permissions because the write permission bits are masked out. Similarly, any new directories will have rw-r-xr-x permissions. Note: New files never have the execute bit set. Directories, however, do. Therefore, you should generally mask out execute permission when masking out read permission unless you have a specific reason to allow users to traverse a directory without seeing its contents. To limit access to any new files or directories so that only the user can access them, set the file creation mask to 077. You can also mask out permissions in such a way that they apply to the user, though this is rare. For example, to create a file that no one can write or execute, and that only the user can read, you could set the file creation mask to 0377. This is not particularly useful, but it is possible. There are several ways to set the file creation mask: In C code: In C code, you can set the file creation mask globally using the umask system call. You can also passthe file creation mask to the open or mkdir system call when creating a file or directory. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 52Note: For maximum portability when writing C code, you should always create your masks using the file mode constants defined in . For example: umask(S_IRWXG|S_IRWXO); In shell scripts: In shell scripts, you set the file creation mask by using the umask shell builtin. This is documented in the manual pages for sh or csh. For example: umask 0077; As an added security bonus, when a process calls another process, the new processinheritsthe parent process’s file creation mask. Thus, if your process starts another process that creates a file without resetting the file creation mask, that file similarly will not be accessible to other users on the system. This is particularly useful when writing shell scripts. For more information on the file creation mask,see the manual page for umask and Viega and McGraw, Building Secure Software , Addison Wesley, 2002. For a particularly lucid explanation of the use of a file creation mask, see http://web.archive.org/web/20090517063338/http://www.sun.com/bigadmin/content/submitted/umask_permissions.html?. Before you read a file (but after opening it), make sure it has the owner and permissions you expect (using fstat). Be prepared to fail gracefully (rather than hanging) if it does not. Here are some guidelines to help you avoid time-of-check–time-of-use vulnerabilities when working with files in publicly writable directories. For more detailed discussions, especially for C code, see Viega and McGraw, Building Secure Software , Addison Wesley, 2002, and Wheeler, Secure Programming for Linux and Unix HOWTO, available at http://www.dwheeler.com/secure-programs/. ● If at all possible, avoid creating temporary files in a shared directory, such as /tmp, or in directories owned by the user. If anyone else has access to your temporary file, they can modify its content, change its ownership or mode, or replace it with a hard or symbolic link. It’s much safer to either not use a temporary file at all (use some other form of interprocess communication) or keep temporary files in a directory you create and to which only your process (acting as your user) has access. ● If your file must be in a shared directory, give it a unique (and randomly generated) filename (you can use the C function mkstemp to do this), and never close and reopen the file. If you close such a file, an attacker can potentially find it and replace it before you reopen it. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 53Here are some public directories that you can use: ● ~/Library/Caches/TemporaryItems When you use this subdirectory, you are writing to the user’s own home directory, not some other user’s directory or a system directory. If the user’s home directory has the default permissions, it can be written to only by that user and root. Therefore, this directory is not as susceptible to attack from outside, nonprivileged users as some other directories might be. ● /var/run This directory is used for process ID (pid) files and other system files needed just once per startup session. This directory is cleared out each time the system starts up. ● /var/db This directory is used for databases accessible to system processes. ● /tmp This directory is used for general shared temporary storage. It is cleared out each time the system starts up. ● /var/tmp This directory is used for general shared temporary storage. Although you should not count on data stored in this directory being permanent, unlike /tmp, the /var/tmp directory is currently not cleared out on reboot. For maximum security, you should always create temporary subdirectories within these directories, set appropriate permissions on those subdirectories, and then write files into those subdirectories. The following sections give some additional hints on how to follow these principles when you are using POSIX-layer C code, Carbon, and Cocoa calls. Working with Publicly Writable Files Using POSIX Calls If you need to open a preexisting file to modify it or read from it, you should check the file’s ownership, type, and permissions, and the number of links to the file before using it. To safely opening a file for reading, for example, you can use the following procedure: 1. Call the open function and save the file descriptor. Pass the O_NOFOLLOW to ensure that it does not follow symbolic links. 2. Using the file descriptor, call the fstat function to obtain the stat structure for the file you just opened. 3. Check the user ID (UID) and group ID (GID) of the file to make sure they are correct. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 544. Check the file's mode flags to make sure that it is a normal file, not a FIFO, device file, or other special file. Specifically, if the stat structure is named st, then the value of (st.st_mode & S_IFMT) should be equal to S_IFREG. 5. Check the read, write, and execute permissions for the file to make sure they are what you expect. 6. Check that there is only one hard link to the file. 7. Pass around the open file descriptor for later use rather than passing the path. Note that you can avoid all the status checking by using a secure directory instead of a public one to hold your program’s files. Table 4-1 shows some functions to avoid—and the safer equivalent functions to use—in order to avoid race conditions when you are creating files in a public directory. Table 4-1 C file functions to avoid and to use Functions to avoid Functions to use instead open returns a file descriptor; creates a file and returns an error if the file already exists when the O_CREAT and O_EXCL options are used fopen returns a file pointer; automatically creates the file if it does not exist but returns no error if the file does exist chmod takes a file path fchmod takes a file descriptor fchown takes a file descriptor and does not follow symbolic links chown takes a file path and follows symbolic links lstat takes a file path but does not follow symbolic links; fstat takes a file descriptor and returns information about an open file stat takes a file path and follows symbolic links mkstemp creates a temporary file with a unique name, opens it for reading and writing, and returns a file descriptor mktemp creates a temporary file with a unique name and returns a file path; you need to open the file in another call Working with Publicly Writable Files Using Carbon If you are using the Carbon File Manager to create and open files, you should be aware of how the File Manager accesses files. ● The file specifier FSSpec structure uses a path to locate files, not a file descriptor. Functions that use an FSSpec file specifier are deprecated and should not be used in any case. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 55● The file reference FSRef structure uses a path to locate files and should be used only if your files are in a safe directory, not in a publicly accessible directory. These functions include FSGetCatalogInfo, FSSetCatalogInfo, FSCreateFork, and others. ● The File Manager creates and opensfilesin separate operations. The create operation failsif the file already exists. However, none of the file-creation functions return a file descriptor. If you’ve obtained the file reference of a directory (from the FSFindFolder function, for example), you can use the FSRefMakePath function to obtain the directory’s path name. However, be sure to check the function result, because if the FSFindFolder function fails, it returns a null string. If you don’t check the function result, you might end up trying to create a temporary file with a pathname formed by appending a filename to a null string. Working with Publicly Writable Files Using Cocoa The NSString and NSData classes have writeToFile:atomically methods designed to minimize the risk of data loss when writing to a file. These methods write first to a temporary file, and then, when they’re sure the write is successful, they replace the written-to file with the temporary file. This is not always an appropriate thing to do when working in a public directory or a user’s home directory, because there are a number of path-based file operationsinvolved. Instead, initialize an NSFileHandle object with an existing file descriptor and use NSFileHandle methods to write to the file, as mentioned above. The following code, for example, usesthe mkstemp function to create a temporary file and obtain a file descriptor, which it then usesto initialize NSFileHandle: fd = mkstemp(tmpfile); // check return for -1, which indicates an error NSFileHandle *myhandle = [[NSFileHandle alloc] initWithFileDescriptor:fd]; Working with Publicly Writable Files in Shell Scripts Scripts must follow the same general rules as other programs to avoid race conditions. There are a few tips you should know to help make your scripts more secure. First, when writing a script, set the temporary directory ($TMPDIR) environment variable to a safe directory. Even if your script doesn’t directly create any temporary files, one or more of the routines you call might create one, which can be a security vulnerability if it’s created in an insecure directory. See the manual pages for setenv and setenv for information on changing the temporary directory environment variable. For the same reason, set your process’ file code creation mask (umask) to restrict access to any files that might be created by routines run by your script (see “Securing File Operations” (page 47) for more information on the umask). Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 56It’s also a good idea to use the dtruss command on a shell script so you can watch every file access to make sure that no temporary files are created in an insecure location. See the manual pages for dtrace and dtruss for more information. Do not redirect output using the operators > or >> to a publicly writable location. These operators do not check to see whether the file already exists, and they follow symbolic links. Instead, pass the -d flag to the mktemp command to create a subdirectory to which only you have access. It’s important to check the result to make sure the command succeeded. if you do all your file operations in this directory, you can be fairly confident that no one with less than root access can interfere with your script. For more information, see the manual page for mktemp. Do not use the test command (or its left bracket ([) equivalent) to check for the existence of a file or other statusinformation for the file before writing to it. Doing so alwaysresultsin a race condition; that is, it is possible for an attacker to create, write to, alter, or replace the file before you start writing. See the manual page for test for more information. For a more in-depth look at security issues specific to shell scripts, read “Shell Script Security” in Shell Scripting Primer. Other Tips Here are a few additional things to be aware of when working with files: ● Before you attempt a file operation, make sure it is safe to perform the operation on that file. For example, before attempting to read a file (but after opening it), you should make sure that it is not a FIFO or a device special file. ● Just because you can write to a file, that doesn’t mean you should write to it. For example, the fact that a directory exists doesn’t mean you created it, and the fact that you can append to a file doesn’t mean you own the file or no one else can write to it. ● OS X can perform file operations on files in several different file systems. Some operations can be done only on certain systems. For example, certain file systems honor setuid files when executed from them and some don’t. Be sure you know what file system you’re working with and what operations can be carried out on that system. ● Local pathnames can point to remote files. For example, the path /volumes/foo might actually be someone’s FTP server rather than a locally-mounted volume. Just because you’re accessing something by a pathname, that does not guarantee that it’s local or that it should be accessed. ● A user can mount a file system anywhere they have write access and own the directory. In other words, almost anywhere a user can create a directory, they can mount a file system on top of it. Because this can be done remotely, an attacker running as root on a remote system could mount a file system into your home directory. Files in that file system would appear to be files in your home directory owned by root. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 57For example, /tmp/foo might be a local directory, or it might be the root mount point of a remotely mounted file system. Similarly, /tmp/foo/bar might be a local file, or it might have been created on another machine and be owned by root over there. Therefore, you can’t trust files based only on ownership, and you can’t assume that setting the UID to 0 was done by someone you trust. To tell whether the file is mounted locally, use the fstat call to check the device ID. If the device ID is different from that of files you know to be local, then you’ve crossed a device boundary. ● Remember that users can read the contents of executable binariesjust as easily asthe contents of ordinary files. For example, the user can run strings(1) to quickly see a list of (ostensibly) human-readable strings in your executable. ● When you fork a new process, the child process inherits all the file descriptors from the parent unless you set the close-on-exec flag. If you fork and execute a child process and drop the child process’ privileges so its real and effective IDs are those of some other user (to avoid running that process with elevated privileges), then that user can use a debugger to attach the child process. They can then run arbitrary code from that running process. Because the child process inherited all the file descriptors from the parent, the user now has access to every file opened by the parent process. See “Inheriting File Descriptors” (page 61) for more information on this type of vulnerability. Race Conditions and Secure File Operations Securing File Operations 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 58By default, applications run as the currently logged in user. Different users have different rights when it comes to accessing files, changing systemwide settings, and so on, depending on whether they are admin users or ordinary users. Some tasks require additional privileges above and beyond what even an admin user can do by default. An application or other process with such additional rights is said to be running with elevated privileges. Running code with root or administrative privileges can intensify the dangers posed by security vulnerabilities. This chapter explains the risks, provides alternatives to privilege elevation, and describes how to elevating privileges safely when you can’t avoid it. Note: Elevating privileges is not allowed in applications submitted to the Mac App Store (and is not possible in iOS). Circumstances Requiring Elevated Privileges Regardless of whether a user is logged in as an administrator, a program might have to obtain administrative or root privileges in order to accomplish a task. Examples of tasks that require elevated privileges include: ● manipulating file permissions, ownership ● creating, reading, updating, or deleting system and user files ● opening privileged ports (those with port numbers less than 1024) for TCP and UDP connections ● opening raw sockets ● managing processes ● reading the contents of virtual memory ● changing system settings ● loading kernel extensions If you have to perform a task that requires elevated privileges, you must be aware of the fact that running with elevated privileges means that if there are any security vulnerabilities in your program, an attacker can obtain elevated privileges as well, and would then be able to perform any of the operations listed above. 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 59 Elevating Privileges SafelyThe Hostile Environment and the Principle of Least Privilege Any program can come under attack, and probably will. By default, every process runs with the privileges of the user or process that started it. Therefore, if a user has logged on with restricted privileges, your program should run with those restricted privileges. This effectively limits the amount of damage an attacker can do, even if he successfully hijacks your program into running malicious code. Do not assume that the user islogged in with administrator privileges; you should be prepared to run a helper application with elevated privileges if you need them to accomplish a task. However, keep in mind that, if you elevate your process’s privileges to run asroot, an attacker can gain those elevated privileges and potentially take over control of the whole system. Note: Although in certain circumstances it’s possible to mount a remote attack over a network, for the most part the vulnerabilities discussed here involve malicious code running locally on the target computer. If an attacker uses a buffer overflow or othersecurity vulnerability (see “Types of Security Vulnerabilities” (page 11)) to execute code on someone else’s computer, they can generally run their code with whatever privileges the logged-in user has. If an attacker can gain administrator privileges, they can elevate to root privileges and gain accessto any data on the user’s computer. Therefore, it is good security practice to log in as an administrator only when performing the rare tasks that require admin privileges. Because the default setting for OS X is to make the computer’s owner an administrator, you should encourage your usersto create a separate non-admin login and to use that for their everyday work. In addition, if possible, you should not require admin privileges to install your software. The idea of limiting risk by limiting access goes back to the “need to know” policy followed by government security agencies (no matter what your security clearance, you are not given access to information unless you have a specific need to know that information). In software security, this policy is often termed “the principle of least privilege,” first formally stated in 1975: “Every program and every user of the system should operate using the leastset of privileges necessary to complete the job.”(Saltzer,J.H. AND Schroeder, M.D.,“The Protection of Information in Computer Systems,” Proceedings of the IEEE , vol. 63, no. 9, Sept 1975.) In practical terms, the principle of least privilege means you should avoid running asroot, or—if you absolutely must run asroot to perform some task—you should run a separate helper application to perform the privileged task (see “Factoring Applications” (page 69)). By running with the least privilege possible, you: ● Limit damage from accidents and errors, including maliciously introduced accidents and errors ● Reduce interactions of privileged components, and therefore reduce unintentional, unwanted, and improper uses of privilege (side effects) Elevating Privileges Safely The Hostile Environment and the Principle of Least Privilege 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 60Keep in mind that, even if your code is free of errors, vulnerabilities in any libraries your code links in can be used to attack your program. For example, no program with a graphical user interface should run with privileges because the large number of libraries used in any GUI application makes it virtually impossible to guarantee that the application has no security vulnerabilities. There are a number of ways an attacker can take advantage of your program if you run as root. Some possible approaches are described in the following sections. Launching a New Process Because any new process runs with the privileges of the process that launched it, if an attacker can trick your process into launching his code, the malicious code runs with the privileges of your process. Therefore, if your process is running with root privileges and is vulnerable to attack, the attacker can gain control of the system. There are many ways an attacker can trick your code into launching malicious code, including buffer overflows, race conditions, and social engineering attacks (see “Types of Security Vulnerabilities” (page 11)). Executing Command-Line Arguments Because all command-line arguments, including the program name (argv(0)), are under the control of the user, you should not use the command line to execute any program without validating every parameter, including the name. If you use the command line to re-execute your own code or execute a helper program, for example, a malicious user might have substituted his own code with that program name, which you are now executing with your privileges. Inheriting File Descriptors When you create a new process, the child process inherits its own copy of the parent process’s file descriptors (see the manual page for fork(2)). Therefore, if you have a handle on a file, network socket, shared memory, or other resource that’s pointed to by a file descriptor and you fork off a child process, you must be careful to either close the file descriptor or you must make sure that the child process cannot be tampered with. Otherwise, a malicious user can use the subprocess to tamper with the resources referenced by the file descriptors. For example, if you open a password file and don’t close it before forking a process, the new subprocess has access to the password file. To set a file descriptor so that it closes automatically when you execute a new process (such as by using the execve system call), use the fcntl(2) command to set the close-on-exec flag. You mustset thisflag individually for each file descriptor; there’s no way to set it for all. Elevating Privileges Safely The Hostile Environment and the Principle of Least Privilege 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 61Abusing Environment Variables Most libraries and utilities use environment variables. Sometimes environment variables can be attacked with buffer overflows or by inserting inappropriate values. If your program links in any libraries or calls any utilities, your program is vulnerable to attacks through any such problematic environment variables. If your program is running as root, the attacker might be able to bring down or gain control of the whole system in this way. Examples of environment variables in utilities and libraries that have been attacked in the past include: 1. The dynamic loader: LD_LIBRARY_PATH, DYLD_LIBRARY_PATH are often misused, causing unwanted side effects. 2. libc: MallocLogFile 3. Core Foundation: CF_CHARSET_PATH 4. perl: PERLLIB, PERL5LIB, PERL5OPT [ 2 CVE-2005-2748 (corrected in Apple Security Update 2005-008) 3 CVE-2005-0716 (corrected in Apple Security Update 2005-003) 4 CVE-2005-4158] Environment variables are also inherited by child processes. If you fork off a child process, your parent process should validate the values of all environment variables before it uses them in case they were altered by the child process (whether inadvertently or through an attack by a malicious user). Modifying Process Limits You can use the setrlimit call to limit the consumption of system resources by a process. For example, you can set the largest size of file the process can create, the maximum amount of CPU time the process can consume, and the maximum amount of physical memory a process may use. These process limits are inherited by child processes. In order to prevent an attacker from taking advantage of open file descriptors, programsthat run with elevated privileges often close all open file descriptors when they start up. However, if an attacker can use setrlimit to alter the file descriptor limit, he can fool the program into leaving some of the files open. Those files are then vulnerable. Similarly, a vulnerability was reported for a version of Linux that made it possible for an attacker, by decreasing the maximum file size, to limit the size of the /etc/passwd and /etc/shadow files. Then, the next time a utility accessed one of these files, it truncated the file, resulting in a loss of data and denial of service. [CVE-2002-0762] Elevating Privileges Safely The Hostile Environment and the Principle of Least Privilege 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 62File Operation Interference If you’re running with elevated privileges in order to write or read files in a world-writable directory or a user’s directory, you must be aware of time-of-check–time-of-use problems; see “Time of Check Versus Time of Use” (page 44). Avoiding Elevated Privileges In many cases, you can accomplish your task without needing elevated privileges. For example, suppose you need to configure the environment (add a configuration file to the user’s home directory or modify a configuration file in the user’s home directory) for your application. You can do this from an installer running asroot (the installer command requires administrative privileges;see the manual page for installer(8)). However, if you have the application configure itself, or check whether configuration is needed when it starts up, then you don’t need to run as root at all. An example of using an alternate design in order to avoid running with elevated privileges is given by the BSD ps command, which displaysinformation about processesthat have controlling terminals. Originally, BSD used the setgid bit to run the ps command with a group ID of kmem, which gave it privilegesto read kernel memory. More recent implementations of the ps command use the sysctl utility to read the information it needs, removing the requirement that ps run with any special privileges. Running with Elevated Privileges If you do need to run code with elevated privileges, there are several approaches you can take: ● You can run a daemon with elevated privileges that you call on when you need to perform a privileged task. The preferred method of launching a daemon is to use the launchd daemon (see “launchd” (page 66)). It is easier to use launchd to launch a daemon and easier to communicate with a daemon than it is to fork your own privileged process. ● You can use the authopen command to read, create, or update a file (see “authopen” (page 65)). ● You can set the setuid and setgid bitsfor the executable file of your code, and set the owner and group of the file to the privilege level you need; for example, you can set the owner to root and the group to wheel. Then when the code is executed, it runs with the elevated privileges of its owner and group rather than with the privileges of the process that executed it. (See the “Permissions” section in the “Security Concepts” chapter in Security Overview.) This technique is often used to execute the privileged code in a factored application (see “Factoring Applications” (page 69)). As with other privileged code, you must be very sure that there are no vulnerabilities in your code and that you don’t link in any libraries or call any utilities that have vulnerabilities. Elevating Privileges Safely Avoiding Elevated Privileges 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 63If you fork off a privileged process, you should terminate it as soon as it has accomplished its task (see “Factoring Applications” (page 69)). Although architecturally thisis often the bestsolution, it is very difficult to do correctly, especially the first time you try. Unless you have a lot of experience with forking off privileged processes, you might want to try one of the other solutions first. ● You can use a BSD system call to change privilege level (see “Calls to Change Privilege Level” (page 64)). These commands have confusing semantics. You must be careful to use them correctly, and it’s very important to check the return values of these calls to make sure they succeeded. Note that in general, unless your process was initially running as root, it cannot elevate its privilege with these calls. However, a process running as root can discard (temporarily or permanently) those privileges. Any process can change from acting on behalf of one group to another (within the set of groups to which it belongs). Calls to Change Privilege Level There are several commands you can use to change the privilege level of a program. The semantics of these commands are tricky, and vary depending on the operating system on which they’re used. Important: If you are running with both a group ID (GID) and user ID (UID) that are different from those of the user, you have to drop the GID before dropping the UID. Once you’ve changed the UID, you may no longer have sufficient privileges to change the GID. Important: As with every security-related operation, you must check the return values of your calls to setuid, setgid, and related routines to make sure they succeeded. Otherwise you might still be running with elevated privileges when you think you have dropped privileges. For more information on permissions,see the “Permissions”section in the “Security Concepts” chapter in Security Overview. For information on setuid and related commands, see Setuid Demystified by Chen, Wagner, and Dean (Proceedings of the 11th USENIX Security Symposium, 2002), available at http://www.usenix.org/publications/library/proceedings/sec02/full_papers/chen/chen.pdf and the manual pages for setuid(2), setreuid(2), setregid(2), and setgroups(2). The setuid(2)manual page includesinformation about seteuid, setgid, and setegid as well. Here are some notes on the most commonly used system calls for changing privilege level: Elevating Privileges Safely Calls to Change Privilege Level 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 64● The setuid function sets the real and effective user IDs and the saved user ID of the current process to a specified value. The setuid function is the most confusing of the UID-setting system calls. Not only does the permission required to use this call differ among different UNIX-based systems, but the action of the call differs among different operating systems and even between privileged and unprivileged processes. If you are trying to set the effective UID, you should use the seteuid function instead. ● The setreuid function modifies the real UID and effective UID, and in some cases, the saved UID. The permission required to use this call differs among different UNIX-based systems, and the rule by which the saved UID is modified is complicated. For this function as well, if your intent is to set the effective UID, you should use the seteuid function instead. ● The seteuid function sets the effective UID, leaving the real UID and saved UID unchanged. In OS X, the effective user ID may be set to the value of the real user ID or of the saved set-user-ID. (In some UNIX-based systems, thisfunction allows you to set the EUID to any of the real UID,saved UID, or EUID.) Of the functions available on OS X that set the effective UID, the seteuid function is the least confusing and the least likely to be misused. ● The setgid function acts similarly to the setuid function, except that it sets group IDs rather than user IDs. It suffers from the same shortcomings as the setuid function; use the setegid function instead. ● The setregid function acts similarly to the setreuid function, with the same shortcomings; use the setegid function instead. ● The setegid function sets the effective GID. This function is the preferred call to use if you want to set the EGID. Avoiding Forking Off a Privileged Process There are a couple of functions you might be able to use to avoid forking off a privileged helper application. The authopen command lets you obtain temporary rights to create, read, or update a file. You can use the launchd daemon to start a process with specified privileges and a known environment. authopen When you run the authopen command, you provide the pathname of the file that you want to access. There are options for reading the file, writing to the file, and creating a new file. Before carrying out any of these operations, the authopen command requests authorization from the system security daemon, which authenticates the user (through a password dialog or other means) and determines whether the user has sufficient rights to carry out the operation. See the manual page for authopen(1) for the syntax of this command. Elevating Privileges Safely Avoiding Forking Off a Privileged Process 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 65launchd Starting with OS X v10.4, the launchd daemon is used to launch daemons and other programs automatically, without user intervention. (If you need to support systems running versions of the OS earlier than OS X v10.4, you can use startup items.) The launchd daemon can launch both systemwide daemons and per-user agents, and can restart those daemons and agents after they quit if they are still needed. You provide a configuration file that tells launchd the level of privilege with which to launch your routine. You can also use launchd to launch a privileged helper. By factoring your application into privileged and unprivileged processes, you can limit the amount of code running as the root user (and thus the potential attack surface). Be sure that you do not request higher privilege than you actually need, and always drop privilege or quit execution as soon as possible. There are several reasons to use launchd in preference to writing a daemon running as the root user or a factored application that forks off a privileged process: ● Because launchd launches daemons on demand, your daemon needs not worry about whether other services are available yet. When it makes a request for one of those services, the service gets started automatically in a manner that is transparent to your daemon. ● Because launchd itself runs as the root user, if your only reason for using a privileged process is to run a daemon on a low-numbered port, you can let launchd open that port on your daemon’s behalf and pass the open socket to your daemon, thus eliminating the need for your code to run as the root user. ● Because launchd can launch a routine with elevated privileges, you do not have to set the setuid or setgid bits for the helper tool. Any routine that has the setuid or setgid bit set is likely to be a target for attack by malicious users. ● A privileged routine started by launchd runs in a controlled environment that can’t be tampered with. If you launch a helper tool that has the setuid bit set, it inherits much of the launching application’s environment, including: ● Open file descriptors (unless their close-on-exec flag is set). ● Environment variables (unless you use posix_spawn, posix_spawnp, or an exec variant that takes an explicit environment argument). ● Resource limits. ● The command-line arguments passed to it by the calling process. ● Anonymous shared memory regions (unattached, but available to reattach, if desired). ● Mach port rights. There are probably others. It is much safer to use launchd, which completely controls the launch environment. Elevating Privileges Safely Avoiding Forking Off a Privileged Process 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 66● It’s much easier to understand and verify the security of a protocol between your controlling application and a privileged daemon than to handle the interprocess communication needed for a process you forked yourself. When you fork a process, it inheritsits environment from your application, including file descriptors and environment variables, which might be used to attack the process (see “The Hostile Environment and the Principle of Least Privilege” (page 60)). You can avoid these problems by using launchd to launch a daemon. ● It’s easier to write a daemon and launch it with launchd than to write factored code and fork off a separate process. ● Because launchd is a critical system component, it receives a lot of peer review by in-house developers at Apple. It is less likely to contain security vulnerabilities than most production code. ● The launchd.plist file includes key-value pairs that you can use to limit the system services—such as memory, number of files, and cpu time—that the daemon can use. For more information on launchd, see the manual pages for launchd, launchctl, and launchd.plist, and Daemons and Services Programming Guide . For more information about startup items, see Daemons and Services Programming Guide . Limitations and Risks of Other Mechanisms In addition to launchd, the following lesser methods can be used to obtain elevated privileges. In each case, you must understand the limitations and risks posed by the method you choose. ● setuid If an executable's setuid bit is set, the program runs as whatever user owns the executable regardless of which process launches it. There are two approaches to using setuid to obtain root (or another user’s) privileges while minimizing risk: ● Launch your program with root privileges, perform whatever privileged operations are necessary immediately, and then permanently drop privileges. ● Launch a setuid helper tool that runs only as long as necessary and then quits. If the operation you are performing needs a group privilege or user privilege other than root, you should launch your program or helper tool with that privilege only, not with root privilege, to minimize the damage if the program is hijacked. It’s important to note that if you are running with both a group ID (GID) and user ID (UID) that are different from those of the user, you have to drop the GID before dropping the UID. Once you’ve changed the UID, you can no longer change the GID. As with every security-related operation, you must check the return values of your calls to setuid, setgid, and related routines to make sure they succeeded. Elevating Privileges Safely Limitations and Risks of Other Mechanisms 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 67For more information about the use of the setuid bit and related routines, see “Elevating Privileges Safely” (page 59). ● SystemStarter When you put an executable in the /Library/StartupItems directory, it is started by the SystemStarter program at boot time. Because SystemStarter runs with root privileges, you can start your program with any level of privilege you wish. Be sure to use the lowest privilege level that you can use to accomplish your task, and to drop privilege as soon as possible. Startup items run daemons with root privilege in a single global session; these processes serve all users. For OS X v10.4 and later, the use of startup items is deprecated; use the launchd daemon instead. For more information on startup items and startup item privileges,see “Startup Items” in Daemons and Services Programming Guide . ● AuthorizationExecWithPrivilege The Authorization Services API provides the AuthorizationExecWithPrivilege function, which launches a privileged helper as the root user. Although this function can execute any process temporarily with root privileges, it is not recommended except for installersthat have to be able to run from CDs and self-repairing setuid tools. See Authorization Services Programming Guide for more information. ● xinetd In earlier versions of OS X, the xinetd daemon was launched with root privileges at system startup and subsequently launched internetservices daemons when they were needed. The xinetd.conf configuration file specified the UID and GID of each daemon started and the port to be used by each service. Starting with OS X v10.4, you should use launchd to perform the services formerly provided by xinetd. SeeDaemonsandServicesProgrammingGuide forinformation about convertingfromxinetdtolaunchd. See the manual pages for xinetd(8) and xinetd.conf(5) for more information about xinetd. ● Other If you are using some other method to obtain elevated privilege for your process, you should switch to one of the methods described here and follow the cautions described in this chapter and in “Elevating Privileges Safely” (page 59). Elevating Privileges Safely Limitations and Risks of Other Mechanisms 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 68Factoring Applications If you’ve read this far and you’re still convinced you need to factor your application into privileged and nonprivileged processes, this section provides some tips and sample code. In addition, see Authorization Services Programming Guide for more advice on the use of Authorization Services and the proper way to factor an application. As explained in the Authorization Services documentation, it is very important that you check the user’s rights to perform the privileged operation, both before and after launching your privileged helper tool. Your helper tool, owned by root and with the setuid bit set, has sufficient privileges to perform whatever task it has to do. However, if the user doesn’t have the rights to perform this task, you shouldn’t launch the tool and—if the tool gets launched anyway—the tool should quit without performing the task. Your nonprivileged process should first use Authorization Services to determine whether the user is authorized and to authenticate the user if necessary (this is called preauthorizing ; see Listing 5-1 (page 70)). Then launch your privileged process. The privileged process then should authorize the user again, before performing the task that requires elevated privileges; see Listing 5-2 (page 71). As soon as the task is complete, the privileged process should terminate. In determining whether a user has sufficient privileges to perform a task, you should use rights that you have defined and put into the policy database yourself. If you use a right provided by the system or by some other developer, the user might be granted authorization for that right by some other process, thus gaining privileges to your application or access to data that you did not authorize or intend. For more information about policies and the policy database, (see the section “The Policy Database” in the “Authorization Concepts” chapter of Authorization Services Programming Guide ). In the code samples shown here, the task that requires privilege is killing a process that the user does not own. Example: Preauthorizing If a user tries to kill a process that he doesn’t own, the application has to make sure the user is authorized to do so. The following numbered items correspond to comments in the code sample: 1. If the process is owned by the user, and the process is not the window server or the login window, go ahead and kill it. 2. Call the permitWithRight method to determine whether the user has the right to kill the process. The application must have previously added this right—in this example, called com.apple.processkiller.kill—to the policy database. The permitWithRight method handles the interaction with the user (such as an authentication dialog). If this method returns 0, it completed without an error and the user is considered preauthorized. 3. Obtain the authorization reference. 4. Create an external form of the authorization reference. 5. Create a data object containing the external authorization reference. Elevating Privileges Safely Factoring Applications 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 696. Pass this serialized authorization reference to the setuid tool that will kill the process (Listing 5-2 (page 71)). Listing 5-1 Non-privileged process if (ownerUID == _my_uid && ![[contextInfo processName] isEqualToString:@"WindowServer"] && ![[contextInfo processName] isEqualToString:@"loginwindow"]) { [self killPid:pid withSignal:signal]; // 1 } else { SFAuthorization *auth = [SFAuthorization authorization]; if (![auth permitWithRight:"com.apple.proccesskiller.kill" flags: kAuthorizationFlagDefaults|kAuthorizationFlagInteractionAllowed| kAuthorizationFlagExtendRights|kAuthorizationFlagPreAuthorize]) // 2 { AuthorizationRef authRef = [auth authorizationRef]; // 3 AuthorizationExternalForm authExtForm; OSStatus status = AuthorizationMakeExternalForm(authRef, &authExtForm);// 4 if (errAuthorizationSuccess == status) { NSData *authData = [NSData dataWithBytes: authExtForm.bytes length: kAuthorizationExternalFormLength]; // 5 [_agent killProcess:pid signal:signal authData: authData]; // 6 } } } The external tool is owned by root and has its setuid bit set so that it runs with root privileges. It imports the externalized authorization rights and checks the user’s authorization rights again. If the user has the rights, the tool killsthe process and quits. The following numbered items correspond to commentsin the code sample: 1. Convert the external authorization reference to an authorization reference. 2. Create an authorization item array. 3. Create an authorization rights set. Elevating Privileges Safely Factoring Applications 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 704. Call the AuthorizationCopyRights function to determine whether the user has the right to kill the process. You pass this function the authorization reference. If the credentials issued by the Security Server when it authenticated the user have not yet expired, this function can determine whether the user is authorized to kill the process without reauthentication. If the credentials have expired, the Security Server handles the authentication (for example, by displaying a password dialog). (You specify the expiration period for the credentials when you add the authorization right to the policy database.) 5. If the user is authorized to do so, kill the process. 6. If the user is not authorized to kill the process, log the unsuccessful attempt. 7. Release the authorization reference. Listing 5-2 Privileged process AuthorizationRef authRef = NULL; OSStatus status = AuthorizationCreateFromExternalForm( (AuthorizationExternalForm *)[authData bytes], &authRef); // 1 if ((errAuthorizationSuccess == status) && (NULL != authRef)) { AuthorizationItem right = {"com.apple.proccesskiller.kill", 0L, NULL, 0L}; // 2 AuthorizationItemSet rights = {1, &right}; // 3 status = AuthorizationCopyRights(authRef, &rights, NULL, kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights, NULL); // 4 if (errAuthorizationSuccess == status) kill(pid, signal); // 5 else NSLog(@"Unauthorized attempt to signal process %d with %d", pid, signal); // 6 AuthorizationFree(authRef, kAuthorizationFlagDefaults); // 7 } Helper Tool Cautions If you write a privileged helper tool, you need to be very careful to examine your assumptions. For example, you should always check the results of function calls; it is dangerousto assume they succeeded and to proceed on that assumption. You must be careful to avoid any of the pitfalls discussed in this document, such as buffer overflows and race conditions. Elevating Privileges Safely Factoring Applications 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 71If possible, avoid linking in any extra libraries. If you do have to link in a library, you must not only be sure that the library has no security vulnerabilities, but also that it doesn’t link in any other libraries. Any dependencies on other code potentially open your code to attack. In order to make your helper tool as secure as possible, you should make it as short as possible—have it do only the very minimum necessary and then quit. Keeping it short makes it less likely that you made mistakes, and makes it easier for others to audit your code. Be sure to get a security review from someone who did not help write the tool originally. An independent reviewer is less likely to share your assumptions and more likely to spot vulnerabilities that you missed. Authorization and Trust Policies In addition to the basic permissions provided by BSD, the OS X Authorization Services API enables you to use the policy database to determine whether an entity should have access to specific features or data within your application. Authorization Services includes functions to read, add, edit, and delete policy database items. You should define your own trust policies and put them in the policy database. If you use a policy provided by the system or by some other developer, the user might be granted authorization for a right by some other process, thus gaining privileges to your application or access to data that you did not authorize or intend. Define a different policy for each operation to avoid having to give broad permissions to users who need only narrow privileges. For more information about policies and the policy database, see the section “The Policy Database” in the “Authorization Concepts” chapter of Authorization Services Programming Guide . Authorization Services does not enforce access controls; rather, it authenticates users and lets you know whether they have permission to carry out the action they wish to perform. It is up to your program to either deny the action or carry it out. Security in a KEXT Because kernel extensions have no user interface, you cannot call Authorization Servicesto obtain permissions that you do not already have. However, in portions of your code that handle requests from user space, you can determine what permissions the calling process has, and you can evaluate access control lists (ACLs; see the section “ACLs” in the “Security Concepts” section of Security Overview). In OS X v10.4 and later, you can also use the Kernel Authorization (Kauth) subsystem to manage authorization. For more information on Kauth, see Technical Note TN2127, Kernel Authorization (http://developer.apple.com/technotes/tn2005/tn2127.html). Elevating Privileges Safely Authorization and Trust Policies 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 72The user is often the weak link in the security of a system. Many security breaches have been caused by weak passwords, unencrypted filesleft on unprotected computers, and successfulsocial engineering attacks. Therefore, it is vitally important that your program’s user interface enhance security by making it easy for the user to make secure choices and avoid costly mistakes. In a social engineering attack, the user is tricked into either divulging secret information or running malicious code. For example, the Melissa virus and the Love Letter worm each infected thousands of computers when users downloaded and opened files sent in email. This chapter discusses how doing things that are contrary to user expectations can cause a security risk, and gives hints for creating a user interface that minimizes the risk from social engineering attacks. Secure human interface design is a complex topic affecting operating systems as well as individual programs. This chapter gives only a few hints and highlights. For an extensive discussion of this topic, see Cranor and Garfinkel, Security and Usability: Designing Secure Systems that People Can Use , O’Reilly, 2005. There is also an interesting weblog on this subject maintained by researchers at the University of California at Berkeley (http://usablesecurity.com/). Use Secure Defaults Most users use an application’s default settings and assume that they are secure. If they have to make specific choices and take multiple actions in order to make a program secure, few will do so. Therefore, the default settings for your program should be as secure as possible. For example: ● If your program launches other programs, it should launch them with the minimum privileges they need to run. ● If your program supports optionally connecting by SSL, the checkbox should be checked by default. ● If your program displays a user interface that requires the user to decide whether to perform a potentially dangerous action, the default option should be the safe choice. If there is no safe choice, there should be no default. (See “UI Element Guidelines: Controls” in OS X Human Interface Guidelines.) And so on. 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 73 Designing Secure User InterfacesThere is a common belief that security and convenience are incompatible. With careful design, this does not have to be so. In fact, it is very important that the user not have to sacrifice convenience for security, because many users will choose convenience in thatsituation. In many cases, a simpler interface is more secure, because the user is less likely to ignore security features and less likely to make mistakes. Whenever possible, you should make security decisions for your users: in most cases, you know more about security than they do, and if you can’t evaluate the evidence to determine which choice is most secure, the chances are your users will not be able to do so either. For a detailed discussion of this issue and a case study, see the article “Firefox and the Worry-Free Web” in Cranor and Garfinkel, Security and Usability: Designing Secure Systems that People Can Use . Meet Users’ Expectations for Security If your program handles data that the user expects to be kept secret, make sure that you protect that data at all times. That means not only keeping it in a secure location or encrypting it on the user’s computer, but not handing it off to another program unless you can verify that the other program will protect the data, and not transmitting it over an insecure network. If for some reason you cannot keep the data secure, you should make this situation obvious to users and give them the option of canceling the insecure operation. Important: The absence of an indication that an operation is secure is not a good way to inform the user that the operation is insecure. A common example of this is any web browser that adds a lock icon (usually small and inconspicuous) on web pages that are protected by SSL/TLS or some similar protocol. The user has to notice that this icon is not present (or that it’s in the wrong place, in the case of a spoofed web page) in order to take action. Instead, the program should prominently display some indication for each web page or operation that is not secure. The user must be made aware of when they are granting authorization to some entity to act on their behalf or to gain access to their files or data. For example, a program might allow users to share files with other users on remote systems in order to allow collaboration. In this case, sharing should be off by default. If the user turns it on, the interface should make clear the extent to which remote users can read from and write to files on the local system. If turning on sharing for one file also lets remote users read any other file in the same folder, for example, the interface must make this clear before sharing is turned on. In addition, as long as sharing is on, there should be some clear indication that it is on, lest users forget that their files are accessible by others. Designing Secure User Interfaces Meet Users’ Expectations for Security 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 74Authorization should be revocable: if a user grants authorization to someone, the user generally expects to be able to revoke that authorization later. Whenever possible, your program should not only make this possible, it should make it easy to do. If for some reason it will not be possible to revoke the authorization, you should make that clear before granting the authorization. You should also make it clear that revoking authorization cannot reverse damage already done (unless your program provides a restore capability). Similarly, any other operation that affects security but that cannot be undone should either not be allowed or the user should be made aware of the situation before they act. For example, if all files are backed up in a central database and can’t be deleted by the user, the user should be aware of that fact before they record information that they might want to delete later. As the user’s agent, you must carefully avoid performing operations that the user does not expect or intend. For example, avoid automatically running code if it performsfunctionsthat the user has not explicitly authorized. Secure All Interfaces Some programs have multiple user interfaces, such as a graphical user interface, a command-line interface, and an interface for remote access. If any of these interfaces require authentication (such as with a password), then all the interfaces should require it. Furthermore, if you require authentication through a command line or remote interface, be sure the authentication mechanism is secure—don’t transmit passwords in cleartext, for example. Place Files in Secure Locations Unless you are encrypting all output, the location where you save files has important security implications. For example: ● FileVault can secure the root volume (or the user’s home folder prior to OS X v10.7), but not other locations where the user might choose to place files. ● Folder permissions can be set in such a way that others can manipulate their contents. You should restrict the locations where users can save files if they contain information that must be protected. If you allow the user to select the location to save files, you should make the security implications of a particular choice clear; specifically, they must understand that, depending on the location of a file, it might be accessible to other applications or even remote users. Designing Secure User Interfaces Secure All Interfaces 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 75Make Security Choices Clear Most programs, upon detecting a problem or discrepancy, display a dialog box informing the user of the problem. Often this approach does not work, however. For one thing, the user might not understand the warning or its implications. For example, if the dialog warns the user that the site to which they are connecting has a certificate whose name does not match the name of the site, the user is unlikely to know what to do with that information, and is likely to ignore it. Furthermore, if the program puts up more than a few dialog boxes, the user is likely to ignore all of them. To solve this problem, when giving the user a choice that has security implications, make the potential consequences of each choice clear. The user should never be surprised by the results of an action. The choice given to the user should be expressed in terms of consequences and trade-offs, not technical details. For example, a choice of encryption methods should be based on the level of security (expressed in simple terms,such asthe amount of time it might take to break the encryption) versusthe time and disk space required to encrypt the data, rather than on the type of algorithm and the length of the key to be used. If there are no practical differences of importance to the user (as when the more secure encryption method is just as efficient as the less-secure method), just use the most secure method and don’t give the user the choice at all. Be sensitive to the fact that few users are security experts. Give as much information—in clear, nontechnical terms—as necessary for them to make an informed decision. In some cases, it might be best not to give them the option of changing the default behavior. For example, most users don’t know what a digital certificate is, let alone the implications of accepting a certificate signed by an unknown authority. Therefore, it is probably not a good idea to let the user permanently add an anchor certificate (a certificate that is trusted for signing other certificates) unless you can be confident that the user can evaluate the validity of the certificate. (Further, if the user is a security expert, they’ll know how to add an anchor certificate to the keychain without the help of your application anyway.) If you are providing security features, you should make their presence clear to the user. For example, if your mail application requires the user to double click a small icon in order to see the certificate used to sign a message, most users will never realize that the feature is available. In an often-quoted but rarely applied monograph, Jerome Saltzer and Michael Schroeder wrote “It is essential that the human interface be designed for ease of use, so that users routinely and automatically apply the protection mechanisms correctly. Also, to the extent that the user’s mental image of his protection goals matchesthe mechanisms he must use, mistakes will be minimized. If he must translate hisimage of his protection needs into a radically different specification language, he will make errors.” (Saltzer and Schroeder, “The Protection of Information in Computer Systems,” Proceedings of the IEEE 63:9, 1975.) Designing Secure User Interfaces Make Security Choices Clear 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 76For example, you can assume the user understandsthat the data must be protected from unauthorized access; however, you cannot assume the user has any knowledge of encryption schemes or knows how to evaluate password strength. In this case, your program should present the user with choices like the following: ● “Is your computer physically secure, or is it possible that an unauthorized user will have physical access to the computer?” ● “Is your computer connected to a network?” From the user’s answers, you can determine how best to protect the data. Unless you are providing an “expert” mode, do not ask the user questions like the following: ● “Do you want to encrypt your data, and if so, with which encryption scheme?” ● “How long a key should be used?” ● “Do you want to permit SSH access to your computer?” These questions don’t correspond with the user’s view of the problem. Therefore, the user’s answers to such questions are likely to be erroneous. In this regard, it is very important to understand the user’s perspective. Very rarely is an interface thatseemssimple or intuitive to a programmer actually simple or intuitive to average users. To quote Ka-Ping Yee (User Interaction Design for Secure Systems, at http://www.eecs.berkeley.edu/Pubs/TechRpts/2002/CSD-02-1184.pdf): In order to have a chance of using a system safely in a world of unreliable and sometimes adversarial software, a user needs to have confidence in all of the following statements: ● Things don’t become unsafe all by themselves. (Explicit Authorization) ● I can know whether things are safe. (Visibility) ● I can make things safer. (Revocability) ● I don’t choose to make things unsafe. (Path of Least Resistance) ● I know what I can do within the system. (Expected Ability) ● I can distinguish the things that matter to me. (Appropriate Boundaries) ● I can tell the system what I want. (Expressiveness) ● I know what I’m telling the system to do. (Clarity) ● The system protects me from being fooled. (Identifiability, Trusted Path) For additional tips, read “Dialogs” in OS X Human Interface Guidelines and “Alerts, Action Sheets, and Modal Views” in iOS Human Interface Guidelines. Designing Secure User Interfaces Make Security Choices Clear 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 77Fight Social Engineering Attacks Social engineering attacks are particularly difficult to fight. In a social engineering attack, the attacker fools the user into executing attack code or giving up private information. A common form of social engineering attack is referred to as phishing . Phishing refers to the creation of an official-looking email or web page that fools the user into thinking they are dealing with an entity with which they are familiar,such as a bank with which they have an account. Typically, the user receives an email informing them that there is something wrong with their account, and instructing them to click on a link in the email. The link takes them to a web page that spoofs a real one; that is, it includes icons, wording, and graphical elements that echo those the user is used to seeing on a legitimate web page. The user is instructed to enter such information as their social security number and password. Having done so, the user has given up enough information to allow the attacker to access the user’s account. Fighting phishing and other social engineering attacks is difficult because the computer’s perception of an email or web page is fundamentally different from that of the user. For example, consider an email containing a link to http://scamsite.example.com/ but in which the link’s text says Apple Web Store. From the computer’s perspective, the URL links to a scam site, but from the user’s perspective, it links to Apple’s online store. The user cannot easily tell that the link does not lead to the location they expect until they see the URL in their browser; the computer similarly cannot determine that the link’s text is misleading. To further complicate matters, even when the user looks at the actual URL, the computer and user may perceive the URL differently. The Unicode characterset includes many charactersthat look similar or identical to common English letters. For example, the Russian glyph that is pronounced like “r” looks exactly like an English “p” in many fonts, though it has a different Unicode value. These characters are referred to as homographs. When web browsers began to support internationalized domain names (IDN), some phishers set up websites that looked identical to legitimate ones, using homographs in their web addresses to fool users into thinking the URL was correct. Some creative techniques have been tried for fighting social engineering attacks, including trying to recognize URLsthat are similar to, but not the same as, well-known URLs, using private email channelsfor communications with customers, using emailsigning, and allowing usersto see messages only if they come from known, trusted sources. All of these techniques have problems, and the sophistication ofsocial engineering attacksisincreasing all the time. For example, to foil the domain name homograph attack, many browsers display internationalized domain names IDN) in an ASCII format called “Punycode.” For example, an impostor website with the URL http://www.apple.com/ that uses a Roman script for all the characters except for the letter “a”, for which it uses a Cyrillic character, is displayed as http://www.xn--pple-43d.com. Designing Secure User Interfaces Fight Social Engineering Attacks 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 78Different browsers use different schemes when deciding which internationalized domain names to show and which ones to translate. For example, Safari uses this form when a URL contains characters in two or more scripts that are not allowed in the same URL, such as Cyrillic characters and traditional ASCII characters. Other browsers consider whether the characterset is appropriate for the user’s default language. Still others maintain a whitelist of registries that actively prevent such spoofing and use punycode for domains from all other registries. For a more in-depth analysis of the problem, more suggested approaches to fighting it, and some case studies, see Security and Usability: Designing Secure Systems that People Can Use by Cranor and Garfinkel. To learn more aboutsocial engineering techniquesin general, read The Art of Deception: Controlling the Human Element of Security by Mitnick, Simon, and Wozniak. Use Security APIs When Possible One way to avoid adding security vulnerabilities to your code is to use the available security APIs whenever possible. The Security Interface Framework API provides a number of user interface viewsto support commonly performed security tasks. iOS Note: The Security Interface Framework is not available in iOS. In iOS, applications are restricted in their use of the keychain, and it is not necessary for the user to create a new keychain or change keychain settings. The Security Interface Framework API provides the following views: ● TheSFAuthorizationView class implements an authorization view in a window. An authorization view is a lock icon and accompanying text that indicates whether an operation can be performed. When the user clicks a closed lock icon, an authorization dialog displays. Once the user is authorized, the lock icon appears open. When the user clicksthe open lock, Authorization Servicesrestricts access again and changes the icon to the closed state. ● The SFCertificateView and SFCertificatePanel classes display the contents of a certificate. ● The SFCertificateTrustPanel class displays and optionally lets the user edit the trust settings in a certificate. ● The SFChooseIdentityPanel class displays a list of identities in the system and lets the user select one. (In this context, identity refers to the combination of a private key and its associated certificate.) ● The SFKeychainSavePanel class adds an interface to an application that lets the user save a new keychain. The user interface is nearly identical to that used for saving a file. The difference is that this class returns a keychain in addition to a filename and lets the user specify a password for the keychain. Designing Secure User Interfaces Use Security APIs When Possible 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 79● The SFKeychainSettingsPanel class displays an interface that lets the user change keychain settings. Documentation for the Security Interface framework is in Security Interface Framework Reference . Designing Secure User Interfaces Use Security APIs When Possible 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 80Privilege separation is a common technique for making applications more secure. By breaking up an application into functional units that each require fewer privileges, you can make it harder to do anything useful with any single part of that application if someone successfully compromises it. However, without proper design, a privilege-separated app is not significantly more secure than a non-privilege-separated app. For proper security, each part of the app must treat other parts of the app as untrusted and potentially hostile. To that end, this chapter provides dos and don’ts for designing a helper app. There are two different ways that you can perform privilege separation: ● Creating a pure computation helper to isolate risky operations. Thistechnique requiresthe main application to be inherently suspicious of any data that the helper returns, but does not require that the helper be suspicious of the application. ● Creating a helper or daemon to perform tasks without granting the application the right to perform them. This requires not only that the main application not trust the helper, but also that the helper not trust the main application. The techniques used for securing the two types of helpers differ only in the level of paranoia required by the helper. Avoid Puppeteering When a helper application is so tightly controlled by the main application that it does not make any decisions by itself, thisis called puppeteering. Thisisinherently bad design because if the application gets compromised, the attacker can then control the helper similarly, in effect taking over pulling the helper’s “strings”. This completely destroys the privilege separation boundary. Therefore, unless you are creating a pure computation helper, splitting code into a helper application that simply does whatever the main app tells it to do is usually not a useful division of labor. In general, a helper must be responsible for deciding whether or not to perform a particular action. If you look at the actions that an application can perform with and without privilege separation, those lists should be different; if they are not, then you are not gaining anything by separating the functionality out into a separate helper. 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 81 Designing Secure Helpers and DaemonsFor example, consider a helper that downloads help content for a word processor. If the helper fetches any arbitrary URL that the word processor sends it, the helper can be trivially exploited to send arbitrary data to an arbitrary server. For example, an attacker who took control of the browser could tell the helper to access the URL http://badguy.example.com/saveData?hereIsAnEncodedCopyOfTheUser%27sData. The subsections that follow describe solutions for this problem. Use Whitelists One way to fix this is with whitelists. The helper should include a specific list of resources that it can access. For example, this helper could include: ● A host whitelist that includes only the domain example.org. Requests to URLs in that domain would succeed, but the attacker could not cause the helper to access URLs in a different domain. ● An allowed path prefix whitelist. The attacker would not be able to use cross-site scripting on the example.org bulletin board to redirect the request to another location. (This applies mainly to apps using a web UI.) You can also avoid this by handling redirection manually. ● An allowed file type whitelist. This could limit the helper to the expected types of files. (Note that file type whitelists are more interesting for helpers that access files on the local hard drive.) ● A whitelist of specific URIs to which GET or POST operations are allowed. Use Abstract Identifiers and Structures A second way to avoid puppeteering is by abstracting away the details of the request itself, using data structures and abstract identifiers instead of providing URIs, queries, and paths. A trivial example of thisis a help system. Instead of the app passing a fully-formed URI for a help search request, it might pass a flag field whose value tells the helper to “search by name” or “search by title” and a string value containing the search string. This flag field is an example of an abstract identifier; it tells the helper what to do without telling it how to do it. Taken one step further, when the helper returns a list of search results, instead of returning the names and URIs for the result pages, it could return the names and an opaque identifier (which may be an index into the last set of search results). By doing so, the application cannot access arbitrary URIs because it never interacts with the actual URIs directly. Similarly, if you have an application that works with project files that reference other files, in the absence of API to directly support this, you can use a temporary exception to give a helper access to all files on the disk. To make this more secure, the helpershould provide access only to filesthat actually appear in the user-opened Designing Secure Helpers and Daemons Avoid Puppeteering 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 82project. The helper might do this by requiring the application to request files by some arbitrary identifier generated by the helper rather than by name or path. This makes it harder for the application to ask the helper to open arbitrary files. This can further be augmented with sniffing, as described in “Use the Smell Test” (page 83). The same concept can be extended to other areas. For example, if the application needs to change a record in a database, the helper could send the record as a data structure, and the app could send back the altered data structure along with an indication of which values need to change. The helper could then verify the correctness of the unaltered data before modifying the remaining data. Passing the data abstractly also allows the helper to limit the application’s access to other database tables. It also allows the helper to limit what kinds of queries the application can perform in ways that are more fine-grained than would be possible with the permissions system that most databases provide. Use the Smell Test If a helper application has access to files that the main application cannot access directly, and if the main application asks the helper to retrieve the contents of that file, it is useful for the helper to perform tests on the file before sending the data to ensure that the main application has not substituted a symbolic link to a different file. In particular, it is useful to compare the file extension with the actual contents of the file to see whether the bytes on disk make sense for the apparent file type. This technique is called file type sniffing. For example, the first few bytes of any image file usually provide enough information to determine the file type. If the first four bytes are JFIF, the file is probably a JPEG image file. If the first four bytes are GIF8, the file is probably a GIF image file. If the first four bytes are MM.* or II*., the file is probably a TIFF file. And so on. If the request passes this smell test, then the odds are good that the request is not malicious. Treat Both App and Helper as Hostile Because the entire purpose of privilege separation is to prevent an attacker from being able to do anything useful after compromising one part of an application, both the helper and the app must assume that the other party is potentially hostile. This means each piece must: ● Avoid buffer overflows (“Avoiding Buffer Overflows And Underflows” (page 17)). ● Validate all input from the other side (“Validating Input And Interprocess Communication” (page 33)). ● Avoid insecure interprocess communication mechanisms (“Validating Input And Interprocess Communication” (page 33)) ● Avoid race conditions (“Avoiding Race Conditions” (page 43)). Designing Secure Helpers and Daemons Treat Both App and Helper as Hostile 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 83● Treat the contents of any directory or file to which the other process has write access as fundamentally untrusted (“Securing File Operations” (page 47)). This list potentially includes: ● The entire app container directory. ● Preference files. ● Temporary files. ● User files. And so on. If you follow these design principles, you will make it harder for an attacker to do anything useful if he or she compromises your app. Run Daemons as Unique Users For daemonsthatstart with elevated privileges and then drop privileges, you should always use a locally unique user ID for your program. If you use some standard UID such as _unknown or nobody, then any other process running with thatsame UID can interact with your program, either directly through interprocess communication, or indirectly by altering configuration files. Thus, if someone hijacks another daemon on the same server, they can then interfere with your daemon; or, conversely, ifsomeone hijacks your daemon, they can use it to interfere with other daemons on the server. You can use Open Directory services to obtain a locally unique UID. Note that UIDs from 0 through 500 are reserved for use by the system. Note: You should generally avoid making security decisions based on the user’s ID or name for two reasons: ● Many APIs for determining the user ID and user name are inherently untrustworthy because they return the value of the USER. ● Someone could trivially make a copy of your app and change the string to a different value, then run the app. Start Other Processes Safely When it comes to security, not all APIs for running external tools are created equal. In particular: Avoid the POSIX system(3) function. Its simplicity makes it a tempting choice, but also makes it much more dangerous than other functions. When you use system, you become responsible for completely sanitizing the entire command, which means protecting any characters that are treated as special by the shell. You are Designing Secure Helpers and Daemons Run Daemons as Unique Users 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 84responsible for understanding and correctly using the shell’s quoting rules, knowing which characters are interpreted within each type of quotation marks, and so on. This is no small feat even for expert shell script programmers, and is strongly inadvisable for everyone else. Bluntly put, you will get it wrong. Set up your own environment correctly ahead of time. Many APIs search for the tool you want to run in locations specified by the PATH environment variable. If an attacker can modify that variable, the attacker can potentially trick your app into starting a different tool and running it as the current user. You can avoid this problem by either explicitly setting the PATH environment variable yourself or by avoiding variants of exec(3) or posix_spawn(2) that use the PATH environment variable to search for executables. Use absolute paths where possible, or relative paths if absolute paths are not available. By explicitly specifying a path to an executable rather than just its name, the PATH environment variable is not consulted when the OS determines which tool to run. For more information about environment variables and shell special characters, read Shell Scripting Primer. Designing Secure Helpers and Daemons Start Other Processes Safely 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 85This appendix presents a set of security audit checklists that you can use to help reduce the security vulnerabilities of your software. These checklists are designed to be used during software development. If you read this section all the way through before you start coding, you may avoid many security pitfalls that are difficult to correct in a completed program. Note that these checklists are not exhaustive; you might not have any of the potential vulnerabilities discussed here and still have insecure code. Also, as the author of the code, you are probably too close to the code to be fully objective, and thus may overlook certain flaws. For this reason, it’s very important that you have your code reviewed for security problems by an independent reviewer. A security expert would be best, but any competent programmer, if aware of what to look for, might find problems that you may have missed. In addition, whenever the code is updated or changed in any way, including to fix bugs, it should be checked again for security problems. Important: All code should have a security audit before being released. Use of Privilege This checklist is intended to determine whether your code ever runs with elevated privileges, and if it does, how best to do so safely. Note that it’s best to avoid running with elevated privileges if possible; see “Avoiding Elevated Privileges” (page 63). 1. Reduce privileges whenever possible. If you are using privilege separation with sandboxing or other privilege-limiting techniques, you should be careful to ensure that your helper tools are designed to limit the damage that they can cause if the main application gets compromised, and vice-versa. Read “Designing Secure Helpers And Daemons” (page 81) to learn how. Also, for daemons that start with elevated privileges and then drop privileges, you should always use a locally unique user ID for your program. See “Run Daemons As Unique Users” (page 84) to learn more. 2. Use elevated privileges sparingly, and only in privileged helpers. In most cases, a program can get by without elevated privileges, butsometimes a program needs elevated privileges to perform a limited number of operations, such as writing files to a privileged directory or opening a privileged port. 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 86 Security Development ChecklistsIf an attacker finds a vulnerability that allows execution of arbitrary code, the attacker’s code runs with the same privilege as the running code, and can take complete control of the computer if that code has root privileges. Because of this risk, you should avoid elevating privileges if at all possible. If you must run code with elevated privileges, here are some rules: ● Never run your main process as a different user. Instead, create a separate helper tool that runs with elevated privileges. ● Your helper tool should do as little as possible. ● Your helper tool should restrict what you can ask it to do as much as possible. ● Your helper tool should either drop the elevated privileges or stop executing as soon as possible. Important: If all or most of your code runs with root or other elevated privileges, or if you have complex code that performs multiple operations with elevated privileges, then your program could have a serious security vulnerability. You should seek help in performing a security audit of your code to reduce your risk. See “Elevating Privileges Safely” (page 59) and “Designing Secure Helpers And Daemons” (page 81) for more information. 3. Use launchd when possible. If you are writing a daemon or other process that runs with elevated privileges, you should always use launchd to start it. (To learn why other mechanisms are not recommended, read “Limitations And Risks Of Other Mechanisms” (page 67).) For more information on launchd,see the manual pagesfor launchd, launchctl, and launchd.plist, and Daemons and Services Programming Guide . For more information about startup items, see Daemons and Services Programming Guide . For more information on ipfw, see the ipfw manual page. 4. Avoid using sudo programmatically. If authorized to do so in the sudoers file, a user can use sudo to execute a command as root. The sudo command is intended for occasional administrative use by a user sitting at the computer and typing into the Terminal application. Its use in scripts or called from code is not secure. After executing the sudo command—which requires authenticating by entering a password—there is a five-minute period (by default) during which the sudo command can be executed without further authentication. It’s possible for another process to take advantage of this situation to execute a command as root. Further, there is no encryption or protection of the command being executed. Because sudo is used to execute privileged commands, the command arguments often include user names, passwords, and other information that should be kept secret. A command executed in this way by a script or other code can expose confidential data to possible interception and compromise. Security Development Checklists Use of Privilege 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 875. Minimize the amount of code that must be run with elevated privileges. Ask yourself approximately how many lines of code need to run with elevated privileges. If this answer is either “all” or is a difficult number to compute, then it will be very difficult to perform a security review of your software. If you can’t determine how to factor your application to separate out the code that needs privileges, you are strongly encouraged to seek assistance with your project immediately. If you are an ADC member, you are encouraged to ask for help from Apple engineers with factoring your code and performing a security audit. If you are not an ADC member, see the ADC membership page at http://developer.apple.com/programs/. 6. Never run a GUI application with elevated privileges. You should never run a GUI application with elevated privileges. Any GUI application linksin many libraries over which you have no control and which, due to their size and complexity, are very likely to contain security vulnerabilities. In this case, your application runs in an environment set by the GUI, not by your code. Your code and your user’s data can then be compromised by the exploitation of any vulnerabilities in the libraries or environment of the graphical interface. Data, Configuration, and Temporary Files Some security vulnerabilities are related to reading or writing files. This checklist is intended to help you find any such vulnerabilities in your code. 1. Be careful when working with files in untrusted locations. If you write to any directory owned by the user, then there is a possibility that the user will modify or corrupt your files. Similarly, if you write temporary files to a publicly writable place (for example, /tmp, /var/tmp, /Library/Caches or another specific place with this characteristic), an attacker may be able to modify your files before the next time you read them. If your code reads and writes files (and in particular if it uses files for interprocess communication), you should put those files in a safe directory to which only you have write access. For more information about vulnerabilities associated with writing files, and how to minimize the risks, see “Time of Check Versus Time of Use” (page 44). 2. Avoid untrusted configuration files, preference files, or environment variables. In many cases, the user can control environment variables, configuration files, and preferences. If you are executing a program for the user with elevated privileges, you are giving the user the opportunity to perform operations that they cannot ordinarily do. Therefore, you should ensure that the behavior of your privileged code does not depend on these things. Security Development Checklists Data, Configuration, and Temporary Files 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 88This means: ● Validate all input, whether directly from the user or through environment variables, configuration files, preferences files, or other files. In the case of environment variables, the effect might not be immediate or obvious; however the user might be able to modify the behavior of your program or of other programs or system calls. ● Make sure that file paths do not contain wildcard characters, such as ../ or ~, which an attacker can use to switch the current directory to one under the attacker’s control. ● Explicitly set the privileges, environment variables, and resources available to the running process, rather than assuming that the process has inherited the correct environment. 3. Load kernel extensions carefully (or not at all). A kernel extension is the ultimate privileged code—it has access to levels of the operating system that cannot be touched by ordinary code, even running as root. You must be extremely careful why, how, and when you load a kernel extension to guard against being fooled into loading the wrong one. It’s possible to load a root kit if you’re notsufficiently careful. (A root kit is malicious code that, by running in the kernel, can not only take over control of the system but can cover up all evidence of its own existence.) To make sure that an attacker hasn’t somehow substituted his or her own kernel extension for yours, you should always store kernel extensions in secure locations. You may, if desired, use code signing or hashes to further verify their authenticity, but this does not remove the need to protect the extension with appropriate permissions. (Time-of-check vs. time-of-use attacks are still possible.) Note that in recent versions of OS X, this is partially mitigated by the KEXT loading system, which refuses to load any kext binary whose owner is not root or whose group is not wheel. In general, you should avoid writing kernel extensions (see “Keep Out” in Kernel Programming Guide ). However, if you must use a kernel extension, use the facilities built into OS X to load your extension and be sure to load the extension from a separate privileged process. See “Elevating Privileges Safely” (page 59) to learn more about the safe use of root access. See Kernel Programming Guide for more information on writing and loading kernel extensions. For help on writing device drivers, see I/O Kit Fundamentals. Network Port Use This checklist is intended to help you find vulnerabilities related to sending and receiving information over a network. If your project does not contain any tool or application that sends or receives information over a network, skip to “Audit Logs” (page 91) (for servers) or “Integer and Buffer Overflows” (page 97) for all other products. 1. Use assigned port numbers. Security Development Checklists Network Port Use 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 89Port numbers 0 through 1023 are reserved for use by certain services specified by the Internet Assigned Numbers Authority (IANA; see http://www.iana.org/). On many systems including OS X, only processes running asroot can bind to these ports. It is notsafe, however, to assume that any communications coming over these privileged ports can be trusted. It’s possible that an attacker has obtained root access and used it to bind to a privileged port. Furthermore, on some systems, root access is not needed to bind to these ports. You should also be aware that if you use the SO_REUSEADDR socket option with UDP, it is possible for a local attacker to hijack your port. Therefore, you should always use port numbers assigned by the IANA, you should always check return codes to make sure you have connected successfully, and you should check that you are connected to the correct port. Also, as always, never trust input data, even if it’s coming over a privileged port. Whether data is being read from a file, entered by a user, or received over a network, you must validate all input. See “Validating Input And Interprocess Communication” (page 33) for more information about validating input. 2. Choose an appropriate transport protocol. Lower-level protocols, such as UDP, provide higher performance for some types of traffic, but are easier to spoof than higher-level protocols, such as TCP. Note that if you’re using TCP, you still need to worry about authenticating both ends of the connection, but there are encryption layers you can add to increase security. 3. Use existing authentication services when authentication is needed. If you’re providing a free and nonconfidential service, and do not process user input, then authentication is not necessary. On the other hand, if any secret information is being exchanged, the user is allowed to enter data that your program processes, or there is any reason to restrict user access, then you should authenticate every user. OS X provides a variety of secure network APIs and authorization services, all of which perform authentication. You should always use these services rather than creating your own authentication mechanism. For one thing, authentication is very difficult to do correctly, and dangerous to get wrong. If an attacker breaks your authentication scheme, you could compromise secrets or give the attacker an entry to your system. The only approved authorization mechanism for networked applications is Kerberos; see “Client-Server Authentication” (page 93). For more information on secure networking, see Secure Transport Reference and CFNetwork Programming Guide . 4. Verify access programmatically. UI limitations do not protect your service from attack. If your service provides functionality that should only be accessible to certain users, that service must perform appropriate checks to determine whether the current user is authorized to access that functionality. Security Development Checklists Network Port Use 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 90If you do not do this, then someone sufficiently familiar with your service can potentially perform unauthorized operations by modifying URLs, sending malicious Apple events, and so on. 5. Fail gracefully. If a server is unavailable, either because of some problem with the network or because the server is under a denial of service attack, your client application should limit the frequency and number of retries and should give the user the opportunity to cancel the operation. Poorly-designed clientsthat retry connectionstoo frequently and too insistently, or that hang while waiting for a connection, can inadvertently contribute to—or cause their own—denial of service. 6. Design your service to handle high connection volume. Your daemon should be capable of surviving a denial of service attack without crashing or losing data. In addition, you should limit the total amount of processor time, memory, and disk space each daemon can use, so that a denial of service attack on any given daemon does not result in denial of service to every process on the system. You can use the ipfwfirewall program to control packets and traffic flow for internet daemons. For more information on ipfw, see the ipfw(8) manual page. See Wheeler, Secure Programming for Linux and Unix HOWTO, available at http://www.dwheeler.com/secure-programs/, for more advice on dealing with denial of service attacks. 7. Design hash functions carefully. Hash tables are often used to improve search performance. However, when there are hash collisions(where two items in the list have the same hash result), a slower (often linear) search must be used to resolve the conflict. If it is possible for a user to deliberately generate different requeststhat have the same hash result, by making many such requests an attacker can mount a denial of service attack. It is possible to design hash tables that use complex data structures such as trees in the collision case. Doing so can significantly reduce the damage caused by these attacks. Audit Logs It’s very important to audit attempts to connect to a server or to gain authorization to use a secure program. If someone is attempting to attack your program, you should know what they are doing and how they are doing it. Furthermore, if your program is attacked successfully, your audit log is the only way you can determine what happened and how extensive the security breach was. This checklist is intended to help you make sure you have an adequate logging mechanism in place. Security Development Checklists Audit Logs 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 91Important: Don’t log confidential data, such as passwords, which could then be read later by a malicious user. 1. Audit attempts to connect. Your daemon orsecure program should audit connection attempts(both successful attempts and failures). Note that an attacker can attempt to use the audit log itself to create a denial of service attack; therefore, you should limit the rate of entering audit messages and the total size of the log file. You also need to validate the input to the log itself, so that an attacker can’t enter special characters such as the newline character that you might misinterpret when reading the log. See Wheeler, Secure Programming for Linux and Unix HOWTO for some advice on audit logs. 2. Use the libbsm auditing library where possible. The libbsm auditing library is part of the TrustedBSD project, which in turn is a set of trusted extensions to the FreeBSD operating system. Apple has contributed to this project and has incorporated the audit library into the Darwin kernel of the OS X operating system. (This library is not available in iOS.) You can use the libbsm auditing library to implement auditing of your program for login and authorization attempts. This library gives you a lot of control over which events are audited and how to handle denial of service attacks. The libbsm project is located at http://www.opensource.apple.com/darwinsource/Current/bsm/. For documentation of the BSM service, see the “Auditing Topics” chapter in Sun Microsystems’ System Administration Guide: Security Services located at http://docs.sun.com/app/docs/doc/806- 4078/6jd6cjs67?a=view. 3. If you cannot use libbsm, be careful when writing audit trails. When using audit mechanisms other than libbsm, there are a number of pitfalls you should avoid, depending on what audit mechanism you are using: ● syslog Prior to the implementation of the libbsm auditing library, the standard C library function syslog was most commonly used to write data to a log file. If you are using syslog, consider switching to libbsm, which gives you more options to deal with denial of service attacks. If you want to stay with syslog, be sure your auditing code is resistant to denial of service attacks, as discussed in step 1. ● Custom log file If you have implemented your own custom logging service, consider switching to libbsm to avoid inadvertently creating a security vulnerability. In addition, if you use libbsm your code will be more easily maintainable and will benefit from future enhancements to the libbsm code. If you stick with your own custom logging service, you must make certain that it is resistant to denial of service attacks (see step 1) and that an attacker can’t tamper with the contents of the log file. Security Development Checklists Audit Logs 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 92Because your log file must be either encrypted or protected with access controlsto prevent tampering, you must also provide tools for reading and processing your log file. Finally, be sure your custom logging code is audited for security vulnerabilities. Client-Server Authentication If any private or secret information is passed between a daemon and a client process, both ends of the connection should be authenticated. This checklist is intended to help you determine whether your daemon’s authentication mechanism is safe and adequate. If you are not writing a daemon, skip to “Integer and Buffer Overflows” (page 97). 1. Do not store, validate, or modify passwords yourself. It’s a very bad idea to store, validate, or modify passwords yourself, as it’s very hard to do so securely, and OS X and iOS provide secure facilities for just that purpose. ● In OS X, you can use the keychain to store passwords and Authorization Services to create, modify, delete, and validate user passwords (see Keychain Services Programming Guide and Authorization Services Programming Guide ). ● In OS X, if you have access to an OS X Server setup, you can use Open Directory (see Open Directory Programming Guide ) to store passwords and authenticate users. ● On an iOS device, you can use the keychain to store passwords. iOS devices authenticate the application that is attempting to obtain a keychain item rather than asking the user for a password. By storing data in the keychain, you also ensure that they remain encrypted in any device backups. 2. Never send passwords over a network connection in cleartext form. You should never assume that an unencrypted network connection issecure. Information on an unencrypted network can be intercepted by any individual or organization between the client and the server. Even an intranet, which does not go outside of your company, is not secure. A large percentage of cyber crime is committed by company insiders, who can be assumed to have accessto a network inside a firewall. OS X provides APIs for secure network connections; see Secure Transport Reference and CFNetwork Programming Guide for details. 3. Use server authentication as an anti-spoofing measure. Although server authentication is optional in the SSL/TLS protocols, you should always do it. Otherwise, an attacker might spoof your server, injuring your users and damaging your reputation in the process. 4. Use reasonable pasword policies. ● Password strength Security Development Checklists Client-Server Authentication 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 93In general, it is better to provide the user with a meansto evaluate the strength of a proposed password rather than to require specific combinations of letters, numbers, or punctuation, as arbitrary rules tend to cause people to choose bad passwords to fit the standard (Firstname.123) instead of choosing good passwords. ● Password expiration Password expiration has pros and cons. If your service transmits passwords in cleartext form, it is absolutely essential. If your password transmission is considered secure, however, password expiration can actually weaken security by causing people to choose weaker passwords that they can remember or to write their passwords down on sticky notes on their monitors. See Password Expiration Considered Harmful for more information. ● Non-password authentication Hardware-token-based authentication providesfar more security than any password scheme because the correct response changes every time you use it. These tokens should always be combined with a PIN, and you should educate your users so that they do not write their username or PIN on the token itself. ● Disabled accounts When an employee leaves or a user closes an account, the accountshould be disabled so that it cannot be compromised by an attacker. The more active accounts you have, the greater the probability that one will have a weak password. ● Expired accounts Expiring unused accounts reduces the number of active accounts, and in so doing, reduces the risk of an old account getting compromised by someone stealing a password that the user has used for some other service. Note, however, that expiring a user account without warning the user first is generally a bad idea. If you do not have a means of contacting the user, expiring accounts are generally considered poor form. ● Changing passwords You can require that the client application support the ability to change passwords, or you can require that the user change the password using a web interface on the server itself. In either case, the user (or the client, on behalf of the user) must provide the previous password along with the new password (twice unless the client is updating it programmatically over a sufficiently robust channel). ● Lost password retrieval (such as a system that triggers the user’s memory or a series of questions designed to authenticate the user without a password) Security Development Checklists Client-Server Authentication 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 94Make sure your authentication method is not so insecure that an attacker doesn’t even bother to try a password, and be careful not to leak information, such as the correct length of the password, the email address to which the recovered password is sent, or whether the user ID is valid. You should always allow (and perhaps even require) customer to choose their own security questions. Pre-written questions are inherently dangerous because any question that is general enough for you to ask it of a large number of people is: ● likely to be a request for information that a large number of that person’s friends already know. In all likelihood, everyone who attended your high school can guess (in a handful of guesses) who your kindergarten teacher was, who your high school mascot was, and so on. ● probably on your public profile on a social networking site. For example, if you ask where you were born, chances are that’s public information. Even if it isn’t on your profile, someone can dig it up through government records. ● potentially guessable given other information about the person. For example, given the last four digits of a social security number, someone’s birthdate, and the city in which that person was born, you can fairly easily guess then entire social security number. Finally, you should always allow your users the option of not filing out security questions. The mere existence of security questions makes their accounts less secure, so security-conscious individuals should be allowed to refuse those questions entirely. ● Limitations on password length (adjustable by the system administrator) In general, you should require passwords to be at least eight characters in length. (As a side note, if yourserver limits passwordsto a maximum of eight characters, you need to rethink your design. There should be no maximum password length at all, if possible.) The more of these policies you enforce, the more secure your server will be. Rather than creating your own password database—which is difficult to do securely—you should use the Apple Password Server. See Open Directory Programming Guide for more information about the Password Server, Directory Service Framework Reference for a list of Directory Services functions, and the manual pages for pwpolicy(8), passwd(1), passwd(5), and getpwent(3) at http://developer.apple.com/documentation/Darwin/Reference/ManPages/index.html for tools to access the password database and set password policies. 5. Do not store unencrypted passwords and do not reissue passwords. In order to reissue a password, you first have to cache the unencrypted password, which is bad security practice. Furthermore, when you reissue a password, you might also be reusing that password in an inappropriate security context. For example, suppose your program is running on a web server, and you use SSL to communicate with clients. If you take a client’s password and use it to log into a database server to do something on the client’s behalf, there’s no way to guarantee that the database server keeps the password secure and does Security Development Checklists Client-Server Authentication 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 95not pass it on to another server in cleartext form. Therefore, even though the password was in a secure context when it was being sent to the web server over SSL, when the web server reissues it, it’s in an insecure context. If you want to spare your client the trouble of logging in separately to each server, you should use some kind of forwardable authentication, such as Kerberos. For more information on Apple’s implementation of Kerberos, see http://developer.apple.com/darwin/projects/kerberos/. Under no circumstances should you design a system in which system administrators or other employees can see users’ passwords. Your users are trusting you with passwords that they may use for other sites; therefore, it is extremely reckless to allow anyone else to see those passwords. Administrators should be allowed to reset passwords to new values, but should never be allowed to see the passwords that are already there. 6. Support Kerberos. Kerberos is the only authorization service available over a network for OS X servers, and it offers single-sign-on capabilities. If you are writing a server to run on OS X, you should support Kerberos. When you do: a. Be sure you’re using the latest version (v5). b. Use a service-specific principal, not a host principal. Each service that uses Kerberos should have its own principal so that compromise of one key does not compromise more than one service. If you use a host principal, anyone who has your host key can spoof login by anybody on the system. The only alternative to Kerberos is combining SSL/TLS authentication with some other means of authorization such as an access control list. 7. Restrict guest access appropriately. If you allow guest access, be sure that guests are restricted in what they can do, and that your user interface makes clear to the system administrator what guests can do. Guest access should be off by default. It’s best if the administrator can disable guest access. Also, as noted previously, be sure to limit what guests can do in the code that actually performs the operation, not just in the code that generates the user interface. Otherwise, someone with sufficient knowledge ofthe systemcan potentially performthose unauthorized operationsin other ways(bymodifying URLs, for example). 8. Do not implement your own directory service. Open Directory is the directory server provided by OS X for secure storage of passwords and user authentication. It is important that you use this service and not try to implement your own, as secure directory servers are difficult to implement and an entire directory’s passwords can be compromised if it’s done wrong. See Open Directory Programming Guide for more information. 9. Scrub (zero) user passwords from memory after validation. Security Development Checklists Client-Server Authentication 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 96Passwords must be kept in memory for the minimum amount of time possible and should be written over, not just released, when no longer needed. It is possible to read data out of memory even if the application no longer has pointers to it. Integer and Buffer Overflows As discussed in “Avoiding Buffer Overflows And Underflows” (page 17), buffer overflows are a major source of security vulnerabilities. This checklist is intended to help you identify and correct buffer overflows in your program. 1. Use unsigned values when calculating memory object offsets and sizes. Signed values make it easier for an attacker to cause a buffer overflow, creating a security vulnerability, especially if your application accepts signed values from user input or other outside sources. Be aware that data structures referenced in parameters might contain signed values. See “Avoiding Integer Overflows And Underflows” (page 27) and “Calculating Buffer Sizes” (page 25) for details. 2. Check for integer overflows (or signed integer underflows) when calculating memory object offsets and sizes. You must always check for integer overflows or underflows when calculating memory offsets or sizes. Integer overflows and underflows can corrupt memory in ways that can lead to execution of arbitrary code. See “Avoiding Integer Overflows And Underflows” (page 27) and “Calculating Buffer Sizes” (page 25) for details. 3. Avoid unsafe string-handling functions. The functions strcat, strcpy, strncat, strncpy, sprintf, vsprintf, gets have no built-in checks for string length, and can lead to buffer overflows. For alternatives, read “String Handling” (page 22). Cryptographic Function Use This checklist is intended to help you determine whether your program has any vulnerabilities related to use of encryption, cryptographic algorithms, or random number generation. 1. Use trusted random number generators. Do not attempt to generate your own random numbers. Security Development Checklists Integer and Buffer Overflows 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 97There are several ways to obtain high-quality random numbers: ● In iOS, use the Randomization Services programming interface. ● In OS X: ● Read from /dev/random in OS X (see the manual page for random). ● Use the read_random function in the header file random.h in the Apple CSP module, which is part of Apple’simplementation ofthe CDSA framework (available at http://developer.apple.com/darwin/projects/security/). Note that rand does not return good random numbers and should not be used. 2. Use TLS/SSL instead of custom schemes. You should always use accepted standard protocols for secure networking. These standards have gone through peer review and so are more likely to be secure. In addition, you should always use the most recent version of these protocols. To learn more about the secure networking protocols available in OS X and iOS, read “Secure Network Communication APIs” in Cryptographic Services Guide . 3. Don’t roll your own crypto algorithms. Always use existing optimized functions. It is very difficult to implement a secure cryptographic algorithm, and good, secure cryptographic functions are readily available. To learn about the cryptographic services available in OS X and iOS, read Cryptographic Services Guide . Installation and Loading Many security vulnerabilities are caused by problems with how programs are installed or code modules are loaded. This checklist is intended to help you find any such problems in your project. 1. Don’t install components in /Library/StartupItemsor/System/Library/Extensions. Code installed into these directories runs with root permissions. Therefore, it is very important that such programs be carefully audited forsecurity vulnerabilities(as discussed in this checklist) and that they have their permissions set correctly. For information on proper permissions for startup items, see “Startup Items”. (Note that in OS X v10.4 and later,startup items are deprecated; you should use launchd to launch your daemonsinstead. See Daemons and Services Programming Guide for more information.) For information on permissions for kernel extensions, see Kernel Extension Programming Topics. (Note that beginning in OS X v10.2, OS X checks for permissions problems and refuses to load extensions unless the permissions are correct.) Security Development Checklists Installation and Loading 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 982. Don’t use custom install scripts. Custom install scripts add unnecessary complexity and risk, so when possible, you should avoid them entirely. If you must use a custom install script, you should: ● If your installerscript runsin a shell, read and follow the advice in “Shell Script Security” in Shell Scripting Primer. ● Be sure that yourscript followsthe guidelinesin this checklist just asthe rest of your application does. In particular: ● Don’t write temporary files to globally writable directories. ● Don’t execute with higher privileges than necessary. In general, your script should execute with the same privileges the user has normally, and should do its work in the user’s directory on behalf of the user. ● Don’t execute with elevated privileges any longer than necessary. ● Set reasonable permissions on your installed app. For example, don’t give everyone read/write permission to files in the app bundle if only the owner needs such permission. ● Set your installer’s file code creation mask (umask) to restrict access to the files it creates (see “Securing File Operations” (page 47)). ● Check return codes, and if anything is wrong, log the problem and report the problem to the user through the user interface. For advice on writing installation code that needs to perform privileged operations, see Authorization Services Programming Guide . For more information about writing shell scripts, read Shell Scripting Primer. 3. Load plug-ins and libraries only from secure locations. An application should load plug-ins only from secure directories. If your application loads plug-ins from directories that are not restricted, then an attacker might be able to trick the user into downloading malicious code, which your application might then load and execute. Important: In code running with elevated privileges, directories writable by the user are not considered secure locations. Be aware that the dynamic link editor (dyld) might link in plugins, depending on the environment in which your code is running. If your code uses loadable bundles (CFBundle or NSBundle), then it is dynamically loading code and could potentially load bundles written by a malicious hacker. See Code Loading Programming Topics for more information about dynamically loaded code. Security Development Checklists Installation and Loading 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 99Use of External Tools and Libraries If your program includes or uses any command-line tools, you have to look for security vulnerabilities specific to the use of such tools. This checklist is intended to help you find and correct such vulnerabilities. 1. Execute tools safely. If you are using routines such as popen or system to send commands to the shell, and you are using input from the user or received over a network to construct the command, you should be aware that these routines do not validate their input. Consequently, a malicious user can pass shell metacharacters—such as an escape sequence or other special characters—in command line arguments. These metacharacters might cause the following text to be interpreted as a new command and executed. In addition, when calling functions such as execlp, execvp, popen, or system that use the PATH environment variable to search for executables, you should always specify a complete absolute path to any tool that you want to run. If you do not, a malicious attacker can potentially cause you to run a different tool using an environment variable attack. When possible, use execvP (which takes an explicit search path argument) or avoid these functions altogether. See Viega and McGraw, Building Secure Software , AddisonWesley, 2002, andWheeler, Secure Programming for Linux andUnixHOWTO, available at http://www.dwheeler.com/secure-programs/, formore information on problems with these and similar routines and for secure ways to execute shell commands. 2. Do not pass sensitive information on the command line. If your application executes command-line tools, keep in mind that your process environment is visible to other users (see man ps(1)). You must be careful not to pass sensitive information in an insecure manner. Instead, pass sensitive information to your tool through some other means such as: ● Pipe or standard input A password is safe while being passed through a pipe; however, you must be careful that the process sending the password obtains and stores it in a safe manner. ● Environment variables Environment variables can potentially be read by other processes and thus may not be secure. If you use environment variables, you must be careful to avoid passing them to any processes that your command-line tool or script might spawn. See “Shell Script Security” in Shell Scripting Primer for details. ● Shared memory Named and globally-shared memory segments can be read by other processes. See “Interprocess Communication And Networking” (page 40) for more information aboutsecure use ofshared memory. ● Temporary file Security Development Checklists Use of External Tools and Libraries 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 100Temporary files are safe only if kept in a directory to which only your program has access. See “Data, Configuration, and Temporary Files” (page 88), earlier in this chapter, for more information on temporary files. 3. Validate all arguments (including the name). Also, remember that anyone can execute a tool—it is not executable exclusively through your program. Because all command-line arguments, including the program name (argv(0)), are under the control of the user, your tool should validate every parameter (including the name, if the tool’s behavior depends on it). Kernel Security This checklist is intended to help you program safely in the kernel. Note: Coding in the kernel poses special security risks and is seldom necessary. See Coding in the Kernel for alternatives to writing kernel-level code. 1. Verify the authenticity of Mach-based services. Kernel-level code can work directly with the Mach component. A Mach port is an endpoint of a communication channel between a client who requests a service and a server that provides the service. Mach ports are unidirectional; a reply to a service request must use a second port. If you are using Mach ports for communication between processes, you should check to make sure you are contacting the correct process. Because Mach bootstrap ports can be inherited, it is important for servers and clients to authenticate each other. You can use audit trailers for this purpose. You should create an audit record for each security-related check your program performs. See “Audit Logs” (page 91), earlier in this chapter, for more information on audit records. 2. Verify the authenticity of other user-space services. If your kernel extension was designed to communicate with only a specific user-space daemon, you should check not only the name of the process, but also the owner and group to ensure that you are communicating with the correct process. 3. Handle buffers correctly. When copying data to and from user space, you must: a. Check the bounds of the data using unsigned arithmetic—just as you check all bounds (see “Integer and Buffer Overflows” (page 97), earlier in this chapter)—to avoid buffer overflows. b. Check for and handle misaligned buffers. c. Zero all pad data when copying to or from user-space memory. Security Development Checklists Kernel Security 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 101If you or the compiler adds padding to align a data structure in some way, you should zero the padding to make sure you are not adding spurious (or even malicious) data to the user-space buffer, and to make sure that you are not accidentally leaking sensitive information that may have been in that page of memory previously. 4. Limit the memory resources a user may request. If your code does not limit the memory resources a user may request, then a malicious user can mount a denial of service attack by requesting more memory than is available in the system. 5. Sanitize any kernel log messages. Kernel code often generates messages to the console for debugging purposes. If your code does this, be careful not to include any sensitive information in the messages. 6. Don’t log too much. The kernel logging service has a limited buffer size to thwart denial of service attacks against the kernel. This means that if your kernel code logs too frequently or too much, data can be dropped. If you need to log large quantities of data for debugging purposes, you should use a different mechanism, and you must disable that mechanism before deploying your kernel extension. If you do not, then your extension could become a denial-of-service attack vector. 7. Design hash functions carefully. Hash tables are often used to improve search performance. However, when there are hash collisions(where two items in the list have the same hash result), a slower (often linear) search must be used to resolve the conflict. If it is possible for a user to deliberately generate different requeststhat have the same hash result, by making many such requests an attacker can mount a denial of service attack. It is possible to design hash tables that use complex data structures such as trees in the collision case. Doing so can significantly reduce the damage caused by these attacks. Security Development Checklists Kernel Security 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 102This appendix provides secure coding guidelines for software to be bundled with Apple products. Insecure software can pose a risk to the overall security of users’ systems. Security issues can lead to negative publicity and end-user support problems for Apple and third parties. Respect Users’ Privacy Your bundled software may use the Internet to communicate with your servers or third party servers. If so, you should provide clear and concise information to the user about what information is sent or retrieved and the reason for sending or receiving it. Encryption should be used to protect the information while in transit. Servers should be authenticated before transferring information. Provide Upgrade Information Provide information on how to upgrade to the latest version. Consider implementing a “Check for updates…” feature. Customers expect (and should receive) security fixes that affect the software version they are running. You should have a way to communicate available security fixes to customers. If possible, you should use the Mac App Store for providing upgrades. The Mac App Store provides a single, standard interface for updating all of a user’s software. The Mac App Store also provides an expedited app review process for handling critical security fixes. Store Information in Appropriate Places Store user-specific information in the home directory, with appropriate file system permissions. Take special care when dealing with shared data or preferences. Follow the guidelines about file system permissions set forth in File System Programming Guide . 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 103 Third-Party Software Security GuidelinesTake care to avoid race conditions and information disclosure when using temporary files. If possible, use a user-specific temporary file directory. Avoid Requiring Elevated Privileges Do not require or encourage users to be logged in as an admin user to install or use your application. You should regularly test your application as a normal user to make sure that it works as expected. Implement Secure Development Practices Educate your developers on how to write secure code to avoid the most common classes of vulnerabilities: ● Buffer overflows ● Integer overflows ● Race conditions ● Format string vulnerabilities Pay special attention to code that: ● deals with potentially untrusted data, such as documents or URLs ● communicates over the network ● handles passwords or other sensitive information ● runs with elevated privileges such as root or in the kernel Use APIs appropriate for the task: ● Use APIs that take security into account in their design. ● Avoid low-level C code when possible (e.g. use NSString instead of C-strings). ● Use the security features of OS X to protect user data. Test for Security As appropriate for your product, use the following QA techniques to find potential security issues: Third-Party Software Security Guidelines Avoid Requiring Elevated Privileges 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 104● Test for invalid and unexpected data in addition to testing what is expected. (Use fuzzing tools, include unit tests that test for failure, and so on.) ● Static code analysis ● Code reviews and audits Helpful Resources The other chaptersin this document describe best practicesfor writing secure code, including more information on the topics referenced above. Security Overview and Cryptographic Services Guide contain detailed information on security functionality in OS X that developers can use. Third-Party Software Security Guidelines Helpful Resources 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 105This table describes the changes to Secure Coding Guide . Date Notes 2012-06-11 Made minor typographical fixes. 2012-02-16 Fixed minor errors throughout. 2012-01-09 Updated for OS X v10.7. 2010-02-12 Added security guidelines. Added article on validating input--including the dangers of loading insecurely stored archives--and added information about the iOS where relevant. 2008-05-23 New document that describes techniques to use and factors to consider to make your code more secure from attack. 2006-05-23 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 106 Document Revision HistoryAES encryption Abbreviation for Advanced Encryption Standard encryption. A Federal Information Processing Standard (FIPS), described in FIPS publication 197. AES has been adopted by the U.S. government for the protection of sensitive, non-classified information. attacker Someone deliberately trying to make a program or operating system do something that it’s not supposed to do, such as allowing the attacker to execute code or read private data. authentication The process by which a person or other entity (such as a server) proves that it is who (or what) it says it is. Compare with authorization. authorization The process by which an entity such as a user or a server gets the right to perform a privileged operation. (Authorization can also refer to the right itself, as in “Bob has the authorization to run that program.”) Authorization usually involves first authenticating the entity and then determining whether it has the appropriate privileges. See also authentication. buffer overflow The insertion of more data into a memory buffer than was reserved for the buffer, resulting in memory locations outside the buffer being overwritten. See also heap overflow and stack overflow. CDSA Abbreviation for Common Data Security Architecture. An open software standard for a security infrastructure that provides a wide array of security services, including fine-grained access permissions, authentication of users, encryption, and secure data storage. CDSA has a standard application programming interface, called CSSM. CERT Coordination Center A center of Internet security expertise, located at the Software Engineering Institute, a federally funded research and development center operated by Carnegie Mellon University. CERT is an acronym for Computer Emergency Readiness Team.) certificate See digital certificate. Common Criteria A standardized process and set of standards that can be used to evaluate the security of software products developed by the governments of the United States, Canada, the United Kingdom, France, Germany, and the Netherlands. cracker See attacker. CSSM Abbreviation for Common Security Services Manager. A public application programming interface for CDSA. CSSM also defines an interface for plug-ins that implement security services for a particular operating system and hardware environment. CVE Abbreviation for Common Vulnerabilities and Exposures. A dictionary of standard names for security vulnerabilities located at http://www.cve.mitre.org/. You can run an Internet search on the CVE number to read details about the vulnerability. 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 107 Glossarydigital certificate A collection of data used to verify the identity of the holder. OS X supports the X.509 standard for digital certificates. exploit A program or sample code that demonstrates how to take advantage of a vulnerability.) FileVault An OS X feature, configured through the Security system preference, that encrypts everything in on the root volume (or everything in the user’s home directory prior to OS X v10.7). hacker An expert programmer—generally one with the skill to create an exploit. Most hackers do not attack other programs, and some publish exploits with the intent of forcing software developers to fix vulnerabilities. See also script kiddie. heap A region of memory reserved for use by a program during execution. Data can be written to or read from any location on the heap, which grows upward (toward highermemory addresses). Compare with stack. heap overflow A buffer overflow in the heap. homographs Characters that look the same but have different Unicode values, such as the Roman character p and the Russian glyph that is pronounced like “r”. integer overflow A buffer overflow caused by entering a number that is too large for an integer data type. Kerberos An industry-standard protocol created by the Massachusetts Institute of Technology (MIT) to provide authentication over a network. keychain A database used in OS X to store encrypted passwords, private keys, and othersecrets. It is also used to store certificates and other non-secret information that is used in cryptography and authentication. Keychain Access utility An application that can be used to manipulate data in the keychain. Keychain Services A public API that can be used to manipulate data in the keychain. level of trust The confidence a user can have in the validity of a certificate. The level of trust for a certificate is used together with the trust policy to answer the question “Should I trust this certificate for this action?” nonrepudiation A process or technique making it impossible for a user to deny performing an operation (such as using a specific credit card number). Open Directory The directory server provided by OS X for secure storage of passwords and user authentication. permissions See privileges. phishing A social engineering technique in which an email or web page that spoofs one from a legitimate businessis used to trick a user into giving personal data and secrets (such as passwords) to someone who has malicious intent. policy database A database containing the set of rules the Security Server uses to determine authorization. privileged operation An operation that requires special rights or privileges. privileges The type of access to a file or directory (read, write, execute, traverse, and so forth) granted to a user or to a group. Glossary 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 108race condition The occurrence of two events out of sequence. root kit Malicious code that, by running in the kernel, can not only take over control of the system but can also cover up all evidence of its own existence. root privileges Having the unrestricted permission to perform any operation on the system. script kiddie Someone who uses published code (scripts) to attack software and computer systems. signal A message sent from one processto another in a UNIX-based operating system (such as OS X) social engineering As applied to security, tricking a user into giving up secrets or into giving access to a computer to an attacker. smart card A plastic card similar in size to a credit card that has memory and a microprocessor embedded in it. A smart card can store and process information, including passwords, certificates, and keys. stack A region of memory reserved for use by a specific program and used to control program flow. Data is put on the stack and removed in a last-in–first-out fashion. The stack grows downward (toward lower memory addresses). Compare with heap. stack overflow A buffer overflow on the stack. time of check–time of use (TOCTOU) A race condition in which an attacker creates, writes to, or alters a file between the time when a program checks the status of the file and when the program writes to it. trust policy A set of rules that specify the appropriate uses for a certificate that has a specific level of trust. For example, the trust policy for a browser might state that if a certificate has expired, the user should be prompted for permission before a secure session is opened with a web server. vulnerability A feature of the way a program was written—either a design flaw or a bug—that makes it possible for a hacker or script kiddie to attack the program. Glossary 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 109Symbols _unknown user 84 A access control 14 applications factoring 69 interfaces 73–78 arguments, command line 61, 101 argv(0) 61 attackers 8 audit logs 91 authentication 14, 90 authopen 65 Authorization Services 72 authorization granting 14 revoking 75 AuthorizationExecWithPrivilege 68 B buffer overflows 11, 17–29 calculating buffer sizes 25–26 checklist 97 detecting 28 integer arithmetic 27 strings 22 buffer overflows See also heap , stack 17 C certificates digital certificates 14 CFBundle 99 chflags 48 chmod 55 chown 55 close-on-exec flag 58 code insertion 37 command-line arguments 61, 101 command-line tools 100 configuration files 88 crackers 8 D default settings 73 denial of service 91 device ID 58 digital certificate identity 79 digital certificates 14 document organization 9 dyld 99 dynamic link editor 99 E elevated privileges 59, 86 encryption 15 environment variables 62, 88 F factoring applications 69 fchmod 55 fchown 55 file descriptor 50, 52 inheriting 58 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 110 Indexfile descriptors 61 file locations 75 file operations Carbon 55 Cocoa 51 insecure 13, 47–58 POSIX 50 file system, remotely mounted 57 files temporary 88 FileVault 75 firewall 91 fopen 55 format string attacks 34 FSFindFolder 50 fstat 55 fuzzing 39 G GID 64 group ID 64 guest access 96 GUI 88 H hackers 7 hard link 48 hash function 91, 102 heap 11 overflow 20, 22 I identity 79 input validation 12 input data structures 97 inappropriate 17 testing 28 to audit logs 92 types of 17 validating 19, 33–40, 100 insecure file operations 13, 47–58 installer 63 integer overflows 27 interface, user 76 ipfw 91 K Kerberos 96 kernel extensions 72, 89 kernel messages 102 kernel checklist 101 KEXT 72 L launchd 66, 87 least privilege, principle of 60 left bracket 57 libbsm 92 /Library/StartupItems 68 logs, audit 91 lstat 55 M Mach ports 101 mkstemp 53, 55 mktemp 55 N negative numbers 27 network ports 90 nobody user 84 NSBundle 99 NSTemporaryDirectory 51 Index 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 111O open 55 organization of document 9 P passwords 93 permissions 52 permissions See also privileges phishing 16, 78 plug-ins 99 policy database 69, 72 port numbers 90 ports, Mach 101 private key identity 79 privileges 14, 59–72 elevated 59, 86 level, changing 64 principle of least privilege 60 root 14 process limits 62 R race conditions 13, 43 interprocess communication 13 scripts 56 time of check–time of use 44–46 44–46 random numbers 97 references 10 remotely mounted file system 58 rm 48 root kit 89 root privileges 14 S script kiddies 8 scripts, avoiding race conditions 56 Security Objective-C API 79 setegid 65 seteuid 65 setgid 65 setregid 65 setreuid 65 setrlimit 62 setuid 65, 67 SFAuthorizationView 79 SFCertificatePanel 79 SFCertificateTrustPanel 79 SFCertificateView 79 SFChooseIdentityPanel 79 SFKeychainSavePanel 79 SFKeychainSettingsPanel 80 shell commands 100 signal handler 46 social engineering 16, 37, 78 stack 11 overflow 18–20 stat 55 statistics of threats and attacks 16 string-handling functions 22, 97 sudo 87 symbolic link 49 syslog 92 SystemStarter 68 T temporary files 50, 53, 88 and scripts 56 default location 50, 51 test 57 twos-complement arithmetic 27 U UID 64 Index 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 112unique 84 umask 52 URL commands 12, 36 user ID 64 user interface 76 V validating input 12, 33–40 W wildcard characters 89 X xinetd 68 Index 2012-06-11 | © 2012 Apple Inc. All Rights Reserved. 113Apple Inc. © 2012 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrievalsystem, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apple’s copyright notice. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Apple, the Apple logo, Carbon, Cocoa, eMac, FileVault, iPhone, Keychain, Mac, Macintosh, Numbers, Objective-C, OS X, Pages, and Safari are trademarks of Apple Inc., registered in the U.S. and other countries. .Mac is a service mark of Apple Inc., registered in the U.S. and other countries. App Store and Mac App Store are service marks of Apple Inc. Java is a registered trademark of Oracle and/or its affiliates. Ping is a registered trademark of Karsten Manufacturing and is used in the U.S. under license. UNIX is a registered trademark of The Open Group. iOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is used under license. Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.ASARESULT, THISDOCUMENT IS PROVIDED “AS IS,” AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state. String Programming GuideContents Introduction to String Programming Guide for Cocoa 5 Who Should Read This Document 5 Organization of This Document 5 See Also 6 Strings 7 Creating and Converting String Objects 8 Creating Strings 8 NSString from C Strings and Data 8 Variable Strings 9 Strings to Present to the User 10 Combining and Extracting Strings 10 Getting C Strings 11 Conversion Summary 12 Formatting String Objects 13 Formatting Basics 13 Strings and Non-ASCII Characters 14 NSLog and NSLogv 14 String Format Specifiers 15 Format Specifiers 15 Platform Dependencies 17 Reading Strings From and Writing Strings To Files and URLs 19 Reading From Files and URLs 19 Reading data with a known encoding 19 Reading data with an unknown encoding 20 Writing to Files and URLs 21 Summary 21 Searching, Comparing, and Sorting Strings 22 Search and Comparison Methods 22 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 2Searching strings 22 Comparing and sorting strings 23 Search and Comparison Options 24 Examples 24 Case-Insensitive Search for Prefix and Suffix 24 Comparing Strings 25 Sorting strings like Finder 26 Paragraphs and Line Breaks 28 Line and Paragraph Separator Characters 28 Separating a String “by Paragraph” 28 Characters and Grapheme Clusters 30 Character Sets 33 Character Set Basics 33 Creating Character Sets 33 Performance considerations 34 Creating a character set file 35 Standard Character Sets and Unicode Definitions 35 Scanners 36 Creating a Scanner 36 Using a Scanner 36 Example 38 Localization 39 String Representations of File Paths 40 Representing a Path 40 User Directories 41 Path Components 42 File Name Completion 43 Drawing Strings 44 Document Revision History 45 Index 47 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 3Tables String Format Specifiers 15 Table 1 Format specifiers supported by the NSString formatting methods and CFString formatting functions 15 Table 2 Length modifiers supported by the NSString formatting methods and CFString formatting functions 16 Table 3 Format specifiers for data types 17 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 4String Programming Guide for Cocoa describes how to create, search, concatenate, and draw strings. It also describes character sets, which let you search a string for characters in a group, and scanners, which convert numbers to strings and vice versa. Who Should Read This Document You should read this document if you need to work directly with strings or character sets. Organization of This Document This document contains the following articles: ● “Strings” (page 7) describes the characteristics of string objects in Cocoa. ● “Creating and Converting String Objects” (page 8) explains the ways in which NSString and its subclass NSMutableString create string objects and convert their contents to and from the various character encodings they support. ● “Formatting String Objects” (page 13) describes how to format NSString objects. ● “String Format Specifiers” (page 15) describes printf-style format specifiers supported by NSString. ● “Reading Strings From and Writing Strings To Files and URLs” (page 19) describes how to read strings from and write strings to files and URLs. ● “Searching, Comparing, and Sorting Strings” (page 22) describes methods for finding characters and substrings within strings and for comparing one string to another. ● “Paragraphs and Line Breaks” (page 28) describes how paragraphs and line breaks are represented. ● “Characters and Grapheme Clusters” (page 30) describes how you can break strings down into user-perceived characters. ● “Character Sets” (page 33) explains how to use character set objects, and how to use NSCharacterSet methods to create standard and custom character sets. ● “Scanners” (page 36) describes NSScanner objects, which interpret and convert the characters of an NSString object into number and string values. 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 5 Introduction to String Programming Guide for Cocoa● “String Representations of File Paths” (page 40) describes the NSString methods that manipulate strings as file-system paths. ● “Drawing Strings” (page 44) discusses the methods of the NSString class that support drawing directly in an NSView object. See Also For more information, refer to the following documents: ● Attributed String Programming Guide is closely related to String Programming Guide for Cocoa . It provides information about NSAttributedString objects, which manage sets of attributes, such as font and kerning, that are associated with character strings or individual characters. ● Data Formatting Guide describes how to format data using objects that create, interpret, and validate text. ● Internationalization Programming Topics provides information about localizing strings in your project, including information on how string formatting arguments can be ordered. ● String Programming Guide for Core Foundation in Core Foundation, discussesthe Core Foundation opaque type CFString, which is toll-free bridged with the NSString class. Introduction to String Programming Guide for Cocoa See Also 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 6String objects represent character strings in Cocoa frameworks. Representing strings as objects allows you to use strings wherever you use other objects. It also providesthe benefits of encapsulation,so thatstring objects can use whatever encoding and storage is needed for efficiency while simply appearing as arrays of characters. A string object is implemented as an array of Unicode characters (in other words, a text string). An immutable string is a text string that is defined when it is created and subsequently cannot be changed. To create and manage an immutable string, use the NSString class. To construct and manage a string that can be changed after it has been created, use NSMutableString. The objects you create using NSString and NSMutableString are referred to as string objects (or, when no confusion will result, merely as strings). The term C string refers to the standard C char * type. A string object presents itself as an array of Unicode characters. You can determine how many characters it contains with the length method and can retrieve a specific character with the characterAtIndex: method. These two “primitive” methods provide basic access to a string object. Most use of strings, however, is at a higher level, with the strings being treated as single entities: You compare strings against one another, search them for substrings, combine them into new strings, and so on. If you need to access string objects character-by-character, you must understand the Unicode character encoding—specifically, issues related to composed character sequences. For details see: ● The Unicode Standard, Version 4.0 . The Unicode Consortium. Boston: Addison-Wesley, 2003. ISBN 0-321-18578-1. ● The Unicode Consortium web site: http://www.unicode.org/. 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 7 StringsNSString and its subclass NSMutableString provide several ways to create string objects, most based around the various character encodingsitsupports. Although string objects always present their own contents as Unicode characters, they can convert their contents to and from many other encodings, such as 7-bit ASCII, ISO Latin 1, EUC, and Shift-JIS. The availableStringEncodings class method returns the encodings supported. You can specify an encoding explicitly when converting a C string to or from a string object, or use the default C string encoding, which varies from platform to platform and is returned by the defaultCStringEncoding class method. Creating Strings The simplest way to create a string object in source code is to use the Objective-C @"..." construct: NSString *temp = @"Contrafibularity"; Note that, when creating a string constant in this fashion, you should use UTF-8 characters. Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated. You can also send messages directly to a string constant as you do any other string: BOOL same = [@"comparison" isEqualToString:myString]; NSString from C Strings and Data To create an NSString object from a C string, you use methods such as initWithCString:encoding:. You must correctly specify the character encoding of the C string. Similar methods allow you to create string objects from characters in a variety of encodings. The method initWithData:encoding: allows you to convert string data stored in an NSData object into an NSString object. char *utf8String = /* Assume this exists. */ ; NSString *stringFromUTFString = [[NSString alloc] initWithUTF8String:utf8String]; 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 8 Creating and Converting String Objectschar *macOSRomanEncodedString = /* assume this exists */ ; NSString *stringFromMORString = [[NSString alloc] initWithCString:macOSRomanEncodedString encoding:NSMacOSRomanStringEncoding]; NSData *shiftJISData = /* assume this exists */ ; NSString *stringFromShiftJISData = [[NSString alloc] initWithData:shiftJISData encoding:NSShiftJISStringEncoding]; The following example converts an NSString object containing a UTF-8 character to ASCII data then back to an NSString object. unichar ellipsis = 0x2026; NSString *theString = [NSString stringWithFormat:@"To be continued%C", ellipsis]; NSData *asciiData = [theString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *asciiString = [[NSString alloc] initWithData:asciiData encoding:NSASCIIStringEncoding]; NSLog(@"Original: %@ (length %d)", theString, [theString length]); NSLog(@"Converted: %@ (length %d)", asciiString, [asciiString length]); // output: // Original: To be continued… (length 16) // Converted: To be continued... (length 18) Variable Strings To create a variable string, you typically use stringWithFormat:: or initWithFormat: (or for localized strings, localizedStringWithFormat:). These methods and theirsiblings use a formatstring as a template into which the values you provide (string and other objects, numerics values, and so on) are inserted. They and the supported format specifiers are described in “Formatting String Objects” (page 13). Creating and Converting String Objects Creating Strings 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 9You can build a string from existing string objects using the methods stringByAppendingString: and stringByAppendingFormat: to create a new string by adding one string after another, in the second case using a format string. NSString *hString = @"Hello"; NSString *hwString = [hString stringByAppendingString:@", world!"]; Strings to Present to the User When creating strings to present to the user, you should consider the importance of localizing your application. In general, you should avoid creating user-visible strings directly in code. Instead you should use strings in your code as a key to a localization dictionary that will supply the user-visible string in the user's preferred language. Typically thisinvolves using NSLocalizedString and similar macros, asillustrated in the following example. NSString *greeting = NSLocalizedStringFromTable (@"Hello", @"greeting to present in first launch panel", @"greetings"); For more about internationalizing your application, see Internationalization Programming Topics. “Localizing String Resources” describes how to work with and reorder variable arguments in localized strings. Combining and Extracting Strings You can combine and extract strings in various ways. The simplest way to combine two strings is to append one to the other. The stringByAppendingString: method returns a string object formed from the receiver and the given argument. NSString *beginning = @"beginning"; NSString *alphaAndOmega = [beginning stringByAppendingString:@" and end"]; // alphaAndOmega is @"beginning and end" You can also combine several strings according to a template with the initWithFormat:, stringWithFormat:, and stringByAppendingFormat: methods; these are described in more detail in “Formatting String Objects” (page 13). Creating and Converting String Objects Combining and Extracting Strings 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 10You can extract substrings from the beginning or end of a string to a particular index, or from a specific range, with the substringToIndex:, substringFromIndex:, and substringWithRange: methods. You can also split a string into substrings (based on a separator string) with the componentsSeparatedByString: method. These methods are illustrated in the following examples—notice that the index of the index-based methods starts at 0: NSString *source = @"0123456789"; NSString *firstFour = [source substringToIndex:4]; // firstFour is @"0123" NSString *allButFirstThree = [source substringFromIndex:3]; // allButFirstThree is @"3456789" NSRange twoToSixRange = NSMakeRange(2, 4); NSString *twoToSix = [source substringWithRange:twoToSixRange]; // twoToSix is @"2345" NSArray *split = [source componentsSeparatedByString:@"45"]; // split contains { @"0123", @"6789" } If you need to extract strings using pattern-matching rather than an index, you should use a scanner—see “Scanners” (page 36). Getting C Strings To get a C string from a string object, you are recommended to use UTF8String. This returns a const char * using UTF8 string encoding. const char *cString = [@"Hello, world" UTF8String]; The C string you receive is owned by a temporary object, and will become invalid when automatic deallocation takes place. If you want to get a permanent C string, you must create a buffer and copy the contents of the const char * returned by the method. Similar methods allow you to create string objects from characters in the Unicode encoding or an arbitrary encoding, and to extract data in these encodings. initWithData:encoding: and dataUsingEncoding: perform these conversions from and to NSData objects. Creating and Converting String Objects Getting C Strings 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 11Conversion Summary This table summarizes the most common means of creating and converting string objects: Source Creation method Extraction method In code @"..." compiler construct N/A UTF8 encoding stringWithUTF8String: UTF8String getCharacters: getCharacters:range: Unicode encoding stringWithCharacters: length: Arbitrary encoding initWithData: encoding: dataUsingEncoding: stringByAppendingString: N/A stringByAppendingFormat: Existing strings localizedStringWithFormat: Use NSScanner initWithFormat: locale: Format string Localized strings NSLocalizedString and similar N/A Creating and Converting String Objects Conversion Summary 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 12This article describes how to create a string using a format string, how to use non-ASCII characters in a format string, and a common error that developers make when using NSLog or NSLogv. Formatting Basics NSString uses a format string whose syntax is similar to that used by other formatter objects. It supports the format characters defined for the ANSI C function printf(), plus %@ for any object (see “String Format Specifiers” (page 15) and the IEEE printf specification). If the object responds to descriptionWithLocale: messages, NSString sends such a message to retrieve the text representation. Otherwise, it sends a description message. “Localizing String Resources” describes how to work with and reorder variable arguments in localized strings. In formatstrings, a ‘%’ character announces a placeholder for a value, with the charactersthat follow determining the kind of value expected and how to format it. For example, a format string of "%d houses" expects an integer value to be substituted for the format expression '%d'. NSString supportsthe format characters defined for the ANSI C functionprintf(), plus ‘@’ for any object. If the object responds to the descriptionWithLocale: message, NSString sends that message to retrieve the text representation, otherwise, it sends a description message. Value formatting is affected by the user’s current locale, which is an NSDictionary object that specifies number, date, and other kinds of formats. NSString uses only the locale’s definition for the decimal separator (given by the key named NSDecimalSeparator). If you use a method that doesn’t specify a locale, the string assumes the default locale. You can use NSString’s stringWithFormat: method and other related methods to create strings with printf-style formatspecifiers and argument lists, as described in “Creating and Converting StringObjects” (page 8). The examples below illustrate how you can create a string using a variety of formatspecifiers and arguments. NSString *string1 = [NSString stringWithFormat:@"A string: %@, a float: %1.2f", @"string", 31415.9265]; // string1 is "A string: string, a float: 31415.93" NSNumber *number = @1234; 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 13 Formatting String ObjectsNSDictionary *dictionary = @{ [NSDate date]:@"date" }; NSString *baseString = @"Base string."; NSString *string2 = [baseString stringByAppendingFormat: @" A number: %@, a dictionary: %@", number, dictionary]; // string2 is "Base string. A number: 1234, a dictionary: {date = 2005-10-17 09:02:01 -0700; }" Strings and Non-ASCII Characters You can include non-ASCII characters(including Unicode) in strings usingmethodssuch as stringWithFormat: and stringWithUTF8String:. NSString *s = [NSString stringWithFormat:@"Long %C dash", 0x2014]; Since \xe2\x80\x94 is the 3-byte UTF-8 string for 0x2014, you could also write: NSString *s = [NSString stringWithUTF8String:"Long \xe2\x80\x94 dash"]; NSLog and NSLogv The utility functions NSLog() and NSLogv() use the NSString string formatting servicesto log error messages. Note that as a consequence of this, you should take care when specifying the argument for these functions. A common mistake isto specify a string that includesformatting characters, asshown in the following example. NSString *string = @"A contrived string %@"; NSLog(string); // The application will probably crash here due to signal 10 (SIGBUS) It is better (safer) to use a format string to output another string, as shown in the following example. NSString *string = @"A contrived string %@"; NSLog(@"%@", string); // Output: A contrived string %@ Formatting String Objects Strings and Non-ASCII Characters 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 14This article summarizes the format specifiers supported by string formatting methods and functions. Format Specifiers The format specifiers supported by the NSString formatting methods and CFString formatting functions follow the IEEE printf specification; the specifiers are summarized in Table 1 (page 15). Note that you can also use the “n$” positional specifiers such as %1$@ %2$s. For more details, see the IEEE printf specification. You can also use these format specifiers with the NSLog function. Table 1 Format specifiers supported by the NSString formatting methods and CFString formatting functions Specifier Description Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function. %@ %% '%' character. %d, %D Signed 32-bit integer (int). %u, %U Unsigned 32-bit integer (unsigned int). Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and lowercase a–f. %x Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and uppercase A–F. %X %o, %O Unsigned 32-bit integer (unsigned int), printed in octal. %f 64-bit floating-point number (double). 64-bit floating-point number (double), printed in scientific notation using a lowercase e to introduce the exponent. %e 64-bit floating-point number (double), printed in scientific notation using an uppercase E to introduce the exponent. %E 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 15 String Format SpecifiersSpecifier Description 64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise. %g 64-bit floating-point number (double), printed in the style of %E if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise. %G 8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit. %c 16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit. %C Null-terminated array of 8-bit unsigned characters. Because the %s specifier causes the characters to be interpreted in the system default encoding, the results can be variable, especially with right-to-left languages. For example, with RTL, %s inserts direction markers when the characters are not strongly directional. For this reason, it’s best to avoid %s and specify encodings explicitly. %s %S Null-terminated array of 16-bit Unicode characters. Void pointer (void *), printed in hexadecimal with the digits 0–9 and lowercase a–f, with a leading 0x. %p 64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a lowercase p to introduce the exponent. %a 64-bit floating-point number (double), printed in scientific notation with a leading 0X and one hexadecimal digit before the decimal point using a uppercase P to introduce the exponent. %A %F 64-bit floating-point number (double), printed in decimal notation. Table 2 Length modifiers supported by the NSString formatting methods and CFString formatting functions Length Description modifier Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a short or unsigned short argument. h Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument. hh String Format Specifiers Format Specifiers 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 16Length Description modifier Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a long or unsigned long argument. l Length modifiers specifying that a following d, o, u, x, or X conversion specifier applies to a long long or unsigned long long argument. ll, q Length modifier specifying that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument. L Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a size_t or the corresponding signed integer type argument. z Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument. t Length modifier specifying that a following d, o, u, x, or X conversion specifier applies to a intmax_t or uintmax_t argument. j Platform Dependencies OS X uses several data types—NSInteger, NSUInteger,CGFloat, and CFIndex—to provide a consistent means of representing values in 32- and 64-bit environments. In a 32-bit environment, NSInteger and NSUInteger are defined as int and unsigned int, respectively. In 64-bit environments, NSInteger and NSUInteger are defined as long and unsigned long, respectively. To avoid the need to use different printf-style type specifiers depending on the platform, you can use the specifiers shown in Table 3. Note that in some cases you may have to cast the value. Table 3 Format specifiers for data types Type Format specifier Considerations NSInteger %ld or %lx Cast the value to long. NSUInteger %lu or %lx Cast the value to unsigned long. %f works for floats and doubles when formatting; but note the technique described below for scanning. CGFloat %f or %g CFIndex %ld or %lx The same as NSInteger. %p adds 0x to the beginning of the output. If you don't want that, use %zx and no typecast. pointer %p or %zx String Format Specifiers Platform Dependencies 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 17The following example illustrates the use of %ld to format an NSInteger and the use of a cast. NSInteger i = 42; printf("%ld\n", (long)i); In addition to the considerations mentioned in Table 3, there is one extra case with scanning: you must distinguish the types for float and double. You should use %f for float, %lf for double. If you need to use scanf (or a variant thereof) with CGFloat, switch to double instead, and copy the double to CGFloat. CGFloat imageWidth; double tmp; sscanf (str, "%lf", &tmp); imageWidth = tmp; It is important to remember that %lf does not represent CGFloat correctly on either 32- or 64-bit platforms. This is unlike %ld, which works for long in all cases. String Format Specifiers Platform Dependencies 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 18Reading files or URLs using NSString is straightforward provided that you know what encoding the resource uses—if you don't know the encoding, reading a resource is more challenging. When you write to a file or URL, you must specify the encoding to use. (Where possible, you should use URLs because these are more efficient.) Reading From Files and URLs NSString provides a variety of methods to read data from files and URLs. In general, it is much easier to read data if you know its encoding. If you have plain text and no knowledge of the encoding, you are already in a difficult position. You should avoid placing yourself in this position if at all possible—anything that calls for the use of plain text files should specify the encoding (preferably UTF-8 or UTF-16+BOM). Reading data with a known encoding To read from a file or URL for which you know the encoding, you use stringWithContentsOfFile:encoding:error: or stringWithContentsOfURL:encoding:error:, or the corresponding init... method, as illustrated in the following example. NSURL *URL = ...; NSError *error; NSString *stringFromFileAtURL = [[NSString alloc] initWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:&error]; if (stringFromFileAtURL == nil) { // an error occurred NSLog(@"Error reading file at %@\n%@", URL, [error localizedFailureReason]); // implementation continues ... You can also initialize a string using a data object, as illustrated in the following examples. Again, you must specify the correct encoding. 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 19 Reading Strings From and Writing Strings To Files and URLsNSURL *URL = ...; NSData *data = [NSData dataWithContentsOfURL:URL]; // Assuming data is in UTF8. NSString *string = [NSString stringWithUTF8String:[data bytes]]; // if data is in another encoding, for example ISO-8859-1 NSString *string = [[NSString alloc] initWithData:data encoding: NSISOLatin1StringEncoding]; Reading data with an unknown encoding If you find yourself with text of unknown encoding, it is best to make sure that there is a mechanism for correcting the inevitable errors. For example, Apple's Mail and Safari applications have encoding menus, and TextEdit allows the user to reopen the file with an explicitly specified encoding. If you are forced to guess the encoding (and note that in the absence of explicit information, it is a guess): 1. Try stringWithContentsOfFile:usedEncoding:error: or initWithContentsOfFile:usedEncoding:error: (or the URL-based equivalents). These methods try to determine the encoding of the resource, and if successful return by reference the encoding used. 2. If (1) fails, try to read the resource by specifying UTF-8 as the encoding. 3. If (2) fails, try an appropriate legacy encoding. "Appropriate" here depends a bit on circumstances; it might be the default C string encoding, it might be ISO or Windows Latin 1, or something else, depending on where your data are coming from. 4. Finally, you can try NSAttributedString's loading methods from the Application Kit (such as initWithURL:options:documentAttributes:error:). These methods attempt to load plain text files, and return the encoding used. They can be used on more-or-less arbitrary text documents, and are worth considering if your application has no special expertise in text. They might not be as appropriate for Foundation-level tools or documents that are not natural-language text. Reading Strings From and Writing Strings To Files and URLs Reading From Files and URLs 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 20Writing to Files and URLs Compared with reading data from a file or URL, writing isstraightforward—NSString providestwo convenient methods, writeToFile:atomically:encoding:error: and writeToURL:atomically:encoding:error:. You must specify the encoding that should be used, and choose whether to write the resource atomically or not. If you do not choose to write atomically, the string is written directly to the path you specify. If you choose to write it atomically, it is written first to an auxiliary file, and then the auxiliary file is renamed to the path. This option guarantees that the file, if it exists at all, won’t be corrupted even if the system should crash during writing. If you write to an URL, the atomicity option is ignored if the destination is not of a type that can be accessed atomically. NSURL *URL = ...; NSString *string = ...; NSError *error; BOOL ok = [string writeToURL:URL atomically:YES encoding:NSUnicodeStringEncoding error:&error]; if (!ok) { // an error occurred NSLog(@"Error writing file at %@\n%@", path, [error localizedFailureReason]); // implementation continues ... Summary This table summarizes the most common means of reading and writing string objects to and from files and URLs: Source Creation method Extraction method writeToURL: atomically:encoding: error: stringWithContentsOfURL: encoding:error: stringWithContentsOfURL: usedEncoding:error: URL contents writeToFile: atomically:encoding: error: stringWithContentsOfFile: encoding:error: stringWithContentsOfFile: usedEncoding:error: File contents Reading Strings From and Writing Strings To Files and URLs Writing to Files and URLs 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 21The string classes provide methods for finding characters and substrings within strings and for comparing one string to another. These methods conform to the Unicode standard for determining whether two character sequences are equivalent. The string classes provide comparison methods that handle composed character sequences properly, though you do have the option of specifying a literal search when efficiency is important and you can guarantee some canonical form for composed character sequences. Search and Comparison Methods The search and comparison methods each come in several variants. The simplest version of each searches or compares entire strings. Other variants allow you to alter the way comparison of composed charactersequences is performed and to specify a specific range of characters within a string to be searched or compared; you can also search and compare strings in the context of a given locale. These are the basic search and comparison methods: Search methods Comparison methods rangeOfString: compare: rangeOfString: options: compare:options: rangeOfString: options:range: compare:options: range: rangeOfString: options:range: locale: compare:options: range:locale: rangeOfCharacterFromSet: rangeOfCharacterFromSet: options: rangeOfCharacterFromSet: options:range: Searching strings You use the rangeOfString:... methods to search for a substring within the receiver. The rangeOfCharacterFromSet:... methodssearch for individual charactersfrom a supplied set of characters. 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 22 Searching, Comparing, and Sorting StringsSubstrings are found only if completely contained within the specified range. If you specify a range for a search or comparison method and don’t request NSLiteralSearch (see below), the range must not break composed character sequences on either end; if it does, you could get an incorrect result. (See the method description for rangeOfComposedCharacterSequenceAtIndex: for a code sample that adjusts a range to lie on character sequence boundaries.) You can also scan a string object for numeric and string values using an instance of NSScanner. For more about scanners, see “Scanners” (page 36). Both the NSString and the NSScanner class clusters use the NSCharacterSet class cluster forsearch operations. For more about charactersets,see “Character Sets” (page 33). If you simply want to determine whether a string contains a given pattern, you can use a predicate: BOOL match = [myPredicate evaluateWithObject:myString]; For more about predicates, see Predicate Programming Guide . Comparing and sorting strings The compare:... methods return the lexical ordering of the receiver and the supplied string. Several other methods allow you to determine whether two strings are equal or whether one isthe prefix orsuffix of another, but they don’t have variants that allow you to specify search options or ranges. The simplest method you can use to compare strings is compare:—this is the same as invoking compare:options:range: with no options and the receiver’s full extent as the range. If you want to specify comparison options(NSCaseInsensitiveSearch, NSLiteralSearch, or NSNumericSearch) you can use compare:options:; if you want to specify a locale you can use compare:options:range:locale:. NSString also provides various convenience methodsto allow you to perform common comparisons without the need to specify ranges and options directly, for example caseInsensitiveCompare: and localizedCompare:. Important: For user-visible sorted lists, you should always use localized comparisons. Thustypically instead of compare: or caseInsensitiveCompare: you should use localizedCompare: or localizedCaseInsensitiveCompare:. If you want to compare strings to order them in the same way as they’re presented in Finder, you should use compare:options:range:locale: with the user’s locale and the following options: NSCaseInsensitiveSearch, NSNumericSearch, NSWidthInsensitiveSearch, and NSForcedOrderingSearch. For an example, see “Sorting strings like Finder” (page 26). Searching, Comparing, and Sorting Strings Search and Comparison Methods 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 23Search and Comparison Options Several of the search and comparison methods take an “options” argument. This is a bit mask that adds further constraints to the operation. You create the mask by combining the following options (not all options are available for every method): Search option Effect NSCaseInsensitive- Ignores case distinctions among characters. Search Performs a byte-for-byte comparison. Differing literal sequences (such as composed character sequences) that would otherwise be considered equivalent are considered not to match. Using this option can speed some operations dramatically. NSLiteralSearch NSBackwardsSearch Performs searching from the end of the range toward the beginning. Performs searching only on characters at the beginning or end of the range. No match at the beginning or end means nothing is found, even if a matching sequence of characters occurs elsewhere in the string. NSAnchoredSearch When used with the compare:options: methods, groups of numbers are treated as a numeric value for the purpose of comparison. For example, Filename9.txt < Filename20.txt < Filename100.txt. NSNumericSearch Search and comparison are currently performed as if the NSLiteralSearch option were specified. Examples Case-Insensitive Search for Prefix and Suffix NSString provides the methods hasPrefix: and hasSuffix: that you can use to find an exact match for a prefix or suffix. The following example illustrates how you can use rangeOfString:options: with a combination of options to perform case insensitive searches. NSString *searchString = @"age"; NSString *beginsTest = @"Agencies"; NSRange prefixRange = [beginsTest rangeOfString:searchString Searching, Comparing, and Sorting Strings Search and Comparison Options 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 24options:(NSAnchoredSearch | NSCaseInsensitiveSearch)]; // prefixRange = {0, 3} NSString *endsTest = @"BRICOLAGE"; NSRange suffixRange = [endsTest rangeOfString:searchString options:(NSAnchoredSearch | NSCaseInsensitiveSearch | NSBackwardsSearch)]; // suffixRange = {6, 3} Comparing Strings The following examples illustrate the use of various string comparison methods and associated options. The first shows the simplest comparison method. NSString *string1 = @"string1"; NSString *string2 = @"string2"; NSComparisonResult result; result = [string1 compare:string2]; // result = -1 (NSOrderedAscending) You can compare strings numerically using the NSNumericSearch option: NSString *string10 = @"string10"; NSString *string2 = @"string2"; NSComparisonResult result; result = [string10 compare:string2]; // result = -1 (NSOrderedAscending) result = [string10 compare:string2 options:NSNumericSearch]; // result = 1 (NSOrderedDescending) You can use convenience methods (caseInsensitiveCompare: and localizedCaseInsensitiveCompare:) to perform case-insensitive comparisons: Searching, Comparing, and Sorting Strings Examples 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 25NSString *string_a = @"Aardvark"; NSString *string_A = @"AARDVARK"; result = [string_a compare:string_A]; // result = 1 (NSOrderedDescending) result = [string_a caseInsensitiveCompare:string_A]; // result = 0 (NSOrderedSame) // equivalent to [string_a compare:string_A options:NSCaseInsensitiveSearch] Sorting strings like Finder To sort strings the way Finder does in OS X v10.6 and later, use the localizedStandardCompare: method. It should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method is different under different localizations, so clients should not depend on the exact sorting order of the strings. The following example shows another implementation of similar functionality, comparing strings to order them in the same way as they’re presented in Finder, and it also shows how to sort the array of strings. First, define a sorting function that includes the relevant comparison options (for efficiency, pass the user's locale as the context—this way it's only looked up once). int finderSortWithLocale(id string1, id string2, void *locale) { static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch; NSRange string1Range = NSMakeRange(0, [string1 length]); return [string1 compare:string2 options:comparisonOptions range:string1Range locale:(NSLocale *)locale]; } Searching, Comparing, and Sorting Strings Examples 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 26You pass the function as a parameter to sortedArrayUsingFunction:context: with the user’s current locale as the context: NSArray *stringsArray = @[@"string 1", @"String 21", @"string 12", @"String 11", @"String 02"]; NSArray *sortedArray = [stringsArray sortedArrayUsingFunction:finderSortWithLocale context:[NSLocale currentLocale]]; // sortedArray contains { "string 1", "String 02", "String 11", "string 12", "String 21" } Searching, Comparing, and Sorting Strings Examples 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 27This article describes how line and paragraph separators are defined and how you can separate a string by paragraph. Line and Paragraph Separator Characters There are a number of ways in which a line or paragraph break may be represented. Historically \n, \r, and \r\n have been used. Unicode defines an unambiguous paragraph separator, U+2029 (for which Cocoa provides the constant NSParagraphSeparatorCharacter), and an unambiguous line separator, U+2028 (for which Cocoa provides the constant NSLineSeparatorCharacter). In the Cocoa text system, the NSParagraphSeparatorCharacter is treated consistently as a paragraph break, and NSLineSeparatorCharacter is treated consistently as a line break that is not a paragraph break—that is, a line break within a paragraph. However, in other contexts, there are few guarantees as to how these characters will be treated. POSIX-level software, for example, often recognizes only \n as a break. Some older Macintosh software recognizes only \r, and some Windows software recognizes only \r\n. Often there is no distinction between line and paragraph breaks. Which line or paragraph break character you should use depends on how your data may be used and on what platforms. The Cocoa text system recognizes \n, \r, or \r\n all as paragraph breaks—equivalent to NSParagraphSeparatorCharacter.When it inserts paragraph breaks, for example with insertNewline:, it uses \n. Ordinarily NSLineSeparatorCharacter is used only for breaks that are specifically line breaks and not paragraph breaks, for example in insertLineBreak:, or for representing HTML
elements. If your breaks are specifically intended as line breaks and not paragraph breaks, then you should typically use NSLineSeparatorCharacter. Otherwise, you may use \n, \r, or \r\n depending on what other software is likely to process your text. The default choice for Cocoa is usually \n. Separating a String “by Paragraph” A common approach to separating a string “by paragraph” is simply to use: NSArray *arr = [myString componentsSeparatedByString:@"\n"]; 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 28 Paragraphs and Line BreaksThis, however, ignores the fact that there are a number of other ways in which a paragraph or line break may be represented in a string—\r, \r\n, or Unicode separators. Instead you can use methods—such as lineRangeForRange: or getParagraphStart:end:contentsEnd:forRange:—that take into account the variety of possible line terminations, as illustrated in the following example. NSString *string = /* assume this exists */; unsigned length = [string length]; unsigned paraStart = 0, paraEnd = 0, contentsEnd = 0; NSMutableArray *array = [NSMutableArray array]; NSRange currentRange; while (paraEnd < length) { [string getParagraphStart:¶Start end:¶End contentsEnd:&contentsEnd forRange:NSMakeRange(paraEnd, 0)]; currentRange = NSMakeRange(paraStart, contentsEnd - paraStart); [array addObject:[string substringWithRange:currentRange]]; } Paragraphs and Line Breaks Separating a String “by Paragraph” 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 29It's common to think of a string as a sequence of characters, but when working with NSString objects, or with Unicode strings in general, in most cases it is better to deal with substrings rather than with individual characters. The reason for this is that what the user perceives as a character in text may in many cases be represented by multiple characters in the string. NSString has a large inventory of methods for properly handling Unicode strings, which in general make Unicode compliance easy, but there are a few precautions you should observe. NSString objects are conceptually UTF-16 with platform endianness. That doesn't necessarily imply anything about their internalstorage mechanism; what it meansisthat NSString lengths, character indexes, and ranges are expressed in terms of UTF-16 units, and that the term “character” in NSString method names refers to 16-bit platform-endian UTF-16 units. This is a common convention for string objects. In most cases, clients don't need to be overly concerned with this; aslong as you are dealing with substrings, the precise interpretation of the range indexes is not necessarily significant. The vast majority of Unicode code points used for writing living languages are represented by single UTF-16 units. However, some less common Unicode code points are represented in UTF-16 by surrogate pairs. A surrogate pair is a sequence of two UTF-16 units, taken from specific reserved ranges, that together represent a single Unicode code point. CFString has functions for converting between surrogate pairs and the UTF-32 representation of the corresponding Unicode code point. When dealing with NSString objects, one constraint is that substring boundaries usually should not separate the two halves of a surrogate pair. This is generally automatic for rangesreturned from most Cocoa methods, but if you are constructing substring ranges yourself you should keep this in mind. However, this is not the only constraint you should consider. In many writing systems, a single character may be composed of a base letter plus an accent or other decoration. The number of possible letters and accents precludes Unicode from representing each combination as a single code point, so in general such combinations are represented by a base character followed by one or more combining marks. For compatibility reasons, Unicode does have single code points for a number of the most common combinations; these are referred to as precomposed forms, and Unicode normalization transformations can be used to convert between precomposed and decomposed representations. However, even if a string is fully precomposed, there are still many combinations that must be represented using a base character and combining marks. For most text processing, substring ranges should be arranged so that their boundaries do not separate a base character from its associated combining marks. 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 30 Characters and Grapheme ClustersIn addition, there are writing systems in which characters represent a combination of parts that are more complicated than accent marks. In Korean, for example, a single Hangul syllable can be composed of two or three subparts known as jamo. In the Indic and Indic-influenced writing systems common throughout South and Southeast Asia, single written characters often represent combinations of consonants, vowels, and marks such as viramas, and the Unicode representations of these writing systems often use code points for these individual parts,so that a single character may be composed of multiple code points. For most text processing, substring ranges should also be arranged so that their boundaries do not separate the jamo in a single Hangul syllable, or the components of an Indic consonant cluster. In general, these combinations—surrogate pairs, base characters plus combining marks, Hangul jamo, and Indic consonant clusters—are referred to as grapheme clusters. In order to take them into account, you can use NSString’s rangeOfComposedCharacterSequencesForRange: or rangeOfComposedCharacterSequenceAtIndex: methods, or CFStringGetRangeOfComposedCharactersAtIndex. These can be used to adjuststring indexes orsubstring ranges so that they fall on grapheme cluster boundaries, taking into account all of the constraints mentioned above. These methods should be the default choice for programmatically determining the boundaries of user-perceived characters.: In some cases, Unicode algorithms deal with multiple charactersin waysthat go beyond even grapheme cluster boundaries. Unicode casing algorithms may convert a single character into multiple characters when going from lowercase to uppercase; for example, the standard uppercase equivalent of the German character “ß” is the two-letter sequence “SS”. Localized collation algorithms in many languages consider multiple-character sequences as single units; for example, the sequence “ch” is treated as a single letter for sorting purposes in some European languages. In order to deal properly with cases like these, it is important to use standard NSString methods for such operations as casing, sorting, and searching, and to use them on the entire string to which they are to apply. Use NSString methods such as lowercaseString, uppercaseString, capitalizedString, compare: and its variants, rangeOfString: and its variants, and rangeOfCharacterFromSet: and its variants, or their CFString equivalents. These all take into account the complexities of Unicode string processing, and the searching and sorting methods in particular have many options to control the types of equivalences they are to recognize. In some less common cases, it may be necessary to tailor the definition of grapheme clusters to a particular need. The issues involved in determining and tailoring grapheme cluster boundaries are covered in detail in Unicode Standard Annex #29, which gives a number of examples and some algorithms. The Unicode standard in general is the best source for information about Unicode algorithms and the considerations involved in processing Unicode strings. If you are interested in grapheme cluster boundaries from the point of view of cursor movement and insertion point positioning, and you are using the Cocoa text system, you should know that on OS X v10.5 and later, NSLayoutManager has API support for determining insertion point positions within a line of text as it is laid Characters and Grapheme Clusters 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 31out. Note that insertion point boundaries are not identical to glyph boundaries; a ligature glyph in some cases, such as an “fi” ligature in Latin script, may require an internal insertion point on a user-perceived character boundary. See Cocoa Text Architecture Guide for more information. Characters and Grapheme Clusters 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 32An NSCharacterSet object represents a set of Unicode characters. NSString and NSScanner objects use NSCharacterSet objects to group characters together for searching operations, so that they can find any of a particular set of characters during a search. Character Set Basics A character set object represents a set of Unicode characters. Character sets are represented by instances of a class cluster. The cluster’s two public classes, NSCharacterSet and NSMutableCharacterSet, declare the programmatic interface for immutable and mutable character sets, respectively. An immutable character set is defined when it is created and subsequently cannot be changed. A mutable character set can be changed after it’s created. A character set object doesn’t perform any tasks; it simply holds a set of character values to limit operations on strings. The NSString and NSScanner classes define methods that take NSCharacterSet objects as argumentsto find any ofseveral characters. For example, this code excerpt findsthe range of the first uppercase letter in myString:. NSString *myString = @"some text in an NSString..."; NSCharacterSet *characterSet = [NSCharacterSet uppercaseLetterCharacterSet]; NSRange letterRange = [myString rangeOfCharacterFromSet:characterSet]; After this fragment executes, letterRange.location is equal to the index of the first “N” in “NSString” after rangeOfCharacterFromSet: isinvoked. If the first letter of the string were “S”, then letterRange.location would be 0. Creating Character Sets NSCharacterSet defines class methodsthat return commonly used charactersets,such asletters(uppercase or lowercase), decimal digits, whitespace, and so on. These “standard” character sets are always immutable, even if created by sending a message to NSMutableCharacterSet. See “Standard Character Sets and Unicode Definitions” (page 35) for more information on standard character sets. 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 33 Character SetsYou can use a standard character set as a starting point for building a custom set by making a mutable copy of it and changing that. (You can also start from scratch by creating a mutable character set with alloc and init and adding characters to it.) For example, this fragment creates a character set containing letters, digits, and basic punctuation: NSMutableCharacterSet *workingSet = [[NSCharacterSet alphanumericCharacterSet] mutableCopy]; [workingSet addCharactersInString:@";:,."]; NSCharacterSet *finalCharacterSet = [workingSet copy]; To define a custom character set using Unicode code points, use code similar to the following fragment (which creates a character set including the form feed and line separator characters): UniChar chars[] = {0x000C, 0x2028}; NSString *string = [[NSString alloc] initWithCharacters:chars length:sizeof(chars) / sizeof(UniChar)]; NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:string]; Performance considerations Because character sets often participate in performance-critical code, you should be aware of the aspects of their use that can affect the performance of your application. Mutable character sets are generally much more expensive than immutable character sets. They consume more memory and are costly to invert (an operation often performed in scanning a string). Because of this, you should follow these guidelines: ● Create as few mutable character sets as possible. ● Cache character sets (in a global dictionary, perhaps) instead of continually recreating them. ● When creating a custom set that doesn’t need to change after creation, make an immutable copy of the final character set for actual use, and dispose of the working mutable character set. Alternatively, create a character set file as described in “Creating a character set file” (page 35) and store it in your application’s main bundle. ● Similarly, avoid archiving characterset objects;store them in characterset filesinstead. Archiving can result in a character set being duplicated in different archive files, resulting in wasted disk space and duplicates in memory for each separate archive read. Character Sets Performance considerations 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 34Creating a character set file If your application frequently uses a custom character set, you should save its definition in a resource file and load that instead of explicitly adding individual characters each time you need to create the set. You can save a character set by getting its bitmap representation (an NSData object) and saving that object to a file: NSData *charSetRep = [finalCharacterSet bitmapRepresentation]; NSURL *dataURL = <#URL for character set#>; NSError *error; BOOL result = [charSetRep writeToURL:dataURL options:NSDataWritingAtomic error:&error]; By convention, characterset filenames use the extension .bitmap. If you intend for othersto use your character set files, you should follow this convention. To read a character set file with a .bitmap extension, simply use the characterSetWithContentsOfFile: method. Standard Character Sets and Unicode Definitions The standard character sets, such as that returned by letterCharacterSet, are formally defined in terms of the normative and informative categories established by the Unicode standard, such as Uppercase Letter, Combining Mark, and so on. The formal definition of a standard character set is in most cases given as one or more of the categories defined in the standard. For example, the set returned by lowercaseLetterCharacterSet include all characters in normative category Lowercase Letters, while the set returned by letterCharacterSet includes the characters in all of the Letter categories. Note that the definitions of the categoriesthemselves may change with new versions of the Unicode standard. You can download the files that define category membership from http://www.unicode.org/. Character Sets Creating a character set file 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 35An NSScanner object scans the characters of an NSString object, typically interpreting the characters and converting them into number and string values. You assign the scanner’s string on creation, and the scanner progresses through the characters of that string from beginning to end as you request items. Creating a Scanner NSScanner is a class cluster with a single public class, NSScanner. Generally, you instantiate a scanner object by invoking the class method scannerWithString: or localizedScannerWithString:. Either method returns a scanner object initialized with the string you pass to it. The newly created scanner starts at the beginning of its string. You scan components using the scan... methods such as scanInt:, scanDouble:, and scanString:intoString:. If you are scanning multiple lines, you typically create a while loop that continues until the scanner is at the end of the string, as illustrated in the following code fragment: float aFloat; NSScanner *theScanner = [NSScanner scannerWithString:aString]; while ([theScanner isAtEnd] == NO) { [theScanner scanFloat:&aFloat]; // implementation continues... } You can configure a scanner to consider or ignore case using the setCaseSensitive: method. By default a scanner ignores case. Using a Scanner Scan operationsstart at the scan location and advance the scanner to just past the last character in the scanned value representation (if any). For example, after scanning an integer from the string “137 small cases of bananas”, a scanner’s location will be 3, indicating the space immediately after the number. Often you need to advance the scan location to skip characters in which you are not interested. You can change the implicit 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 36 Scannersscan location with the setScanLocation: method to skip ahead a certain number of characters (you can also use the method to rescan a portion of the string after an error). Typically, however, you either want to skip characters from a particular character set, scan past a specific string, or scan up to a specific string. You can configure a scanner to skip a set of characters with the setCharactersToBeSkipped: method. A scanner ignores characters to be skipped at the beginning of any scan operation. Once it finds a scannable character, however, it includes all characters matching the request. Scanners skip whitespace and newline characters by default. Note that case is always considered with regard to characters to be skipped. To skip all English vowels, for example, you must set the characters to be skipped to those in the string “AEIOUaeiou”. If you want to read content from the current location up to a particular string, you can use scanUpToString:intoString: (you can pass NULL as the second argument if you simply want to skip the intervening characters). For example, given the following string: 137 small cases of bananas you can find the type of container and number of containers using scanUpToString:intoString: asshown in the following example. NSString *bananas = @"137 small cases of bananas"; NSString *separatorString = @" of"; NSScanner *aScanner = [NSScanner scannerWithString:bananas]; NSInteger anInteger; [aScanner scanInteger:&anInteger]; NSString *container; [aScanner scanUpToString:separatorString intoString:&container]; It is important to note that the search string (separatorString) is " of". By default a scanner ignores whitespace, so the space character after the integer is ignored. Once the scanner begins to accumulate characters, however, all characters are added to the output string until the search string is reached. Thus if the search string is "of" (no space before), the first value of container is “small cases ” (includes the space following); if the search string is " of" (with a space before), the first value of container is “small cases” (no space following). Scanners Using a Scanner 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 37After scanning up to a given string, the scan location is the beginning of that string. If you want to scan past thatstring, you must therefore firstscan in the string you scanned up to. The following code fragment illustrates how to skip past the search string in the previous example and determine the type of product in the container. Note the use of substringFromIndex: to in effect scan up to the end of a string. [aScanner scanString:separatorString intoString:NULL]; NSString *product; product = [[aScanner string] substringFromIndex:[aScanner scanLocation]]; // could also use: // product = [bananas substringFromIndex:[aScanner scanLocation]]; Example Suppose you have a string containing lines such as: Product: Acme Potato Peeler; Cost: 0.98 73 Product: Chef Pierre Pasta Fork; Cost: 0.75 19 Product: Chef Pierre Colander; Cost: 1.27 2 The following example uses alternating scan operationsto extract the product names and costs(costs are read as a float forsimplicity’ssake),skipping the expected substrings“Product:” and “Cost:”, as well asthe semicolon. Note that because a scanner skips whitespace and newlines by default, the loop does no special processing for them (in particular there is no need to do additional whitespace processing to retrieve the final integer). NSString *string = @"Product: Acme Potato Peeler; Cost: 0.98 73\n\ Product: Chef Pierre Pasta Fork; Cost: 0.75 19\n\ Product: Chef Pierre Colander; Cost: 1.27 2\n"; NSCharacterSet *semicolonSet; NSScanner *theScanner; NSString *PRODUCT = @"Product:"; NSString *COST = @"Cost:"; NSString *productName; float productCost; Scanners Example 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 38NSInteger productSold; semicolonSet = [NSCharacterSet characterSetWithCharactersInString:@";"]; theScanner = [NSScanner scannerWithString:string]; while ([theScanner isAtEnd] == NO) { if ([theScanner scanString:PRODUCT intoString:NULL] && [theScanner scanUpToCharactersFromSet:semicolonSet intoString:&productName] && [theScanner scanString:@";" intoString:NULL] && [theScanner scanString:COST intoString:NULL] && [theScanner scanFloat:&productCost] && [theScanner scanInteger:&productSold]) { NSLog(@"Sales of %@: $%1.2f", productName, productCost * productSold); } } Localization A scanner bases some of its scanning behavior on a locale, which specifies a language and conventions for value representations. NSScanner uses only the locale’s definition for the decimal separator (given by the key named NSDecimalSeparator). You can create a scanner with the user’s locale by using localizedScannerWithString:, or set the locale explicitly using setLocale:. If you use a method that doesn’t specify a locale, the scanner assumes the default locale values. Scanners Localization 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 39NSString provides a rich set of methodsfor manipulating strings asfile-system paths. You can extract a path’s directory, filename, and extension, expand a tilde expression (such as “~me”) or create one for the user’s home directory, and clean up paths containing symbolic links, redundant slashes, and references to “.” (current directory) and “..” (parent directory). Note: Where possible, you should use instances of NSURL to represent paths—the operating system deals with URLs more efficiently than with string representations of paths. Representing a Path NSString represents paths generically with ‘/’ asthe path separator and ‘.’ asthe extension separator. Methods that accept strings as path arguments convert these generic representations to the proper system-specific form as needed. On systems with an implicit root directory, absolute paths begin with a path separator or with a tilde expression (“~/...” or “~user/...”). Where a device must be specified, you can do that yourself—introducing a system dependency—or allow the string object to add a default device. You can create a standardized representation of a path using stringByStandardizingPath. This performs a number of tasks including: ● Expansion of an initial tilde expression; ● Reduction of empty components and references to the current directory (“//” and “/./”) to single path separators; ● In absolute paths, resolution of references to the parent directory (“..”) to the real parent directory; for example: NSString *path = @"/usr/bin/./grep"; NSString *standardizedPath = [path stringByStandardizingPath]; // standardizedPath: /usr/bin/grep path = @"~me"; 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 40 String Representations of File PathsstandardizedPath = [path stringByStandardizingPath]; // standardizedPath (assuming conventional naming scheme): /Users/Me path = @"/usr/include/objc/.."; standardizedPath = [path stringByStandardizingPath]; // standardizedPath: /usr/include path = @"/private/usr/include"; standardizedPath = [path stringByStandardizingPath]; // standardizedPath: /usr/include User Directories The following examples illustrate how you can use NSString’s path utilities and other Cocoa functions to get the user directories. // Assuming that users’ home directories are stored in /Users NSString *meHome = [@"~me" stringByExpandingTildeInPath]; // meHome = @"/Users/me" NSString *mePublic = [@"~me/Public" stringByExpandingTildeInPath]; // mePublic = @"/Users/me/Public" You can find the home directory for the current user and for a given user with NSHomeDirectory and NSHomeDirectoryForUser respectively: NSString *currentUserHomeDirectory = NSHomeDirectory(); NSString *meHomeDirectory = NSHomeDirectoryForUser(@"me"); Note that you should typically use the function NSSearchPathForDirectoriesInDomains to locate standard directories for the current user. For example, instead of: NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; String Representations of File Paths User Directories 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 41you should use: NSString *documentsDirectory; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); if ([paths count] > 0) { documentsDirectory = [paths objectAtIndex:0]; } Path Components NSString provides a rich set of methods for manipulating strings as file-system paths, for example: Interprets the receiver as a path and returns the receiver’s extension, if any. pathExtension Returns a new string made by deleting the extension (if any, and only the last) from the receiver. stringByDeletingPathExtension Returns a new string made by deleting the last path component from the receiver, along with any final path separator. stringByDeletingLastPathComponent Using these and related methods described in NSString Class Reference , you can extract a path’s directory, filename, and extension, as illustrated by the following examples. NSString *documentPath = @"~me/Public/Demo/readme.txt"; NSString *documentDirectory = [documentPath stringByDeletingLastPathComponent]; // documentDirectory = @"~me/Public/Demo" NSString *documentFilename = [documentPath lastPathComponent]; // documentFilename = @"readme.txt" NSString *documentExtension = [documentPath pathExtension]; // documentExtension = @"txt" String Representations of File Paths Path Components 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 42File Name Completion You can find possible expansions of file names using completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:. For example, given a directory ~/Demo that contains the following files: ReadMe.txt readme.html readme.rtf recondite.txt test.txt you can find all possible completions for the path ~/Demo/r as follows: NSString *partialPath = @"~/Demo/r"; NSString *longestCompletion; NSArray *outputArray; unsigned allMatches = [partialPath completePathIntoString:&longestCompletion caseSensitive:NO matchesIntoArray:&outputArray filterTypes:NULL]; // allMatches = 3 // longestCompletion = @"~/Demo/re" // outputArray = (@"~/Demo/readme.html", "~/Demo/readme.rtf", "~/Demo/recondite.txt") You can find possible completions for the path ~/Demo/r that have an extension “.txt” or “.rtf” as follows: NSArray *filterTypes = @[@"txt", @"rtf"]; unsigned textMatches = [partialPath completePathIntoString:&outputName caseSensitive:NO matchesIntoArray:&outputArray filterTypes:filterTypes]; // allMatches = 2 // longestCompletion = @"~/Demo/re" // outputArray = (@"~/Demo/readme.rtf", @"~/Demo/recondite.txt") String Representations of File Paths File Name Completion 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 43You can draw string objects directly in a focused NSView using methods such as drawAtPoint:withAttributes: (to draw a string with multiple attributes, such as multiple text fonts, you must use an NSAttributedString object). These methods are described briefly in “Text” in Cocoa Drawing Guide . The simple methods, however, are designed for drawing small amounts of text or text that is only drawn rarely—they create and dispose of various supporting objects every time you call them. To draw strings repeatedly, it is more efficient to use NSLayoutManager, as described in “Drawing Strings”. For an overview of the Cocoa text system, of which NSLayoutManager is a part, see Cocoa Text Architecture Guide . 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 44 Drawing StringsThis table describes the changes to String Programming Guide . Date Notes 2012-07-17 Updated code snippets to adopt new Objective-C features. Corrected string constant character set to UTF-8. Added guidance about using localizedStandardCompare: for Finder-like sorting. Added caveat to avoid using %s with RTL languages. Revised "String Format Specifiers" article. 2012-06-11 2009-10-15 Added links to Cocoa Core Competencies. Added new aricle on character clusters; updated list of string format specifiers. 2008-10-15 2007-10-18 Corrected minor typographical errors. Added notes regarding NSInteger and NSUInteger to "String Format Specifiers". 2007-07-10 2007-03-06 Corrected minor typographical errors. 2007-02-08 Corrected sentence fragments and improved the example in "Scanners." 2006-12-05 Added code samples to illustrate searching and path manipulation. 2006-11-07 Made minor revisions to "Scanners" article. 2006-10-03 Added links to path manipulation methods. 2006-06-28 Corrected typographical errors. Added a new article, "Reading Strings From and Writing Strings To Files and URLs"; significantly updated "Creating and Converting Strings." 2006-05-23 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 45 Document Revision HistoryDate Notes Included “Creating a Character Set” into “Character Sets” (page 33). Changed title from "Strings" to conform to reference consistency guidelines. 2006-01-10 Added “Formatting String Objects” (page 13) article. Added Data Formatting and the Core Foundation Strings programming topics to the introduction. 2004-06-28 Added information about custom Unicode character sets and retrieved missing code fragments in “Creating a Character Set”. Added information and cross-reference to “Drawing Strings” (page 44). Rewrote introduction and added an index. 2004-02-06 Added NSNumericSearch description to “Searching, Comparing, and Sorting Strings” (page 22). 2003-09-09 2003-03-17 Reinstated the sample code that was missing from “Scanners” (page 36). Updated “Creating and Converting String Objects” (page 8) to recommend the use of UTF8 encoding, and noted the pending deprecation of the cString... methods. 2003-01-17 2002-11-12 Revision history was added to existing topic. Document Revision History 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 46A alloc method 34 archiving character set objects 34 ASCII character encoding converting string object contents 8 availableStringEncodings method 8 C C strings Cocoa string objects and 7 creating and converting 11 character encodings string manipulation and 8 character sets custom 34 example code 34 guidelines for use 34 mutable and immutable 33 saving to a file 35 standard 33, 35 characterAtIndex: method 7 characterSetWithContentsOfFile: method 35 compare: method 22 compare:options: method 22, 24 compare:options:range: method 22 comparing strings 22–23 comparison methods for strings 22 componentsSeparatedByString: method 11 current directories resolving references to 40 D dataUsingEncoding: method 11, 12 defaultCStringEncoding method 8 description method 13 descriptionWithLocale: method 13 directories manipulating strings as paths 40, 42 E encodings, character string manipulation and 8 EUC character encoding 8 F file-system paths and strings 42 format strings 13 G getCharacters:length: method 12 I init method for mutable character sets 34 initWithData:encoding: method 8, 11, 12 initWithFormat: method 10 initWithFormat:locale: method 12 ISO Latin 1 character encoding 8 L length method 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 47 Indexfor string objects 7 letterCharacterSet method 35 localization scanning strings and 39 value formatting and 13 localizedScannerWithString: method 36, 39 localizedStringWithFormat: method 9, 12 lowercaseLetterCharacterSet method 35 M myString: method 33 N NSCharacterSet class 33 NSLayoutManager class 44 NSMutableCharacterSet class 33 NSMutableString class 7, 8 NSScanner class 23, 36–38 NSString class creating string objects from 8 described 7 methods for representing file-system paths 40 scanners and 36 NSView class 44 P parent directories resolving references to 40 paths and strings 42 primitive methods of NSString 7 printf function NSString and 13 R rangeOfCharacterFromSet: method 22, 33 rangeOfCharacterFromSet:options: method 22 rangeOfCharacterFromSet:options:range: method 22 rangeOfComposedCharacterSequenceAtIndex: method 23 rangeOfString: method 22 rangeOfString:options: method 22 rangeOfString:options:range: method 22 S scan... methods 36 scanners 36, 38 instantiating 36 operation of 36 sample code 38 scannerWithString: method 36 scanUpToString:intoString: method 37 search methods for strings 22 setCaseSensitive: method 36 setCharactersToBeSkipped: method 37 setLocale: method 39 setScanLocation: method 37 Shift-JIS character encoding 8 standard character sets 33, 35 string objects combining and extracting 10 comparison methods 22 creating and converting 8–12 described 7 drawing 44 searching and comparing 22–23 stringByAppendingFormat: method 10, 12 stringByAppendingString: method 10, 12 stringWithCharacters:length: method 12 stringWithContentsOfFile: method 21 stringWithFormat: method 10 stringWithUTF8String: method 12 substringFromIndex: method 11 substringToIndex: method 11 Index 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 48substringWithRange: method 11 U Unicode characters in string objects 8 code points used to define character sets 34 in string objects 7 NSCharacterSet and 33 standard character sets 35 string comparison standard 22 UTF8 character encoding 11 UTF8String method 11, 12 V value formatting string conversion and 13 W writeToFile:atomically: method 21 Index 2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved. 49Apple Inc. © 1997, 2012 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrievalsystem, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apple’s copyright notice. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Apple, the Apple logo, Cocoa, Finder, Mac, Macintosh, Objective-C, OS X, and Safari are trademarks of Apple Inc., registered in the U.S. and other countries. Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.ASARESULT, THISDOCUMENT IS PROVIDED “AS IS,” AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state. Apple AirPort Networks2 1 Contents Chapter 1 3 Getting Started 5 Configuring an Apple Wireless Device for Internet Access Using AirPort Utility 6 Extending the Range of Your AirPort Network 6 Sharing a USB Hard Disk Connected to an AirPort Extreme Base Station or Time Capsule 6 Printing with an Apple Wireless Device 6 Sharing Your Computer’s Internet Connection Chapter 2 9 AirPort Security 9 Security for AirPort Networks at Home 10 Security for AirPort Networks in Businesses and Classrooms 11 Wi-Fi Protected Access (WPA) and WPA2 Chapter 3 14 AirPort Network Designs 15 Using AirPort Utility 17 Setting Up the AirPort Extreme Network 24 Configuring and Sharing Internet Access 41 Setting Advanced Options 43 Extending the Range of an 802.11n Network 45 Keeping Your Network Secure 49 Directing Network Traffic to a Specific Computer on Your Network (Port Mapping) 51 Logging 52 Using Back to My Mac on your Wireless Network 53 Setting up IPv6 54 Sharing and Securing USB Hard Disks on Your Network 55 Using a Time Capsule in Your Network 55 Connecting a USB Printer to an Apple Wireless Device 56 Adding a Wireless Client to Your 802.11n Network 57 Solving Problems Chapter 4 59 Behind the Scenes 59 Basic Networking 63 Items That Can Cause Interference with AirPort Glossary 641 3 1 Getting Started AirPort offers the easiest way to provide wireless Internet access and networking anywhere in the home, classroom, or office. AirPort is based on the latest Institute of Electrical and Electronics Engineers (IEEE) 802.11n draft specification and provides fast and reliable wireless networking in the home, classroom, or small office. You can enjoy data transfer rates of up to five times faster than data rates provided by the 802.11g standard and more than twice the network range. The new AirPort Extreme Base Station and the new Time Capsule are based on simultaneous dual-band technology, so they work in both the 2.4 gigahertz (GHz) or 5 GHz spectrum at the same time. And they are 100 percent backward-compatible, so Mac computers and PCs that use 802.11a, 802.11b, 802.11g, or IEEE draft specification 802.11n wireless cards can connect to an AirPort wireless network. They also work flawlessly with the AirPort Express for wireless music streaming and more. The AirPort Extreme Base Station and Time Capsule have three additional 10/100/1000BaseT Gigabit Ethernet ports, so you don’t need to include another router in your network. To set up an AirPort Extreme Base Station, an AirPort Express, or a Time Capsule, you use AirPort Utility, the easy-to-use setup and management application. AirPort Utility has a simple user experience, with all software controls accessible from the same application. It provides better management of several Apple wireless devices, with client-monitoring features and logging. If you’re using AirPort Utility version 5.4 or later, you can set up a guest network, in both the 2.4 GHz and 5 GHz bands, so that guests can connect to the Internet using your AirPort network, while you keep your private network secure. You can also choose to set up guest accounts that expire, to grant temporary access to your network; you no longer need to give your network password to visitors in your home or office. You can even set up accounts with time constraints for the best in parental controls. AirPort Utility supports IPv6 and Bonjour, so you can “advertise” network services such as printing and sharing a hard disk over the Wide Area Network (WAN) port.4 Chapter 1 Getting Started Note: When the features discussed in this document apply to the AirPort Extreme Base Station, AirPort Express, and Time Capsule, the devices are referred to collectively as Apple wireless devices. With an AirPort Extreme Base Station or a Time Capsule, you can connect a USB hard disk so that everyone on the network can back up, store, and share files. Every Time Capsule includes an internal AirPort disk, so you don’t need to connect an external one. If you want, you can connect additional USB disks to the USB port on your Time Capsule. You can also connect a USB printer to the USB port on any Apple wireless device, so that everyone on the network can access the printer or hub. All Apple wireless devices provide strong, wireless security. They offer a built-in firewall and support industry-standard encryption technologies. Yet the simple setup utility and powerful access controls make it easy for authorized users to connect to the AirPort network they create. You can use an Apple wireless device to provide wireless Internet access and share a single Internet connection among several computers in the following ways:  Set up the device to act as a router and provide Internet Protocol (IP) addresses to computers on the network using Dynamic Host Configuration Protocol (DHCP) and Network Address Translation (NAT). When the wireless device is connected to a DSL or cable modem that is connected to the Internet, it receives webpages and email content from the Internet through its Internet connection, and then sends the content to wireless-enabled computers, using the wireless network or using Ethernet if there are computers connected to the Ethernet ports.  Set up the Apple wireless device to act as a bridge on an existing network that already has Internet access and a router providing IP addresses. The device passes IP addresses and the Internet connection to AirPort or wireless-enabled computers, or computers connected to the wireless device by Ethernet. This document provides information about the latest AirPort Extreme Base Station, AirPort Express, and Time Capsule, and detailed information about designing 802.11n networks with AirPort Utility for computers using Mac OS X v10.5 or later, and Windows Vista or Windows XP with Service Pack 2. If you’re using previous versions of Mac OS X, or are setting up earlier versions of AirPort devices, you’ll find more information at www.apple.com/support/airport.Chapter 1 Getting Started 5 You can set up an Apple wireless device and connect to the Internet wirelessly in minutes. But because Apple wireless devices are flexible and powerful networking products, you can also create an AirPort network that does much more. If you want to design an AirPort network that provides Internet access to non-AirPort computers via Ethernet, or take advantage of some of your wireless device’s more advanced features, use this document to design and implement your network. You can find more general wireless networking information and an overview of AirPort technology in the earlier AirPort documents, located at www.apple.com/support/manuals/airport. Note: The images of AirPort Utility in this document are from Mac OS X v10.5. If you’re using a Windows computer, the images you see in this document may be slightly different from what you see on your screen. Configuring an Apple Wireless Device for Internet Access Using AirPort Utility Like your computer, Apple wireless devices must be set up with the appropriate hardware and IP networking information to connect to the Internet. Install AirPort Utility, which came on the CD with your wireless device, and use it to provide Internet configuration information and other network settings. AirPort Utility combines the ease of use of AirPort Setup Assistant and the power of AirPort Admin Utility. It is installed in the Utilities folder in the Applications folder on a Macintosh computer using Mac OS X, and in Start > All Programs > AirPort on computers using Windows. AirPort Utility walks you through the setup process by asking a series of questions to determine how the device’s Internet connection and other interfaces should be set up. Enter the settings you received from your ISP or network administrator for Ethernet, PPP over Ethernet (PPPoE), or your local area network (LAN); give your AirPort network a name and password; set up a device as a wireless bridge to extend the range of your existing AirPort network; and set other options. When you’ve finished entering the settings, AirPort Utility transfers the settings to your wireless device. Then it connects to the Internet and shares its Internet connection with computers that join its AirPort network. You can also create an AirPort network that takes advantage of the more advanced networking features of Apple wireless devices. To set more advanced AirPort options, use AirPort Utility to manually set up your wireless device’s configuration, or make quick adjustments to one you’ve already set up. Some of the AirPort advanced networking features can be configured only using the manual setup features in AirPort Utility. 6 Chapter 1 Getting Started Set up your Apple wireless device manually using AirPort Utility when:  You want to provide Internet access to computers that connect to the wireless device using Ethernet  you’ve already set up your device, but you need to change one setting, such as your account information  You need to configure advanced settings such as channel frequency, advanced security options, closed networks, DHCP lease time, access control, WAN privacy, power controls, or port mapping or other options For instructions on using AirPort Utility to manually set up your wireless device and network, see “Using AirPort Utility” on page 15. Extending the Range of Your AirPort Network You can extend the range of your network by using AirPort Utility to set up wireless connections among several devices in your network, or to connect a device using Ethernet to create a roaming network. For more information on extending the range of your network, see “Connecting Additional Wireless Devices to Your AirPort Network” on page 41. Sharing a USB Hard Disk Connected to an AirPort Extreme Base Station or Time Capsule If you’re using an AirPort Extreme Base Station or a Time Capsule, you can connect a USB hard disk to it, and computers connected to the network—wired or wireless, Mac or Windows—can share files using the hard disk. Every Time Capsule includes an internal AirPort disk, so you don’t need to connect an external one. If you want, you can connect additional USB disks to the USB port on your Time Capsule. See “Sharing and Securing USB Hard Disks on Your Network” on page 54. Printing with an Apple Wireless Device If you have a compatible USB printer connected to your Apple wireless device, computers on the AirPort network can use Bonjour (Apple’s zero-configuration networking technology) to print to the printer. For instructions about printing to a USB printer from a computer, see “Connecting a USB Printer to an Apple Wireless Device” on page 55. Sharing Your Computer’s Internet Connection If your computer is connected to the Internet, you can share your Internet connection with other computers using Mac OS X version 10.2 or later, or Windows XP with Service Pack 2. This is sometimes called using your computer as a software base station.Chapter 1 Getting Started 7 You can share your Internet connection as long as your computer is connected to the Internet. If your computer goes to sleep or is restarted, or if you lose your Internet connection, you need to restart Internet sharing. To start Internet sharing on a computer using Mac OS X v10.5 or later: 1 Open System Preferences and click Sharing. 2 Choose the port you want to use to share your Internet connection from the “Share your connection using” pop-up menu. 3 Select the port you want to use to share your Internet connection in the “To computers using” list. You can choose to share your Internet connection with AirPort-enabled computers or computers with built-in Ethernet, for example. 4 Select Internet Sharing in the Services list. 5 If you want to share your Internet connection with computers using AirPort, click AirPort Options to give your network a name and password. 8 Chapter 1 Getting Started To start Internet sharing on a computer using Windows: 1 Open Control Panel from the Start menu, and then click “Network and Internet.” 2 Click “Network and Sharing Center.” 3 Click “Manage network connections” in the Tasks list. 4 Right-click the network connection you want to share, and then select Properties. 5 Click Sharing and then select “Allow other network users to connect through this computer’s Internet connection.” Note: If your Internet connection and your local network use the same port (built-in Ethernet, for example), contact your ISP before you turn on Internet sharing. In some cases (if you use a cable modem, for example) you might unintentionally affect the network settings of other ISP customers, and your ISP might terminate your service to prevent you from disrupting its network. The following chapters explain AirPort security options, AirPort network design and setup, and other advanced options.2 9 2 AirPort Security This chapter provides an overview of the security features available in AirPort. Apple has designed its wireless devices to provide several levels of security, so you can enjoy peace of mind when you access the Internet, manage online financial transactions, or send and receive email. The AirPort Extreme Base Station and Time Capsule also include a slot for inserting a lock to deter theft. For information and instructions for setting up these security features, see “Setting Up the AirPort Extreme Network” on page 17. Security for AirPort Networks at Home Apple gives you ways to protect your wireless AirPort network as well as the data that travels over it. NAT Firewall You can isolate your wireless network with firewall protection. Apple wireless devices have a built-in Network Address Translation (NAT) firewall that creates a barrier between your network and the Internet, protecting data from Internet-based IP attacks. The firewall is automatically turned on when you set up the device to share a single Internet connection. For computers with a cable or DSL modem, AirPort can actually be safer than a wired connection. Closed Network Creating a closed network keeps the network name and the very existence of your network private. Prospective users of your network must know the network name and password to access it. Use AirPort Utility, located in the Utilities folder in the Applications folder on a Macintosh computer using Mac OS X, or in Start > All Programs > AirPort on a computer using Windows, to create a closed network.10 Chapter 2 AirPort Security Password Protection and Encryption AirPort uses password protection and encryption to deliver a level of security comparable to that of traditional wired networks. Users can be required to enter a password to log in to the AirPort network. When transmitting data and passwords, the wireless device uses up to 128-bit encryption, through either Wi-Fi Protected Access (WPA), WPA2, or Wired Equivalent Privacy (WEP), to scramble data and help keep it safe. If you’re setting up an 802.11n-based AirPort device, you can also use WEP (Transitional Security Network) if both WEP-compatible and WPA/WPA2-compatible computers will join your network. Note: WPA security is available only to AirPort Extreme wireless devices; AirPort and AirPort Extreme clients using Mac OS X 10.3 or later and AirPort 3.3 or later; and to non-Apple clients using other 802.11 wireless adapters that support WPA. WPA2 security requires firmware version 5.6 or later for an AirPort Extreme Base Station, firmware version 6.2 or later for an AirPort Express, firmware version 7.3 or later for a Time Capsule, and a Macintosh computer with an AirPort Extreme wireless card using AirPort 4.2 or later. If your computer uses Windows XP or Windows Vista, check the documentation that came with your computer to see if your computer supports WPA2. Security for AirPort Networks in Businesses and Classrooms Businesses and schools need to restrict network communications to authorized users and keep data safe from prying eyes. To meet this need, Apple wireless devices and software provide a robust suite of security mechanisms. Use AirPort Utility to set up these advanced security features. Transmitter Power Control Because radio waves travel in all directions, they can extend outside the confines of a specific building. The Transmit Power setting in AirPort Utility lets you adjust the transmission range of your device’s network. Only users within the network vicinity have access to the network. MAC Address Access Control Every AirPort and wireless card have a unique Media Access Control (MAC) address. For AirPort Cards and AirPort Extreme Cards, the MAC address is sometimes referred to as the AirPort ID. Support for MAC address access control lets administrators set up a list of MAC addresses and restrict access to the network to only those users whose MAC addresses are in the access control list.Chapter 2 AirPort Security 11 RADIUS Support The Remote Authentication Dial-In User Service (RADIUS) makes securing a large network easy. RADIUS is an access control protocol that allows a system administrator to create a central list of the user names and passwords of computers that can access the network. Placing this list on a centralized server allows many wireless devices to access the list and makes it easy to update. If the MAC address of a user’s computer (which is unique to each 802.11 wireless card) is not on your approved MAC address list, the user cannot join your network. Wi-Fi Protected Access (WPA) and WPA2 There has been increasing concern about the vulnerabilities of WEP. In response, the Wi-Fi Alliance, in conjunction with the IEEE, has developed enhanced, interoperable security standards called Wi-Fi Protected Access (WPA) and WPA2. WPA and WPA2 use specifications that bring together standards-based, interoperable security mechanisms that significantly increase the level of data protection and access control for wireless LANs. WPA and WPA2 provide wireless LAN users with a high-level assurance that their data remains protected and that only authorized network users can access the network. A wireless network that uses WPA or WPA2 requires all computers that access the wireless network to have WPA or WPA2 support. WPA provides a high level of data protection and (when used in Enterprise mode) requires user authentication. The main standards-based technologies that constitute WPA include Temporal Key Integrity Protocol (TKIP), 802.1X, Message Integrity Check (MIC), and Extensible Authentication Protocol (EAP). TKIP provides enhanced data encryption by addressing the WEP encryption vulnerabilities, including the frequency with which keys are used to encrypt the wireless connection. 802.1X and EAP provide the ability to authenticate a user on the wireless network. 802.1X is a port-based network access control method for wired as well as wireless networks. The IEEE adopted 802.1X as a standard in August 2001. The Message Integrity Check (MIC) is designed to prevent an attacker from capturing data packets, altering them, and resending them. The MIC provides a strong mathematical function in which the receiver and the transmitter each compute and then compare the MIC. If they do not match, the data is assumed to have been tampered with and the packet is dropped. If multiple MIC failures occur, the network may initiate countermeasures.12 Chapter 2 AirPort Security The EAP protocol known as TLS (Transport Layer Security) presents a user’s information in the form of digital certificates. A user’s digital certificates can comprise user names and passwords, smart cards, secure IDs, or any other identity credentials that the IT administrator is comfortable using. WPA uses a wide variety of standards-based EAP implementations, including EAP-Transport Layer Security (EAP-TLS), EAP-Tunnel Transport Layer Security (EAP-TTLS), and Protected Extensible Authentication Protocol (PEAP). AirPort Extreme also supports the Lightweight Extensible Authentication Protocol (LEAP), a security protocol used by Cisco access points to dynamically assign a different WEP key to each user. AirPort Extreme is compatible with Cisco’s LEAP security protocol, enabling AirPort users to join Cisco-hosted wireless networks using LEAP. In addition to TKIP, WPA2 supports the AES-CCMP encryption protocol. Based on the very secure AES national standard cipher, combined with sophisticated cryptographic techniques, AES-CCMP was specifically designed for wireless networks. Migrating from WEP to WPA2 requires new firmware for the AirPort Extreme Base Station (version 5.6 or later), and for AirPort Express (version 6.2 or later). Devices using WPA2 mode are not backward compatible with WEP. WPA and WPA2 have two modes:  Personal mode, which relies on the capabilities of TKIP or AES-CCMP without requiring an authentication server  Enterprise mode, which uses a separate server, such as a RADIUS server, for user authentication WPA and WPA2 Personal  For home or Small Office/Home Office (SOHO) networks, WPA and WPA2 operates in Personal mode, taking into account that the typical household or small office does not have an authentication server. Instead of authenticating with a RADIUS server, users manually enter a password to log in to the wireless network. When a user enters the password correctly, the wireless device starts the encryption process using TKIP or AES-CCMP. TKIP or AES-CCMP takes the original password and derives encryption keys mathematically from the network password. The encryption key is regularly changed and rotated so that the same encryption key is never used twice. Other than entering the network password, the user isn’t required to do anything to make WPA or WPA2 Personal work in the home.Chapter 2 AirPort Security 13 WPA and WPA2 Enterprise WPA is a subset of the draft IEEE 802.11i standard and effectively addresses the wireless local area network (WLAN) security requirements for the enterprise. WPA2 is a full implementation of the ratified IEEE 802.11i standard. In an enterprise with IT resources, WPA should be used in conjunction with an authentication server such as RADIUS to provide centralized access control and management. With this implementation in place, the need for add-on solutions such as virtual private networks (VPNs) may be eliminated, at least for securing wireless connections in a network. For more information about setting up a WPA or WPA2 protected network, see “Using Wi-Fi Protected Access” on page 45.3 14 3 AirPort Network Designs This chapter provides overview information and instructions for the types of AirPort Extreme networks you can set up, and some of the advanced options of AirPort Extreme. Use this chapter to design and set up your AirPort Extreme network. Configuring your Apple wireless device to implement a network design requires three steps: Step 1: Setting Up the AirPort Extreme Network Computers communicate with the wireless device over the AirPort wireless network. When you set up the AirPort network created by the wireless device, you can name the wireless network, assign a password that will be needed to join the wireless network, and set other options. Step 2: Configuring and Sharing Internet Access When computers access the Internet through the AirPort Extreme network, the wireless device connects to the Internet and transmits information to the computers over the AirPort Extreme network. You provide the wireless device with settings appropriate for your ISP and configure how the device shares this connection with other computers. Step 3: Setting Advanced Options These settings are optional for most users. They include using the Apple wireless device as a bridge between your AirPort Extreme network and an Ethernet network, setting advanced security options, extending the AirPort network to other wireless devices, and fine-tuning other settings. For specific instructions on all these steps, refer to the sections later in this chapter. You can do most of your setup and configuration tasks using AirPort Utility, and following the onscreen instructions to enter your ISP and network information. To set advanced options, you need to use AirPort Utility to manually set up your Apple wireless device and AirPort network.Chapter 3 AirPort Network Designs 15 Using AirPort Utility To set up and configure your computer or Apple wireless device to use AirPort Extreme for basic wireless networking and Internet access, use AirPort Utility and answer a series of questions about your Internet settings and how you would like to set up your network. 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer. 2 Select your device in the list on the left if there is more than one device in your network. Click Continue, and then follow the onscreen instructions to enter the settings from your ISP or network administrator for the type of network you want to set up. See the network diagrams later in this chapter for the types of networks you can set up using AirPort Utility. To set up a more complicated network, or to make adjustments to a network you’ve already set up, use the manual setup features in AirPort Utility. Setting AirPort preferences Use AirPort preferences to set up your wireless device to alert you when there are updates available for your device. You can also set it up to notify you if there are problems detected, and to provide instructions to help solve the problems. To set AirPort preferences: 1 Open AirPort Utility, located in the Utilities folder inside the Applications folder on a Mac, and in Start > All Programs > AirPort on a Windows computer. 2 Do one of the following:  On a Mac, choose AirPort Utility > Preferences  On a Windows computer, choose File > Preferences16 Chapter 3 AirPort Network Designs Select from the following checkboxes:  Select “Check for Updates when opening AirPort Utility” to automatically check the Apple website for software and firmware updates each time you open AirPort Utility.  Select the “Check for updates” checkbox, and then choose a time interval from the pop-up menu, such as weekly, to check for software and firmware updates in the background. AirPort Utility opens if updates are available.  Select “Monitor Apple wireless devices for problems” to investigate problems that may cause the device’s status light to blink amber. With the checkbox selected, AirPort Utility opens if a problem is detected, and then provides instructions to help resolve the problem. This option monitors all of the wireless devices on the network.  Select “Only Apple wireless devices that I have configured” to monitor only the devices you’ve set up using this computer. Monitoring devices for problems requires an AirPort wireless device that supports firmware version 7.0 or later. To set up your wireless device manually: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer. 2 Select your device in the list. 3 Choose Base Station > Manual Setup and enter the password if necessary. The default device password is public. If you don’t see your wireless device in the list: 1 Open the AirPort status menu in the menu bar on a Mac and make sure that you’ve joined the AirPort network created by your wireless device. On a Windows computer, hover the cursor over the wireless network icon in the status tray to make sure the computer is connected to the correct network. The default network name for an Apple wireless device is AirPort Network XXXXXX, where XXXXXX is replaced with the last six digits of the AirPort ID, (or MAC address). The AirPort ID is printed on the bottom of Apple wireless devices. 2 Make sure your computer’s network and TCP/IP settings are configured properly. On a computer using Mac OS X, choose AirPort from the Show pop-up menu in the Network pane of System Preferences. Then choose Using DHCP from the Configure IPv4 pop-up menu in the TCP/IP pane. On a computer using Windows, right-click the wireless connection icon that displays the AirPort network, and choose Status. Click Properties, select Internet Protocol (TCP/IP), and then click Properties. Make sure “Obtain an IP address automatically” is selected.Chapter 3 AirPort Network Designs 17 If you can’t open the wireless device settings: 1 Make sure your network and TCP/IP settings are configured properly. On a computer using Mac OS X, select AirPort from the network connection services list in the Network pane of System Preferences. Click Advanced, and then choose Using DHCP from the Configure IPv4 pop-up menu in the TCP/IP pane. On a computer using Windows, right-click the wireless connection icon that displays the AirPort network, and choose Status. Click Properties, select Internet Protocol (TCP/IP), and then click Properties. Make sure “Obtain an IP address automatically” is selected. 2 Make sure you entered the wireless device password correctly. The default password is public. If you’ve forgotten the device password, you can reset it to public by resetting the device. To temporarily reset the device password to public, hold down the reset button for one second. To reset the device back to its default settings, hold the reset button for five full seconds. If you’re on an Ethernet network that has other devices, or you’re using Ethernet to connect to the device: AirPort Utility scans the Ethernet network to create the list of devices. As a result, when you open AirPort Utility, you may see devices that you cannot configure. Setting Up the AirPort Extreme Network The first step in configuring your Apple wireless device is setting up the device and the network it will create. You can set up most features using AirPort Utility and following the onscreen instructions to enter the information from your ISP or network administrator. To configure a network manually or set advanced options, open your wireless device’s configuration in AirPort Utility and manually set up your device and network. 1 Choose the network of the wireless device you want to configure from the AirPort status menu on a computer using Mac OS X, or from the wireless connection icon in the status tray on a computer using Windows. 2 Open AirPort Utility and select the wireless device from the list. If you don’t see the device you want to configure, click Rescan to scan for available wireless devices, and then select the one you want from the list. 18 Chapter 3 AirPort Network Designs 3 Choose Base Station > Manual Setup and enter the password if necessary. The default device password is public. You can also double-click the name of the wireless device to open its configuration in a separate window. When you open the manual setup window, the Summary pane is displayed. The summary pane provides information and status about your wireless device and network.Chapter 3 AirPort Network Designs 19 If the wireless device reports a problem, the status icon turns yellow. Click Base Station Status to display the problem and suggestions to resolve it. Wireless Device Settings Click the AirPort button, and then click Base Station or Time Capsule, depending on the device you’re setting up, to enter information about the wireless device. Give the Device a Name Give the device an easily identifiable name. This makes it easy for administrators to locate a specific device on an Ethernet network with several devices. Change the Device Password The device password protects its configuration so that only the administrator can modify it. The default password is public. It is a good idea to change the device password to prevent unauthorized changes to it. If the password is not changed from public, you’ll not be prompted for a password when you select it from the list and click Configure. Other Information  Allow configuration over the WAN port. This allows you to administer the wireless device remotely.  Advertise the wireless device over the Internet using Bonjour. If you have an account with a dynamic DNS service, you can connect to it over the Internet.  Set the device time automatically. If you have access to a Network Time Protocol server, whether on your network or on the Internet, choose it from the pop-up menu. This ensures your wireless device is set to the correct time.20 Chapter 3 AirPort Network Designs Set Device Options Click Base Station Options and set the following:  Enter a contact name and location for the wireless device. The name and location are included in some logs the device generates. The contact and location fields may be helpful if you’ve more than one wireless device on your network.  Set status light behavior to either Always On or Flash On Activity. If you choose Flash On Activity, the device status light blinks when there is network traffic.  If your wireless device supports it, select “Check for firmware updates” and choose an increment, such as Daily from the pop-up menu. Wireless Network Settings Click Wireless, and enter the network name, radio mode, and other wireless information. Setting the Wireless Mode AirPort Extreme supports two wireless modes:  Create a wireless network. Choose this option if you’re creating a new AirPort Extreme network.  Extend a wireless network. Choose this option if you plan to connect another Apple wireless device to the network you’re setting up. Naming the AirPort Extreme Network Give your AirPort network a name. This name appears in the AirPort status menu on the AirPort-enabled computers that are in range of your AirPort network.Chapter 3 AirPort Network Designs 21 Choosing the Radio Mode Choose 802.11a/n - 802.11b/g from the Radio Mode pop-up menu if computers with 802.11a, 802.11n, 802.11g, or 802.11b wireless cards will join the network. Each client computer will connect to the network and transmit network traffic at the highest possible speed. Choose 802.11n - 802.11b/g if only computers with 802.11n, 802.11b, or 802.11g compatible wireless cards will join the network. Note: If you don’t want to use an 802.11n radio mode, hold down the Option key and chose a radio mode that doesn’t include 802.11n. Changing the Channel The “channel” is the radio frequency over which your wireless device communicates. If you use only one device (for example, at home), you probably won’t need to change the channel frequency. If you set up several wireless devices in a school or office, use different channel frequencies for devices that are within approximately 150 feet of each other. Adjacent wireless devices should have at least 4 channels between their channel frequencies. So if device A is set to channel 1, device B should be set to channel 6 or 11. For best results, use channels 1, 6, or 11 when operating your device in the 2.4 GHz range. Choose Manually from the Radio Channel Selection pop-up menu, and then click Edit to set the channels manually. AirPort-enabled computers automatically tune to the channel frequency your wireless device is using when they join the AirPort network. If you change the channel frequency, AirPort client computers do not need to make any changes. Password-protect Your Network To password-protect your network, you can choose from a number of wireless security options. In the AirPort pane of AirPort Utility, click Wireless and choose one of the following options from the Wireless Security pop-up menu:  None: Choosing this option turns off all password protection for the network. Any computer with a wireless adapter or card can join the network, unless the network is set up to use access control. See “Setting Up Access Control” on page 47.  WEP: If your device supports it, choose this option and enter a password to protect your network with a Wired Equivalent Privacy (WEP) password. Your Apple wireless device supports 40-bit and 128-bit encryption. To use 40-bit WEP, don’t use an 802.11n radio mode.22 Chapter 3 AirPort Network Designs  WPA/WPA2 Personal: Choose this option to protect your network with Wi-Fi Protected Access. You can use a password between 8 and 63 ASCII characters or a Pre-Shared Key of exactly 64 hexadecimal characters. Computers that support WPA and computers that support WPA2 can join the network. Choose WPA2 Personal if you want only computers that support WPA2 to join your network.  WPA/WPA2 Enterprise: Choose this option if you’re setting up a network that includes an authentication server, such as a RADIUS server, with individual user accounts. Enter the IP address and port number for the primary and optional secondary server, and enter a “shared secret,” which is the password for the server. Choose WPA2 Enterprise if you want only computers that support WPA2 to join the network.  WEP (Transitional Security Network): If your device supports it, you can use this option to allow computers using WPA or WPA2 to join the network. Computers or devices that use WEP can also join the network. WEP (Transitional Security Network) supports 128-bit encryption. To use this option, the wireless device use an 802.11n radio mode. Hold the Option key on your keyboard while clicking the Wireless Security pop-up menu to use WEP (Transitional Security Netowrk). For more information and instructions for setting up WPA or WPA2 on your network, see “Using Wi-Fi Protected Access” on page 45. Setting Wireless Options Click Wireless Options to set additional options for your network.Chapter 3 AirPort Network Designs 23 Setting Additional Wireless Options Use the Wireless Options pane to set the following:  5 GHz network name: Provide a name for the 5 GHz segment of the dual-band network if you want it to have a different name than the 2.4 GHz network.  Country: Choose the country for the location of your network from the Country pop-up menu.  Multicast rate: Choose a multicast rate from the pop-up menu. If you set the multicast rate high, only clients on the network that are within range and can achieve the speed you set will receive transmissions.  Transmit power: Choose a setting from the Transmit Power pop-up menu to set the network range (the lower the percentage, the shorter the network range).  WPA Group Key Timeout: Enter a number in the text field, and choose an increment from the pop-up menu to change the frequency of key rotation.  Use Wide Channels: If you set up your network to use the 5 GHz frequency range, you can use wide channels to provide higher network throughput. Note: Using wide channels is not permitted in some countries.  Create a closed network: Selecting a closed network hides the name of the network so that users must enter the exact network name and password to join the AirPort Extreme network.  Use interference robustness: Interference robustness can solve interference problems caused by other devices or networks. To set more advanced security options, see “Keeping Your Network Secure” on page 45.24 Chapter 3 AirPort Network Designs Setting up a Guest Network Click Guest Network and then enter the network name and other options for the guest network. When you set up a guest network, a portion of your connection to the Internet is reserved for “guests”, wireless clients that can join the guest network and connect to the Internet without accessing your private network. Select “Allow guest network clients to communicate with each other” to allow client computers to share files and services with each other while they’re connected to the guest network. Make sure sharing services are set up on the client computers. Configuring and Sharing Internet Access The next step is setting up your wireless device’s Internet connection and sharing its Internet access with client computers. The following sections tell you what to do, depending on how your device connects to the Internet. You’re Using a DSL or Cable Modem In most cases, you can implement this network design using AirPort Utility and following the onscreen instructions to set up your wireless device and network. You need to use AirPort Utility to manually set up your device only if you want to set up or adjust optional advanced settings.Chapter 3 AirPort Network Designs 25 What It Looks Like How It Works  The Apple wireless device (in this example, a Time Capsule) connects to the Internet through its Internet WAN (<) connection to your DSL or cable modem.  Computers using AirPort or computers connected to the wireless device’s Ethernet LAN port (G) connect to the Internet through the device.  The device is set up to use a single, public IP address to connect to the Internet, and uses DHCP and NAT to share the Internet connection with computers on the network using private IP addresses.  AirPort computers and Ethernet computers communicate with one another through the wireless device. Important: Connect Ethernet computers that are not connected to the Internet to the device’s LAN port (G) only. Since the device can provide network services, you must set it up carefully to avoid interfering with other services on your Ethernet network. What You Need for a DSL or Cable Modem Connection DSL or cable modem to Internet to Ethernet port Time Capsule < Ethernet WAN port 2.4 or 5 GHz Components Check Comments Internet account with DSL or cable modem service provider Does your service provider use a static IP or DHCP configuration? You can get this information from your service provider or the Network preferences pane on the computer you use to access the Internet through this service provider. Apple wireless device (an AirPort Extreme Base Station, an AirPort Express, or a Time Capsule) Place the device near your DSL or cable modem.26 Chapter 3 AirPort Network Designs What to Do If you’re using AirPort Utility to assist you with configuring the Apple wireless device for Internet access: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer. 2 Follow the onscreen instructions and enter the settings you received from your service provider to connect to the Internet, and then set up the device to share the Internet connection with computers on the network. If you’re using AirPort Utility to manually set up your wireless device: 1 Make sure that your DSL or cable modem is connected to the Ethernet WAN port (<) on your Apple wireless device. 2 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer. Select your wireless device and choose Base Station > Manual Setup, or double-click your device’s icon in the list to open the configuration in a separate window. 3 Click the Internet button. Click Internet Connection and choose Ethernet or PPPoE from the Connect Using pop-up menu, depending on which one your service provider requires. If your service provider gave you PPPoE connection software, such as EnterNet or MacPoET, choose PPPoE. Note: If you’re connecting to the Internet through a router using PPPoE and your Apple wireless device is connected to the router via Ethernet, you do not need to use PPPoE on your wireless device. Choose Ethernet from the Connect Using pop-up menu in the Internet pane, and deselect the “Distribute IP addresses” checkbox in the Network pane. Contact your service provider if you aren’t sure which one to select. 4 Choose Manually or Using DHCP from the Configure IPv4 pop-up menu if you chose Ethernet from the Connect Using pop-up menu, depending on how your service provider provides IP addresses.  If your provider gave you an IP address and other numbers with your subscription, use that information to configure the wireless device IP address manually. If you aren’t sure, ask your service provider. Enter the IP address information in the fields below the Configure IPv4 pop-up menu.Chapter 3 AirPort Network Designs 27  If you chose PPPoE, your ISP provides your IP address automatically using DHCP. If your service provider asks you for the MAC address of your wireless device, use the address of the Ethernet WAN port (<), printed on the label on the bottom of the device. If you’ve already used AirPort Utility to set up your wireless device, the fields below the Configure IPv4 pop-up menu may already contain the information appropriate for your service provider. You can change the WAN Ethernet speed if you have specific requirements for the network you’re connected to. In most cases, the settings that are configured automatically are correct. Your service provider should be able to tell you if you need to adjust these settings. Changing the WAN Ethernet speed can affect the way the wireless device interacts with the Internet. Unless your service provider has given you specific settings, use the automatic settings. Entering the wrong settings can affect network performance. Contact your service provider for the information you should enter in these fields. Use this pop-up menu if you need to adjust the speed of the Ethernet WAN port.28 Chapter 3 AirPort Network Designs If you configure TCP/IP using DHCP, choose Using DHCP from the Configure IPv4 pop-up menu. Your IP information is provided automatically by your ISP using DHCP. 5 If you chose PPPoE from the Connect Using pop-up menu, enter the PPPoE settings your service provider gave you. Leave the Service Name field blank unless your service provider requires a service name. Note: With AirPort, you don’t need to use a third-party PPPoE connection application. You can connect to the Internet using AirPort. Your service provider may require you to enter information in these fields. Contact your service provider for the information you should enter in these fields.Chapter 3 AirPort Network Designs 29 If you’re connecting to the Internet through a router that uses PPPoE to connect to the Internet, and your wireless device is connected to the router via Ethernet, you do not need to use PPPoE on your device. Choose Ethernet from the Connect Using pop-up menu in the Internet pane, and deselect the “Distribute IP addresses” checkbox in the Network pane. Because your router is distributing IP addresses, your wireless device doesn’t need to. More than one device on a network providing IP addresses can cause problems. 6 Click PPPoE to set PPPoE options for your connection.  Choose Always On, Automatic, or Manual, depending on how you want to control when your wireless device is connected to the Internet. If you choose Always On, your device stays connected to your modem and the Internet as long as the modem is turned on. If you choose Automatic, the wireless device connects to the modem, which connects to the Internet when you use an application that requires an Internet connection, such as email or an instant message or web application. If you choose Manual, you need to connect the modem to the Internet when you use an application that requires an Internet connection. If you chose Automatic or Manual from the Connection pop-up menu, you need to choose an increment, such as “10 minutes,” from the “Disconnect if idle” pop-up menu. If you don’t use an Internet application after the increment of time has passed, you’ll be disconnected from the Internet. Note: If your wireless device is connected to your modem using an Ethernet LAN port, and your modem is connected to the Internet using PPPoE, you may not be able to use the manual setting.30 Chapter 3 AirPort Network Designs  Enter Domain Name System (DNS) server addresses and a specific domain name your wireless device accesses when you connect to the Internet. 7 Click the Network button and configure how the device will share its Internet access with AirPort and Ethernet computers. If you chose Ethernet from the Connect Using pop-up menu, choose how your device will share the Internet connection from the Connection Sharing pop-up menu.  To share a single Internet connection with AirPort computers and computers connected to the device with Ethernet using DHCP and NAT, choose “Share a public IP address” from the Connection Sharing pop-up menu. Using DHCP and NAT lets the wireless device dynamically and automatically assign IP addresses to client computers, which simplifies each computer’s TCP/IP configuration. See “Setting DHCP and NAT Options” on page 31. By default, the wireless device allows other devices, computers using Ethernet, and computers using AirPort to communicate with each other using non-IP protocols like AppleTalk. If you want to connect an AppleTalk Ethernet printer to the Apple wireless device or use AppleTalk between wired and wireless computers, make sure the devices are connected to the Ethernet LAN port (G) on the device.  To distribute a range of IP addresses using only DHCP, choose “Distribute a range of IP addresses.” See “Setting DHCP Only Options” on page 33.Chapter 3 AirPort Network Designs 31  If you don’t want your wireless device to share its IP address, choose “Off (Bridge Mode).” If you set up your device in bridge mode, AirPort computers have access to all services on the Ethernet network, and the device does not provide Internet sharing services. See “You’re Using an Existing Ethernet Network” on page 37 for more information about setting up your wireless device as a bridge. Using the wireless device as a bridge can be a way to address incompatibilities between the device’s Internet sharing features and your ISP’s connection method. Setting DHCP and NAT Options If you chose “Share a public IP address” from the Connection Sharing pop-up menu, you can set DHCP and NAT options. Click DHCP.  Choose a range of IP addresses from the DHCP Range pop-up menu. Choose 10.0, 192.168, or 172.16 and then enter a beginning and ending address in the DHCP Beginning Address and the DHCP Ending Address fields, depending on which addresses you want the wireless device to provide.  Enter a number in the DHCP Lease field, and then choose minutes, hours, or days from the pop-up menu.  Type a welcome message in the DHCP Message field. This message is displayed when a computer joins your network.  If your network is set up to use a Lightweight Directory Access Protocol (LDAP) server on your network, you can enter the address of the server in the LDAP Server field, and computers on your network will have access to it.32 Chapter 3 AirPort Network Designs  To provide specific IP addresses to specific computers on your wireless network, click the Add (+) button below the DHCP Reservations list, and follow the onscreen instructions to name the reservation and reserve the address by MAC address or DHCP client ID. If you choose MAC address, click Continue and enter the MAC address and specific IP address. Next you can set NAT options for the network. Click NAT.  You can set up a default host on your network. A default host (sometimes known as a DMZ) is a computer on your network that is exposed to the Internet and receives all inbound traffic. A default host may be useful if you use a computer on your AirPort network to play network games, or want to route all Internet traffic through a single computer.  You can set up NAT Port Mapping Protocol (NAT-PMP). NAT-PMP is an Internet Engineering Task Force Internet Draft, an alternative to the more common Universal Plug and Play (UPnP) protocol implemented in many network address translation (NAT) routers. NAT-PMP allows a computer in a private network (behind a NAT router) to automatically configure the router to allow parties outside the private network to contact this computer. Included in the protocol is a method for retrieving the public IP address of a NAT gateway, allowing a client to make this public IP address and port number known to peers that may wish to communicate with it. This protocol is implemented in current Apple products, including Mac OS X 10.4 Tiger and later, AirPort Extreme, AirPort Express, and Time Capsule networking products, and Bonjour for Windows.Chapter 3 AirPort Network Designs 33 You can also set up port mapping. To ensure that requests are properly routed to your web, AppleShare, or FTP server, or a specific computer on your network, you need to establish a permanent IP address for the server or computer, and provide “inbound port mapping” information to the Apple wireless device. See “Directing Network Traffic to a Specific Computer on Your Network (Port Mapping)” on page 49. Setting DHCP Only Options If you chose “Distribute a range of IP addresses” from the Connection Sharing pop-up menu, your wireless device is set up to use DHCP to distribute a range of IP addresses using only DHCP. You cannot use NAT if you chose this option. Click DHCP and enter the beginning and ending addresses you want to distribute to computers joining your wireless network. You can set the additional DHCP options, such as DHCP Lease, DHCP Message, and other options following the instructions above. Setting Up Client Computers To configure TCP/IP on client computers using Mac OS X v10.5: 1 Open System Preferences on the client computer and then click Network. 2 Do one of the following: a If the client computer is using AirPort, select AirPort in the network connection services list, and then click Advanced.34 Chapter 3 AirPort Network Designs Next, choose DHCP from the Configure IPv4 pop-up menu. b If you enabled a DHCP server when you set up the wireless device’s network, and the client computer is using Ethernet, select Ethernet in the network connection services list, and then choose Using DHCP from the Configure pop-up menu.Chapter 3 AirPort Network Designs 35 c If you selected “Distribute a range of IP addresses” when you set up the wireless device’s network, you can provide Internet access to client computers using Ethernet by setting the client IP addresses manually. Select Ethernet in the network connection services list, and then choose Manually from the Configure pop-up menu. When you configure Ethernet clients manually for a wireless device that provides NAT over Ethernet, you can use IP addresses in the range 10.0.1.2 to 10.0.1.200. In the Subnet Mask field, enter 255.255.255.0. In the Router field, enter 10.0.1.1. Enter the same name server address and search domain information that you entered in the wireless device configuration. To configure TCP/IP on client computers using Windows Make sure you’ve installed the wireless adapter in your computer and the software necessary to set up the adapter. To configure TCP/IP on client computers: 1 Open Control Panel from the Start menu, and then click “Network and Internet.” 2 Click “Network and Sharing Center.” 3 Click “Manage network connections” in the Tasks list. 4 Right-click the wireless connection you want to share, and then select Properties. Enter the IP and router addresses from the range your device is providing. Enter the DNS and Search Domain addresses if necessary.36 Chapter 3 AirPort Network Designs 5 Click Internet Protocol Version 4 (TCP/IPv4), and then click Properties.  If you chose “Share a public IP address” in the Network pane of AirPort Utility, select “Obtain an IP address automatically.”  If you chose “Distribute a range of IP addresses” when you set up the wireless device’s network, you can provide Internet access to client computers by setting the client IP addresses manually. Select “Use the following IP address.” When you configure clients manually for a wireless device that provides NAT service, use IP addresses in the range 10.0.1.2 to 10.0.1.200, 172.16.1.2 to 172.16.1.200, or 192.168.1.2 to 192.168.1.200. In the “Subnet mask” field, enter 255.255.255.0. In the “Default gateway” field, enter 10.0.1.1, 172.16.1.1, or 192.168.1.1, depending on which addressing scheme you used. Enter the same name server address and search domain information that you entered in the wireless device configuration.Chapter 3 AirPort Network Designs 37 You’re Using an Existing Ethernet Network You can use AirPort Utility to easily set up the Apple wireless device for Internet access through an existing Ethernet network that already has a router, switch, or other network device providing IP addresses. Use the manual setup features of AirPort Utility if you need to adjust optional advanced settings. What It Looks Like How It Works  The Apple wireless device (in this example, a Time Capsule) uses your Ethernet network to communicate with the Internet through the Ethernet WAN port (<).  AirPort and Ethernet clients access the Internet and the Ethernet network through the Apple wireless device. What You Need for an Ethernet Connection Router to Internet to Ethernet port Time Capsule All Programs > AirPort on a Windows computer. 2 Click Continue and follow the onscreen instructions to connect to your local area network (LAN). If you’re using AirPort Utility to manually set up your wireless device: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer. 2 Select your device and choose Base Station > Manual Setup, or double-click your device icon to open the configuration in a separate window. 3 Click Internet and choose Ethernet from the Connect Using pop-up menu. 4 Choose Manually or Using DHCP from the Configure IPv4 pop-up menu, depending on how IP addresses are provided on your Ethernet network. If you aren’t sure, ask your service provider or network administrator. If your addresses are provided manually, choose Manually from the Configure IPv4 pop-up menu. Enter your IP address information in the fields below the Configure IPv4 pop-up menu. If you’ve already used AirPort Utility to set up your Apple wireless device, the fields below the Configure IPv4 pop-up menu may already contain the appropriate information. Contact your network administrator for the information you should enter in these fields.Chapter 3 AirPort Network Designs 39 If your IP address is provided by DHCP, choose Using DHCP from the Configure IPv4 pop-up menu. 5 Choose Off (Bridge Mode) from the Connection Sharing pop-up menu. Your wireless device “bridges” the Ethernet networks Internet connection to computers connected to the device wirelessly or by Ethernet. See “Setting Up Client Computers” on page 33 for information about how to set up client computers to connect to the Ethernet network.40 Chapter 3 AirPort Network Designs Connecting Additional Devices to Your AirPort Extreme Network Connect a USB printer to the USB port of your Apple wireless device (in this example, a Time Capsule) and everyone on the network can print to it. Connect a USB hub to the USB port of an AirPort Extreme Base Station or a Time Capsule, and then connect a hard disk and a printer so everyone on the network can access them. If you connect a Time Capsule, you can use Time Machine in Mac OS X Leopard (v10.5.2 or later) to back up all of the Mac OS X Leopard computers on the network. What It Looks Like What to Do Follow the instructions in the previous sections to set up your AirPort Extreme network depending on how you connect to the Internet or set up your wireless network. Connect a USB hard disk, printer, or hub to the USB port on your AirPort Extreme Base Station or Time Capsule. Note: If you’re using an AirPort Express in your network, you can connect a USB printer to the USB port, and everyone on the network can print to it. AirPort Express doesn’t support connecting a USB hard disk. DSL or cable modem USB Printer Time Capsule to Internet Ethernet WAN port AirPort Extreme < 2.4 or 5 GHz 2.4 or 5 GHz 2.4 or 5 GHzChapter 3 AirPort Network Designs 41 Using Apple TV on Your AirPort Extreme Network to Play Content from iTunes When you connect Apple TV to your AirPort Extreme network wirelessly, or using Ethernet, and then connect Apple TV to your widescreen TV, you can enjoy your favorite iTunes content including movies, TV shows, music, and more. (See the documentation that came with your Apple TV for instructions setting it up.) Setting Advanced Options Connecting Additional Wireless Devices to Your AirPort Network You can connect additional Apple wireless devices to extend the range of your wireless network. For example, you can connect an AirPort Extreme Base Station or a Time Capsule using Ethernet. A network with devices connected using Ethernet is known as a roaming network. You can also connect Apple wireless devices wirelessly to extend the network. DSL or cable modem to Internet to Ethernet port < Ethernet WAN port Time Capsule Apple TV 2.4 GHz 2.4 or 5 GHz42 Chapter 3 AirPort Network Designs Setting Up Roaming Several AirPort Extreme Base Stations or Time Capsules can be set up to create a single wireless network. Client computers using AirPort can move from device to device with no interruption in service (a process known as roaming). To set up roaming: 1 Connect all of the AirPort Extreme Base Stations and Time Capsules to the same subnet on your Ethernet network. 2 Give each device a unique name. 3 Give each device the same network name and password. 4 Set up the devices as bridges, following the instructions in the previous section. If you want one device to assign IP addresses using DHCP, also do the following: 1 Set up one device to act as the DHCP server. 2 Set up the other devices as bridges, following the instructions in the previous section. The device acting as a DHCP server can also receive its IP address via DHCP from a server on an Ethernet network or from a cable or DSL modem connected to an Internet service provider (ISP). to Ethernet port Ethernet LAN ports to Internet AirPort Extreme DSL or cable modem G Time Capsule < Ethernet WAN port 2.4 or 5 GHz 2.4 GHzChapter 3 AirPort Network Designs 43 Extending the Range of an 802.11n Network Extending the range of an 802.11n network is simpler if you’re connecting another 802.11n device. Connecting two Apple 802.11n wireless devices makes the WDS setup process more straightforward. To extend the range of an 802.11n network: 1 Open AirPort Utility and select the device that will connect to the Internet. See the previous sections of this document for instructions about setting up your wireless device, depending on your Internet connection. 2 Choose Base Station > Manual Setup, or double-click the device’s icon to open the configuration in a separate window. Enter the password if necessary. 3 Click the AirPort button, and then click Wireless. 4 Choose “Create a wireless network” from the Wireless Mode pop-up menu, and then select the “Allow this network to be extended” checkbox. 5 Next, select the device that will extend this network and choose Base Station > Manual Setup, or double-click the device’s icon to open its configuration in a separate window. Enter the password if necessary. 6 Choose “Extend a wireless network” from the Wireless Mode pop-up menu, and then choose the network you want to extend from the Network Name pop-up menu. 7 Enter the network name and password if necessary.44 Chapter 3 AirPort Network Designs 8 Click Update to update the device with new network settings. Controlling the Range of Your AirPort Network You can also shorten the range of your AirPort network. This might be useful if you want to control who has access to the network by restricting the range to a single room, for example. To shorten the range of your AirPort network: 1 Open AirPort Utility (in the Utilities folder in the Applications folder on a Macintosh computer, or in Start > All Programs > AirPort on a computer using Windows). 2 Select your wireless device and choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 3 Click the AirPort button, and then click Wireless. 4 Click Wireless Options, and then choose a percentage setting from the Transmit Power pop-up menu. The lower the percentage is, the shorter the range is.Chapter 3 AirPort Network Designs 45 Keeping Your Network Secure Your network is protected by the password you assign to it. However, you can take additional steps to help keep your network secure. Networks managed by Simple Network Management Protocol (SNMP) may be vulnerable to denial-of-service attacks. Similarly, if you configure your wireless device over the WAN port, it may be possible for unauthorized users to change network settings. When remote configuration is enabled, the device’s Bonjour information (the device name and IP address) is published over the WAN port. Turning off remote configuration may provide additional security. To help protect your network and wireless device: 1 Open AirPort Utility, select your device, and choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 2 Click the Advanced button, and then click Logging & SNMP. 3 Make sure the Allow SNMP Access and “Allow SNMP over WAN” checkboxes are not selected. Using Wi-Fi Protected Access AirPort Extreme supports WPA and WPA2 security standard for wireless networks. Using Mac OS X v10.3 or later or Windows XP with Service Pack 2, and 802.1X authentication capabilities, WPA security delivers more sophisticated data encryption than WEP, and also provides user authentication, which was virtually unavailable with WEP. If your computer has an AirPort Extreme wireless card installed, you can take advantage of the security updates in WPA2, including AES-CCMP encryption. AirPort Extreme supports two modes of WPA and WPA2: Enterprise mode, which uses an authentication server for user authentication, and Personal mode, which relies on the capabilities of TKIP for WPA and AES-CCMP for WPA2, without requiring an authentication server. Enterprise mode is designed for a larger network in which an IT professional is most likely setting up and managing the network. In order to set up a WPA or WPA2 Enterprise network, an 802.1X connection must be set up first in Network preferences on a Mac. To set up an 802.1x connection on a Windows computer, see the documentation that came with your computer. The 802.1X connection requires an authentication protocol, like TTLS, LEAP, or PEAP. Setting up a WPA or WPA2 Enterprise network requires setting up an authentication server, such as a RADIUS server, to manage and validate network users’ credentials, such as user names, passwords, and user certificates. See the documentation that came with the server to set it up. 46 Chapter 3 AirPort Network Designs Personal mode is for the home or small office network and can be set up and managed by most users. Personal mode does not require a separate authentication server. Network users usually only need to enter a user name and password to join the network. Note: If you change an existing WDS network from WEP to WPA, you’ll need to reset the wireless devices and set up your network again. For information about resetting your Apple wireless device, see the documentation that came with it. To set up a WPA or WPA2 Enterprise network: On a computer using Mac OS X, you first need to set up an 802.1x connection. 1 Open System Preferences, click Network, and then click AirPort. 2 Click Advanced, and then click 802.1X 3 Enter the settings for the connection. Note: Some of the authentication protocols require digital certificate authorization on the server. See the documentation that came with your server to create and distribute digital certificates. 4 Click OK to save the connection settings. To use AirPort Utility to set up a WPA or WPA2 Enterprise network on computers using Mac OS X and Windows XP: 1 Open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 2 Choose WPA/WPA2 Enterprise, or WPA2 Enterprise from the Wireless Security pop-up menu, depending on the capabilities of the client computers that will join your network. 3 Click Configure RADIUS, and enter the IP address, port, and shared secret (or password) of the primary and secondary RADIUS authentication servers. Check with the administrator of the RADIUS server for information to type in these fields. To set up a WPA or WPA2 Personal network: 1 Open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 2 Choose WPA/WPA2 Personal or WPA2 Personal from the Wireless Security pop-up menu depending on the capabilities of the client computers that will join your network. 3 Type a password of 8 to 63 ASCII characters.Chapter 3 AirPort Network Designs 47 Setting Up Access Control Access control lets you specify which computers can send or receive information through the wireless device to the wired network. Each wireless-enabled computer has a unique MAC address. You can restrict access by creating an access control list that includes only the MAC addresses for computers you want to access your wired network. To find the MAC address (AirPort ID) of your computer’s AirPort Card, click the AirPort button in the Network pane of System Preferences. To set up the access control list: 1 Open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup. Enter the password if necessary. 2 Click the AirPort button, and then click Access. 3 Choose Timed Access or RADIUS from the MAC Address Access Control pop-up menu, depending on the device you’re setting up.  If you choose Timed Access, click the Add (+) button and enter the MAC address and description or name of the computers you’re allowing to access the network. You can also click This Computer to add the MAC address and name of the computer you’re using to set up this wireless device. Double-click the computer in the list and choose a value from each pop-up menu. Choose a day of the week or Everyday from the day pop-up menu, and then choose either “all day” or “between” from the other pop-up menu. If you choose “between,” you can edit the times of the day by double-clicking in the time fields.48 Chapter 3 AirPort Network Designs  If you choose RADIUS, enter the type of RADIUS service, the RADIUS IP addresses, shared secret, and primary port for the primary RADIUS server. Enter the information for the secondary RADIUS server if there is one. Check with the server administrator if you don’t have that information. Important: AirPort access control prevents computers that aren’t on the access control list from accessing the AirPort network. For information on how to prevent unauthorized computers from joining the AirPort network, see “Setting Up the AirPort Extreme Network” on page 17. You can also add the MAC address of a third-party 802.11 wireless networking card to the access control list. Most third-party cards have the MAC address on a label attached to the metal case of the card. Access control is not compatible with WPA or WPA2 Enterprise mode. You can use either access control or WPA Enterprise in a network, but you can’t use both. Using a RADIUS Server Using a RADIUS server on your network lets you authenticate MAC addresses (AirPort IDs) on a separate computer, so that each device on the network doesn’t need to store the MAC addresses of computers that have access to the network. Instead, all the addresses are stored on a server that is accessed through a specific IP address. To set up authentication using a RADIUS server: 1 On the server, enter the MAC addresses of the computers that will access the network. 2 When the RADIUS server is set up, open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 3 Click AirPort, click Access, and then choose RADIUS from the MAC Address Access Control pop-up menu. 4 Choose a format from the RADIUS pop-up menu. If you choose Default, your wireless device formats the MAC addresses as 010203- 0a0b0c, and they are used as the user names on the RADIUS server. The shared secret is the password for users joining the network. This format is often used for Lucent and Agere servers. If you choose Alternate, MAC addresses are formatted as 0102030a0b0c and are used for both the user name and password by users joining the network. This format is often used for Cisco servers.Chapter 3 AirPort Network Designs 49 5 Enter the IP address, port, and shared secret (or password) for the primary and secondary servers. See the RADIUS documentation that came with your server, or check with the network administrator for more information on setting up the RADIUS server. The access control list and RADIUS work together. When a user tries to join a network that authenticates using access control or a RADIUS server, the wireless device searches first in the access control list, and if the MAC address is there, the user can join the network. If the MAC address is not in the access control list, the device checks the RADIUS server for the MAC address. If it is there, the user can join the network. Note: RADIUS access control is not compatible with WPA or WPA2 Personal mode. You can use either RADIUS access control or WPA Enterprise in a network, but you can’t use both. Directing Network Traffic to a Specific Computer on Your Network (Port Mapping) AirPort Extreme uses Network Address Translation (NAT) to share a single IP address with the computers that join the AirPort Extreme network. To provide Internet access to several computers with one IP address, NAT assigns private IP addresses to each computer on the AirPort Extreme network, and then matches these addresses with port numbers. The wireless device creates a port-to-private IP address table entry when a computer on your AirPort (private) network sends a request for information to the Internet. 50 Chapter 3 AirPort Network Designs If you’re using a web, AppleShare, or FTP server on your AirPort Extreme network, other computers initiate communication with your server. Because the Apple wireless device has no table entries for these requests, it has no way of directing the information to the appropriate computer on your AirPort network. To ensure that requests are properly routed to your web, AppleShare, or FTP server, you need to establish a permanent IP address for your server and provide inbound port mapping information to your Apple wireless device. To set up inbound port mapping: 1 Open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 2 Click the Advanced button, and then click Port Mapping. 3 Click the Add (+) button and choose a service, such as Personal File Sharing, from the Service pop-up menu.Chapter 3 AirPort Network Designs 51 Type any additional information you need in the text fields. To use port mapping, you must configure TCP/IP manually on the computer that is running the web, AppleShare, or FTP server. You can also set up a computer as a default host to establish a permanent IP address for the computer and provide inbound port mapping information to the AirPort Extreme Base Station or AirPort Express. This is sometimes known as a DMZ and is useful when playing some network games or video conferencing. To set up a default host: 1 Open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 2 Click the Internet button, and then click NAT. 3 Select the “Enable Default Host at” checkbox. The default IP address is 10.0.1.253. 4 Enter the same IP address on the host computer. Logging You can set up your wireless device to log status information to the Mac OS X system log or the Syslog application on a Windows computer. This is helpful for understanding problems and monitoring a device’s performance. To set up logging: 1 Open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 2 Click the Advanced button, and then click Statistics.52 Chapter 3 AirPort Network Designs 3 Enter the IP address of the computer that will receive the logs in the Syslog Destination Address field. 4 Choose a level from the Syslog Level pop-up menu. You need to assign a Network Time Protocol (NTP) server for each wireless device, so the log information will contain the accurate time of the status logs. To set the time automatically: 1 Open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 2 Click the AirPort button, and then click Base Station. 3 Select the “Set time automatically” checkbox, and then choose an NTP server from the pop-up menu if you have access to one on your network or on the Internet. If you click “Logs and Statistics” you can view and export logs, and view wireless client and DHCP client information. If you export the logs, use the Mac OS X Console application, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer, to view the logs on the computer receiving them. Using Back to My Mac on your Wireless Network If you have a paid MobileMe subscription (not a free trial), you can use Back to My Mac to access your AirPort Base Station or Time Capsule. You can access the base station or Time Capsule to monitor the network or make changes to the base station or Time Capsule settings. You can also access the hard disk built into the Time Capsule or an external USB hard disk connected to the base station or Time Capsule. To set up Back to My Mac on your wireless device: 1 Click MobileMe in the Advanced pane. 2 Enter your MobileMe account and password.Chapter 3 AirPort Network Designs 53 Setting up IPv6 IPv6 is a new version of Internet Protocol (IP). IPv6 is currently used primarily by some research institutions. Most computers do not need to set up or use IPv6. The primary advantage of IPv6 is that it increases the address size from 32 bits (the current IPv4 standard) to 128 bits. An address size of 128 bits is large enough to support billions and billions of addresses. This allows for more addresses or nodes than are currently available. IPv6 also provides more ways to set up the address and simpler autoconfiguration. By default, IPv6 is configured automatically, and the default settings are sufficient. However, if your network administrator or Internet service provider (ISP) has specifically told you to configure IPv6 manually, follow the instructions below. Open AirPort Utility, select your wireless device, and then choose Base Station > Manual Setup. Enter the password if necessary. Click the Advanced button, and then click IPv6. To manually set IPv6 options: 1 Choose Node or Tunnel from the IPv6 mode pop-up menu, depending on the method you were instructed to use. 2 Choose Manually from the Configure IPv6 pop-up menu, and enter the information you were given from your ISP or network administrator. Customizing the IPv6 firewall If your wireless device supports it, you can use AirPort Utility to adjust IPv6 firewall settings. To adjust IPv6 firewall settings: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer. 2 Select your device from the list, and then enter the password. 3 Click the Advanced button, and then click IPv6 Firewall By default, “Allow Teredo tunnels” and “Allow incoming IPSec authentication” are selected. To provide access to specific devices on your network from outside the IPv6 firewall, click the Add (+) button and enter the IPv6 address and/or the port for the device. To use an IPv6 firewall, you need an Apple 802.11n wireless device.54 Chapter 3 AirPort Network Designs Sharing and Securing USB Hard Disks on Your Network If you connect a USB hard disk to your AirPort Extreme Base Station or Time Capsule, computers connected to the network—both wireless and wired, Mac and Windows— can use it to back up, store, and share files. If you’re using a Time Capsule, you don’t need to connect a hard disk to it. Every Time Capsule includes an internal AirPort disk. To share a hard disk on your network: 1 Plug the hard disk into the USB port on the back of the AirPort Extreme Base Station or Time Capsule. 2 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer. 3 Select your AirPort Extreme Base Station or your Time Capsule, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. Enter the password if necessary. 4 Click the Disks button, and then click File Sharing. 5 Choose “With a disk password,” or “With base station password” if you want to secure the shared disk with a password, or choose “With accounts” if you want to secure the disk using accounts.  If you choose to use accounts, click Configure Accounts, click the Add (+) button, and then enter a name and password for each user that will access the disk. 6 Choose “Not allowed,” “Read only,” or “Read and write” to assign guest access to the disk. 7 Select the “Share disks over Ethernet WAN port” checkbox if you want to provide remote access to the disk over the WAN port. Data transfer speed may vary, depending on the network. to Internet DSL or cable modem AirPort Extreme USB hard disk < Ethernet WAN port 2.4 or 5 GHz 2.4 or 5 GHzChapter 3 AirPort Network Designs 55 Using a Time Capsule in Your Network If you’re using a Time Capsule and a computer with Mac OS X Leopard (v10.5.2 or later), you can use Time Machine to automatically back up all of the computers on the network that are using Leopard. Other Mac computers and Windows computers can access the Time Capsule’s internal AirPort disk to back up, store, and share files. And because every Time Capsule is also a full-featured 802.11n base station, you can set up your Time Capsule to share an Internet connection with computers on the AirPort network it creates. For information about using your Time Capsule with Time Machine in Mac OS X Leopard, search for “Time Capsule” in Mac Help. Connecting a USB Printer to an Apple Wireless Device You can connect a compatible USB printer to your Apple wireless device (an AirPort Extreme Base Station, AirPort Express, or Time Capsule), so that anyone on the network using Mac OS X v10.2.3 or later, Windows XP with Service Pack 2, or Windows Vista can print to that printer. To use a printer on your network: 1 Connect the printer to the USB port on the Apple wireless device. 2 Set up the client computers:  On a computer using Mac OS X v10.5 or later, open System Preferences and click Print & Fax. Select the printer from the Printers list. If the printer isn’t in the list, click Add (+) at the bottom of the list, locate the printer, and then click Add.  On a computer using Mac OS X v10.2.3 or later, open Printer Setup Utility located in the Utilities folder in the Applications folder, and then select the printer from the list. If the printer is not in the list, click Add, choose Bonjour from the pop-up menu, and then select the printer from the list. to Internet DSL or cable modem Time Capsule < Ethernet WAN port 2.4 or 5 GHz 2.4 or 5 GHz 2.4 GHz56 Chapter 3 AirPort Network Designs  On a computer using Windows, install Bonjour for Windows from AirPort Utility CD, and follow the onscreen instructions to connect to the printer. You can change the name of the printer from the default name to one you choose. To change the name of your USB printer: 1 Open AirPort Utility, select your device, and then choose Base Station > Manual Setup, or double-click the device icon to open its configuration in a separate window. 2 Click the Printer button and type a name for the printer in the USB Printers field. Adding a Wireless Client to Your 802.11n Network If your Apple wireless device supports it, and your network is password-protected using WPA Personal or WPA/WPA2 Personal, you can provide wireless clients access to your network without requiring them to enter the network password. When you allow a client access to your network, the client’s name and wireless MAC address (or AirPort ID) are stored in the access control list of AirPort Utility until you remove them from the list. You can provide 24 hours of access, after which time the client will no longer be able to access your network. When you provide a client access to your wireless network, the client does not need to enter the network password. To allow client access to your network: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a Windows computer. 2 Select your Apple wireless device and choose Base Station > Manual Setup. Enter the password if necessary. 3 Choose Add Wireless Clients from the Base Station menu. 4 Select how you want the client to access the network:  Select PIN to enter the eight-digit number provided by the client requesting network access.  Select “First attempt” to allow network access to the first client attempting to join the network.  Select “Limit client’s access to 24 hours” if you want to provide only one day of access to your network. If you don’t select this option, the client will have access to your network until you remove the name from the list.Chapter 3 AirPort Network Designs 57 Solving Problems If you have trouble connecting to the Internet with any AirPort Extreme network design, try the following: On a computer using Mac OS X:  Make sure the wireless device is connected to the Internet. The computers on your AirPort network cannot connect to the Internet if your device is not connected to the Internet.  Check your Internet connection using your computer. If you can’t connect with your computer, the problem may be with your Internet connection.  On a Mac using Mac OS X v10.5, check the active network services in the Network pane of System Preferences. Make sure the ports you want to use are active.  Open Network preferences and then click AirPort. Make sure that the computer has joined the AirPort network created by your wireless device.  Restart your computer. This renews the IP address you receive from the wireless device. The IP addresses should be in the range of 10.0.1.2 to 10.0.1.200, 172.16.1.2 to 172.16.1.200, or 192.168.1.2 to 192.168.1.200, depending on the address scheme the wireless device uses.  If the wireless device is set up as a DHCP server, make sure you choose “Share a public IP address” from the Connection Sharing pop-up menu on the Internet Connection pane of Internet settings in AirPort Utility.  If you’re using a cable modem and your wireless device cannot connect to the Internet, turn off the cable modem, wait a few minutes, and then turn it on again. On a computer using Windows:  Make sure the wireless device is connected to the Internet. The computers on your AirPort network cannot connect to the Internet if your device is not connected to the Internet.  Check your Internet connection using your computer. If you can’t connect with your computer, the problem may be with your Internet connection.  Right-click the wireless connection icon, and then choose Status.58 Chapter 3 AirPort Network Designs  Make sure that the computer has joined the AirPort network created by your wireless device.  Restart your computer. This renews the IP address you receive from the wireless device. The IP addresses should be in the range of 10.0.1.2 to 10.0.1.200, 172.16.1.2 to 172.16.1.200, or 192.168.1.2 to 192.168.1.200 depending on the address scheme the device uses.  If the device is set up as a DHCP server, make sure the “Obtain an IP address automatically” checkbox is selected in the General pane of Internet Protocol (TCP/IP) Properties. Right-click the wireless connection icon and click Properties. Click Internet Protocol (TCP/IP), and then click Properties. More Information About AirPort You can find more information about AirPort in the following locations:  AirPort Utility Help Look in AirPort Utility Help for information on setting up an AirPort Extreme network; using an AirPort Extreme Base Station, an AirPort Express, or a Time Capsule; editing settings; avoiding sources of interference; locating additional information on the Internet; and more. On a computer using Mac OS X, open AirPort Utility and choose Help > AirPort Utility Help. On a computer using Windows, open AirPort Utility and click Help.  World Wide Web Apple AirPort website at www.apple.com/airportextreme Apple Support website at www.apple.com/support/airport4 59 4 Behind the Scenes This chapter defines terms and concepts used to discuss computer networks. Use it as a reference to help you understand what is taking place behind the scenes of your AirPort wireless network. Basic Networking Packets and Traffic Information travels across a network in chunks called packets. Each packet has a header that tells where the packet is from and where it’s going, like the address on the envelope when you send a letter. The flow of all these packets on the network is called traffic. How Information Reaches Its Destination Hardware Addresses Your computer “listens” to all of the traffic on its local network and selects the packets that belong to it by checking for its hardware address (also called the media access control, or MAC address) in the packet header. This address is a number unique to your computer. Every hardware product used for networking is required to have a unique hardware address permanently embedded in it. Your AirPort Card’s number is called the AirPort ID. IP Addresses Since the Internet is a network of networks (connecting millions of computers), hardware addresses alone are not enough to deliver information on the Internet. It would be impossible for your computer to find its packets in all the world’s network traffic, and impossible for the Internet to move all traffic to every network.60 Chapter 4 Behind the Scenes So, your computer also has an Internet Protocol (IP) address that defines exactly where and in what network it’s located. IP addresses ensure that your local Ethernet network receives only the traffic intended for it. Like the hierarchical system used to define zip codes, street names, and street numbers, IP addresses are created according to a set of rules, and their assignment is carefully administered. The hardware address is like your name; it uniquely and permanently identifies you. But it doesn’t offer any clues about your location, so it’s only helpful in a local setting. An IP address is like your street address, which contains the information that helps letters and packages find your house. Rules for Sending Information (Protocols) A protocol is a set of rules that define how communication takes place. For instance, a networking protocol may define how information is formatted and addressed, just as there’s a standard way to address an envelope when you send a letter. Using the AirPort Extreme Base Station This section describes the different network interfaces of the AirPort Extreme Base Station and describes the functions the base station can provide. Base Station Interfaces To use the AirPort Extreme Base Station, you configure how its networking interfaces will be used. The AirPort Extreme Base Station has five hardware networking interfaces:  AirPort interface: The AirPort interface creates an AirPort network for AirPortenabled computers to join. The base station can provide IP services such as DHCP and NAT using this interface. The base station cannot use the AirPort interface to establish a connection with the Internet.  Ethernet WAN (<) interface: Use the Ethernet WAN interface to connect DSL or cable modems and connect to the Internet.  Ethernet LAN (G) interface: If your base station has one or more Ethernet LAN interface ports, you can use them to provide IP services to local Ethernet clients.  USB (d) interface: Use the USB interface to connect a USB printer or hard disk to the AirPort Extreme Base Station. Status light Ethernet WAN port Power port USB port Ethernet ports Reset button Security slot < G ¯ ∏ dChapter 4 Behind the Scenes 61 Using the Time Capsule This section describes the different network interfaces of the Time Capsule and describes the functions it can provide. Time Capsule Interfaces To use your Time Capsule, you configure how its networking interfaces will be used. The Time Capsule has five hardware networking interfaces:  AirPort interface: The AirPort interface creates an AirPort network for AirPortenabled computers to join. The Time Capsule can provide IP services such as DHCP and NAT using this interface. The Time Capsule cannot use the AirPort interface to establish a connection with the Internet.  Ethernet WAN (<) interface: Use the Ethernet WAN interface to connect DSL or cable modems and connect to the Internet.  Ethernet LAN (G) interface: The Time Capsule has three Ethernet LAN interface ports. You can use them to provide IP services to local Ethernet clients.  USB (d) interface: Use the USB interface to connect a USB printer to the Time Capsule. Using the AirPort Express This section describes the different network interfaces of the AirPort Express Base Station and describes the functions the base station can provide. AirPort Express Interfaces To set up the AirPort Express Base Station, you configure how its networking interfaces will be used. The AirPort Express Base Station has four hardware networking interfaces:  AirPort interface: The AirPort interface creates an AirPort network for AirPortenabled computers to join. The base station can provide IP services such as DHCP and NAT using this interface. The base station cannot use the AirPort interface to establish a connection with the Internet.  Ethernet WAN (<) interface: Use the Ethernet WAN interface to connect DSL or cable modems and connect to the Internet.  USB (d) interface: Use the USB interface to connect a USB printer to the AirPort Extreme Base Station. < G ≤ d ∏ Status light Ethernet WAN port Power port Reset button USB port Ethernet ports Security slot62 Chapter 4 Behind the Scenes  Audio (-) interface: Use the analog and optical digital audio stereo mini-jack to connect an AirPort Express to a home stereo or powered speakers. Apple Wireless Device Functions  Bridge: Each Apple wireless device is configured by default as a bridge between the wireless AirPort network and the wired Ethernet network. Connecting an AirPort network to an Ethernet network through the device’s Ethernet LAN port (G) bridges the wireless AirPort network to the wired Ethernet network. Important: If you’re connecting an Ethernet network to the device’s Ethernet LAN port (G), make sure the Ethernet network does not have an Internet connection.  NAT router: One of the most powerful features of Apple wireless devices is their ability to share one Internet connection with several computers. To provide this service, the device acts as a router. The device can be configured to provide both bridging services and routing services at the same time.  DHCP server: When you configure the wireless device to act as a DHCP server, it provides IP addresses to both wired and wireless client computers that are configured to obtain IP addresses using DHCP. Using DHCP makes IP configuration simple for client computers, since they don’t need to enter their own IP information. Status light AC plug adapter USB port Ethernet port Line Out port (Analog and optical digital audio mini-jack) Reset button G - d ∏Chapter 4 Behind the Scenes 63 Items That Can Cause Interference with AirPort The farther away the interference source, the less likely it is to cause a problem. The following items can cause interference with AirPort communication:  Microwave ovens  DSS (Direct Satellite Service) radio frequency leakage  The original coaxial cable that came with certain types of satellite dishes. Contact the device manufacturer and obtain newer cables.  Certain electrical devices, such as power lines, electrical railroad tracks, and power stations  Cordless telephones that operate in the 2.4 gigahertz (GHz) range. If you have problems with your phone or AirPort communication, change the channel of your base station.  Other AirPort and wireless networks  Adjacent base stations using nearby channels. If base station A is set to channel 1, base station B should be set to channel 6 or 11. For best results, use channels 1, 6, or 11 when operating your base station in the 2.4 GHz range.  Moving objects that temporarily place metal between your computer and the base stationGlossary 64 Glossary 10Base-T The most common cabling method for Ethernet. 10Base-T conforms to IEEE standard 802.3. It was developed to enable data communications over unshielded twisted pair (telephone) wiring at speeds of up to 10 megabits per second (Mbps) up to distances of approximately 330 feet on a network segment. 10/100Base-T A networking standard that supports data transfer rates up to 100 Mbps. Because it is 10 times faster than Ethernet, it is often referred to as Fast Ethernet. 10/100/1000Base-T A term describing various technologies for transmitting Ethernet packets at a rate of a gigabit per second. Sometimes referred to as Gigabit Ethernet. In 2000, Apple’s Power Mac G4 and PowerBook G4 were the first mass-produced personal computers featuring the 10/100/1000Base-T connection. It quickly became a built-in feature in many other computers. 802.11a An IEEE standard for a wireless network that operates at 5 GHz with rates up to 54 Mbps. 802.11b An IEEE standard for a wireless network that operates at 2.4 GHz with rates up to 11 Mbps. 802.11g An IEEE standard for a wireless network that operates at 2.4 GHz Wi-Fi with rates up to 54 Mbps. 802.11n A task group of the IEEE 802.11 committee whose goal is to define a standard for high throughput speeds of at least 100 Mbps on wireless networks. Some proposals being fielded by the task group include designs for up to 540 Mbps, Multiple-input multiple-output (MIMO) technology, using multiple receivers and multiple transmitters in both the client and access point to achieve improved performance, is expected to form the basis of the final specification. See Mbps, MIMO. access point Also known as a wireless access point (WAP), a device that connects wireless devices together to form a network. authentication The process that occurs after association to verify the identity of the wireless device or end user and allow access to the network. See WPA, WPA2.Glossary 65 backbone The central part of a large network that links two or more subnetworks. The backbone is the primary data transmission path on large networks such as those of enterprises and service providers. A backbone can be wireless or wired. bandwidth The maximum transmission capacity of a communications channel at any point in time. Bandwidth, usually measured in bits per second (bps), determines the speed at which information can be sent across a network. If you compare the communications channel to a pipe, bandwidth represents the pipe width and determines how much data can flow through the pipe at any one time. The greater the bandwidth, the faster data can flow. See bps. base station In the area of wireless computer networking, a base station is a radio receiver/transmitter that serves as the hub of the local wireless network, and may also be the gateway between a wired network and the wireless network. A base station can also be referred to as an access point or router. Bluetooth A technology designed for short-range, wireless communications among computing devices and mobile products, including PCs and laptop computers, personal digital assistants, printers, and mobile phones. Designed as a cable replacement, Bluetooth enables short-range transmission of voice and data in the 2.4 GHz frequency spectrum within a range of about 30 feet. bps Bits per second. A measure of data transmission speed across a network or communications channel; bps is the number of bits that can be sent or received per second. It measures the speed at which data is communicated and should not be—but often is—confused with bytes per second. Whereas “bits” is a measure of transmission speed, “bytes” is a measure of storage capacity. See bandwidth, Mbps. bridge A wireless device that connects multiple networks together. Using an access point as a bridge turns off Network Address Translation (NAT) and DHCP routing and simply extends the range of service. broadband A comparatively fast Internet connection possessing sufficient bandwidth to accommodate multiple voice, data, and video channels simultaneously. Cable, DSL, and satellite are all considered to be broadband channels; they provide much greater speed than dial-up Internet access over telephone wires. See cable modem, DSL. broadband modem A device that connects a local computer or network to a highspeed Internet service, such as DSL or Cable Internet. See cable modem, DSL. cable modem A device used with broadband Internet service provided by a traditional cable TV service. Cable modems convert analog data from the cable TV system into a digital format that can be used by a computer. See broadband modem.66 Glossary channel One portion of the available radio spectrum that all devices on a wireless network use to communicate. Changing the channel on the access point/router can help reduce interference. client Any computer or device connected to a network that requests files and services (files, print capability) from the server or other devices on the network. The term also refers to end users. DHCP Dynamic Host Configuration Protocol. A protocol for dynamically assigning IP addresses from a predefined list to nodes on a network. When they log on, network nodes automatically receive an IP address from a pool of addresses served by a DHCP. The DHCP server provides (or leases) an IP address to a client for a specific period of time. The client will automatically request a renewal of the lease when the lease is about to run out. If a lease renewal is not requested and it expires, the address is returned to the pool of available IP addresses. Using DHCP to manage IP addresses simplifies client configuration and efficiently utilizes IP addresses. See IP address. DNS Domain Name System. An Internet service that translates alphanumeric domain names to assigned IP addresses and vice versa. The term is typically used to describe the server that makes the translation. Every website has its own specific IP address on the Internet. DNS typically refers to a database of Internet names and addresses that translates the alphanumeric names to the official Internet Protocol numbers and vice versa. For instance, a DNS server converts a name like mywebsite.com to a series of numbers like 107.22.55.26. See IP, IP address. DSL Digital Subscriber Line. A dedicated digital circuit between a residence or business and a telephone company’s central office. It allows high-speed data, voice, and video transmissions over existing twisted-pair copper plain old telephone service (POTS) telephone wires. See broadband. dual-band A device that is capable of operating in either of two frequencies. On a wireless network, dual-band devices are capable of operating in the 2.4 GHz (802.11b/g) or 5 GHz (802.11a) bands. encryption A mechanism for providing data confidentiality. See WPA, WPA2. Ethernet The most popular international standard technology for wired local area networks (LANs). It provides from 10 Mbps transmission speeds on basic 10Base-T Ethernet networks to 100 Mbps transmission speeds on Fast Ethernet networks, 1000 Mbps on Gigabit Ethernet, and 10,000 Mbps on 10 Gigabit Ethernet.Glossary 67 firewall A system of software and/or hardware that resides between two networks to prevent access by unauthorized users. The most common use of a firewall is to provide security between a local network and the Internet. Firewalls can make a network appear invisible to the Internet and can block unauthorized and unwanted users from accessing files and systems on the network. Hardware and software firewalls monitor and control the flow of data in and out of computers in both wired and wireless enterprise, business and home networks. They can be set to intercept, analyze, and stop a wide range of Internet intruders and hackers. gateway In the wireless world, a gateway is an access point with additional software capabilities such as providing NAT and DHCP. Gateways may also provide VPN support, roaming, firewalls, various levels of security, and so on. hotspot A location where users can access the Internet using Wi-Fi laptops and other Wi-Fi enabled devices. Access may be provided free or for a fee. Hotspots are often found at coffee shops, hotels, airport lounges, train stations, convention centers, gas stations, truck stops, and other public meeting areas. Corporations and campuses often offer hotspot service to visitors and guests. Hotspot service is sometimes available aboard planes, trains, and boats. hub A multiport device used to connect client devices to a wired Ethernet network. Hubs can have numerous ports and can transmit data at speeds ranging from 10 to 1000 Mbps to all the connected ports. A small wired hub may only connect 4 computers; a large hub can connect 48 or more. See router. IEEE 802.11 The family of specifications developed by the Institute of Electrical and Electronics Engineers (IEEE) 802.11 committee, which establishes standards for wireless Ethernet networks. 802.11 standards define the over-the-air interface between wireless clients and a base station, or an access point that is physically connected to the wired network. IP Internet Protocol. The basic communications protocol of the Internet. See IP address, TCP/IP. IP address Internet Protocol address. IP Version 4, the most widely used Internet protocol, provides a 32-bit number that identifies the sender or receiver of information sent across the Internet. An IP address has two parts: The identifier of the particular network on the Internet and the identifier of the particular device (which can be a server or a workstation) within that network. The newer IP, Version 6, provides a 128-bit addressing scheme to support a much greater number of IP addresses. See DHCP, DNS, IP. IP subnet An IP subnet is a local network as defined by IP network numbers. Connecting to a subnet involves connecting to the appropriate hardware network and configuring IP for that network.68 Glossary LAN Local area network. A system of connecting PCs and other devices within the same physical proximity for sharing resources such as an Internet connections, printers, files, and drives. When Wi-Fi is used to connect the devices, the system is known as a wireless LAN or WLAN. See WAN. MAC address Media Access Control address. A unique hardware number that identifies each device on a network. A device can be a computer, printer, and so on. A MAC address is also known as an AirPort ID. Mbps Megabits per second. A measurement of data speed equivalent to a million bits per second. MIMO Multiple-input multiple-output. An advanced signal processing technology that uses multiple receivers and multiple transmitters in both the client and access point to achieve data throughput speeds of 100 Mbps. See 802.11n. NAT Network Address Translation. A network capability that enables multiple computers to dynamically share a single incoming IP address from a dial-up, cable, or DSL connection. NAT takes a single incoming public IP address and translates it to a new private IP address for each client on the network. See DHCP, IP address. network name A name used to identify a wireless network. See SSID. NIC Network interface card. A wireless or wired PC adapter card that allows the client computer to utilize network resources. Most office-wired NICs operate at 100 Mbps. Wireless NICs operate at data rates defined by 802.11 standards. packet A unit of information transmitted from one device to another on a network. A packet typically contains a header with addressing information, data, and a checksum mechanism to ensure data integrity. pass phrase A series of characters used to create a key that is used by Wi-Fi Protected Access (WPA). See PSK, WPA. print server A network device, often a computer, that connects to at least one printer, allowing it to be shared among computers on a network. PSK Pre-shared key. A mechanism in Wi-Fi Protected Access (WPA)-Personal that allows the use of manually entered keys or passwords to initiate WPA security. The PSK is entered on the access point or home wireless gateway and each PC that is on the Wi-Fi network. After entering the password, Wi-Fi Protected Access automatically takes over. It keeps out eavesdroppers and other unauthorized users by requiring all devices to have the matching password. The password also initiates the encryption process which, in WPA is Temporal Key Integrity Protocol (TKIP) and in WPA2 is Advanced Encryption Standard (AES). See TKIP, WPA-Personal, WPA2-Personal.Glossary 69 roaming (Wi-Fi) The ability to move from one area of Wi-Fi coverage to another with no loss in connectivity (hand-off). router A wireless router is a device that accepts connections from wireless devices to a network, includes a network firewall for security, and provides local network addresses. See hub. server A computer that provides resources or services to other computers and devices on a network. Types of servers include print servers, Internet servers, mail servers, and DHCP servers. A server can also be combined with a hub or router. See DHCP, hub, router. SSID Service set identifier. A unique 32-character network name, or identifier, that differentiates one wireless LAN from another. All access points and clients attempting to connect to a specific WLAN must use the same SSID. The SSID can be any alphanumeric entry up to a maximum of 32 characters. See network name. subnet An IP address range that is part of a larger address range. Subnets are used to subdivide a network address of a larger network into smaller networks. Subnets connect to other networks through a router. Each individual wireless LAN will typically use the same subnet for all of its clients. See IP address, router. TCP Transmission Control Protocol. The transport-level protocol used with the Internet Protocol (IP) to route data across the Internet. See IP, TCP/IP. TCP/IP The underlying technology of Internet communications. While IP handles the actual delivery of data, TCP tracks the data packets to efficiently route a message through the Internet. Every computer in a TCP/IP network has its own IP address that is either dynamically assigned at startup (see DHCP) or permanently assigned as a static address. All TCP/IP messages contain the address of the destination network, as well as the address of the destination station. This enables TCP/IP messages to be transmitted to multiple networks (subnets) within an organization or worldwide. For example, when a user downloads a webpage, TCP divides the page file on the web server into packets, numbers the packets, and forwards them individually to the user’s IP address. The packets may be routed along different paths before reaching the user’s address. At the destination, TCP reassembles the individual packets, waiting until they have all arrived to present them as a single file. See IP, IP address, packet, TCP. throughput Usually measured in bps, Kbps, Mbps or Gbps, throughput is the amount of data that can be sent from one location to another in a specific amount of time. See bps, Mbps. USB Universal Serial Bus. A high-speed bidirectional serial connection used to transfer data between a computer and peripherals such as digital cameras and memory cards. 70 Glossary WEP Wired equivalent privacy. The original security standard used in wireless networks to encrypt the wireless network traffic. See WPA, Wireless local area network. Wi-Fi A term developed by the Wi-Fi Alliance to describe wireless local area network (WLAN) products that are based on the Institute of Electrical and Electronics Engineers. Wi-Fi Certified The certification standard designating IEEE 802.11-based wireless local area network (WLAN) products that have passed interoperability testing requirements developed and governed by the Wi-Fi Alliance. wireless network Devices connected to a network using a centralized wireless access point. See WLAN. WLAN A data communications network that spans large local, regional, national, or international areas and is usually provided by a public carrier (such as a telephone company or service provider).The term is used to distinguish between phone-based data networks and Wi-Fi networks. Phone networks are considered wide area networks (WANs) and Wi-Fi networks are considered wireless local area networks (WLANs). See LAN. WPA - Enterprise Wi-Fi Protected Access-Enterprise. A wireless security method that provides strong data protection for multiple users and large managed networks. It uses the 802.1X authentication framework with TKIP encryption and prevents unauthorized network access by verifying network users through an authentication server. See 802.1X. WPA - Personal Wi-Fi Protected Access-Personal. A wireless security method that provides strong data protection and prevents unauthorized network access for small networks. It uses TKIP encryption and protects against unauthorized network access. WPA2 Wi-Fi Protected Access 2. The follow-on security method to WPA for wireless networks that provides stronger data protection and network access control. It provides enterprise and consumer Wi-Fi users with a high level of assurance that only authorized users can access their wireless networks. Based on the ratified IEEE 802.11i standard, WPA2 provides government grade security by implementing the National Institute of Standards and Technology (NIST) FIPS 140-2 compliant AES encryption algorithm and 802.1X-based authentication. There are two versions of WPA2: WPA2- Personal and WPA2-Enterprise. WPA2-Personal protects unauthorized network access by utilizing a set-up password. WPA2-Enterprise verifies network users through a server. WPA2 is backward compatible with WPA. Like WPA, WPA2 uses the 802.1X/EAP framework as part of the infrastructure that ensures centralized mutual authentication and dynamic key management and offers a pre-shared key for use in home and small office environments. Like WPA, WPA2 is designed to secure all versions of 802.11 devices, including 802.11b, 802.11a, and 802.11g, multiband and multimode. See WPA2- Enterprise, WPA2-Personal.Glossary 71 WPA2 - Enterprise Wi-Fi Protected Access 2 - Enterprise. The follow-on wireless security method to WPA that provides stronger data protection for multiple users and large managed networks. It prevents unauthorized network access by verifying network users through an authentication server. See WPA2. WPA2 - Personal Wi-Fi Protected Access 2 - Personal. The follow-on wireless security method to WPA that provides stronger data protection and prevents unauthorized network access for small networks. See WPA2, PSK.www.apple.com/airportextreme www.apple.com/airport © 2009 Apple Inc. All rights reserved. Apple, the Apple logo, AirPort, AirPort Extreme, AppleShare, AppleTalk, Back to My Mac, Bonjour, Mac, and Mac OS are trademarks of Apple Inc., registered in the U.S. and other countries. AirPort Express, AirTunes, Time Capsule, and Time Machine are trademarks of Apple Inc. Other product and company names mentioned herein may be trademarks of their respective companies. 019-1257 Time Capsule3  5 1 7 Time Capsule 8  AirPort  9  11 Time Capsule 13 2 Time Capsule 14 Time Capsule  17  AirPort  19  19  ! Internet " 21 #$%& 22 '()*+,-./0"12 23 3Time Capsule 4 Time Machine 25 3 25 5627"1 Internet 25 56289-.:Time Capsule -. 26 56Time Capsule ;<=> 27 56Time Capsule  ?@ABC4 28 56DEF;<=> 29 G AirPort  29 HITime Capsule JKLM 30 NO AirPort PQR& 31 4 33 Time Capsule 36 Regulatory Compliance Information1 5 1  Time Capsule Time Capsule Time Capsule 0S2TUL#V Wi-Fi WXYZ[\❡ Mac OS X v10.5.2 Leopard :^4_`a Time Machine >❝0^TcLd4 eZ[ 4e 23 ? ➋A Time Capsule 5 Time Machine➌❡  Ÿ-. ¡¢£"1 Internet❝Sžfg Wi-Fi Z ⑧5 iPhone❞iPod touch  Apple TV⑨kl ! Internet "❡2¤0^3"1h fg¥¦ !§¨❡  <-. ¡:;<-. ¡©ª❝«¬d­< Internet "®¯ z{°±K ⑧ˆ5fg❞iPhone❞iPod touch  Apple TV⑨❡  d Time Capsule "1h2›œ❡pZtu Macintosh❞ Windows XP : Windows Vista fg™š1❝/u"1s‚❡  d²³ USB DEF"1h2 Time Capsule❡AirPort 4e<“”fg ⑧<:⑨´u"1hµDEF#V¶D❡  d·1 USB ¸¹"1h2 Time Capsule 4❡AirPort 4e<“”fg ⑧<:⑨´uº»¸¹¼½¾❡ 1  7  d USB ¿À"1h Time Capsule 4❝ÁÂÃ"1Ă USB Z ⑧5DEF: ¸¹⑨❡4e / ➝§¨I¼❤56n Windows XP : Windows Vista fg❝FnB [ J ] > [ e< ] > AirPort ¼❡ -./01( Time Capsule ÷ðZKL❝'()*"1❡ý: ;< 22 ì➋'()*+,-./0"12 ➌❡ /2 13 2  Time Capsule Time Capsule Internet AirPort `Mdz{ê¶N\OP✐dTime Capsule "1 Internet❝^ ➜AirPort ➝¼QR2 Time Capsule žtu❡5G Ä“½Q❝^ ➜AirPort ➝#$tu“½Q❝ý:; www.apple.com/tw/support/airport S4 ➜ AirPort T AirPort  ⑧Mac OS X v10.5 + Windows⑨➝❡ 32ç±q Time Capsule ãä¥å¹4 ➜AirPort ➝¥Â❝2K0^  ➜AirPort ➝¼QRUVVoWpK\ X❡íî#$%&❝ý3 ➜AirPort ➝ ➜wLx➝%ia%D ➜þY➝❡ý:;< 21 ì ➋#$%&➌❡14  2  Time Capsule Time Capsule ~2 Time Capsule z{ Internet "l❝ê¶fgZdu"1  AirPort  !§¨❞YZ[❝^ Internet > ⑧ˆ5\ ]Àf^_`>⑨✐  pZ ➜AirPort ø➝ ➜AirPort Extreme ø➝ Macintosh fg  pZ 802.11a❞802.11b❞802.11g  IEEE 802.11n draft ñòtufg  ž Wi-Fi Z ›œ"1 Time Capsule fgm0º» !§¨^"1 Internet❡ í2ç±q Mac OS X v10.5.2 :^4_`❝2K0^Time Machine d4 e / ➝§¨ I¼❤^Windows fg [ J ] > [ e< ] > AirPort ¼⑨❝%D2 Time Capsule❝ÁÂ×jê ➜e*➝❡ 4 èéfg4 +h❡ 5 Mac OS X v10.5 6789:;<✐ 1 ý%D ➜i6➝ > ➜j♠➝❝ÁÂ×jê ➜¶DÊl➝❡ 2 ×jê ➜Ž,➝⑧+⑨❝ÁÂ3¶E¼%D2DEF❡ 3 ×jê ➜Ž,➝×Ø❡ 56¶Ea;<á DEF❝ý¶4×ØmnDEF❡ 5 Mac OS X v10.3 ,10.4 6789:;<✐ 1 c ➜DEF➝⑧B ➜> / ➝§¨Io⑨❡ 2 %D¶EaDEF❡ 56¶Ea;<á DEF❝ý×jê ➜Ž,➝£A%ia%D Bonjour❝ Á¶Ea%DDEF❡ =>Windows XP , Vista 679:;<✐ 1 ý Time Capsule ãäå¹4ç± Windows _` Bonjour❡ 2 ýèéfg4 +h"1h2DEF❡  AirPort fg:ž“”ø:p1øfg❝d0™š Time Capsule "1 Internet❡"1h Time Capsule ›œËfgm0º»" 1 Internet❡ 2  Time Capsule 17 ™š Time Capsule❝fg"1h›œËfgmu“q#VPQ❡ AirPort íî£pK2 Time Capsule❝ý ➜AirPort ➝¼QR ❡➜AirPort ➝€32ç± Time Capsule å¹4lj"ç±❡ 5 Mac OS X v10.4 ,8?@ Macintosh 678✐ 1 c ➜AirPort ➝⑧B ➜> / ➝§¨Io⑨❡ 2 %D2 Time Capsule ÁÂ×jê [ e*]❡ 56; [ e< ] > AirPort⑨❡ 2 %D2 Time Capsule ÁÂ×jê [ e*]❡18  2  Time Capsule 3 ýèéfg4 +h Time Capsule 2❡ ➜AirPort ➝¼QR€vÝ2jƓÝÞ❝wxî y‹2îz{❝£€|R2+,ö❡ 562î Time Capsule "1 Internet❝2óô} Internet z{{>~ ⑧ISP⑨ý—} ⑧DSL :ÎÏÐF⑨€ ❝:n™šÑ<›œ"1 Internet❡í2 ISP 1h‚½Q ⑧5ƒ IP B„: DHCP )* ID⑨❝0 uî3 ➜AirPort ➝a+,ÅƽQ❡32 Time Capsule l❝ý9 êÅƽQ^Zd❡ 2  Time Capsule 19 20^ ➜AirPort ➝¼QR❡Q Rd…†2UVóô‡ˆ'‰Š❞-. ¡❝ž&â ❡ í2î34 ! USB DEF: USB ¸¹✐ 1 dDEF:¸¹"1h Time Capsule  USB Ë ⑧d⑨❡ 2 c ➜AirPort ➝⑧B Macintosh fg4 ➜> / ➝§ ¨I¼❤:Windows XP fg [ J ] > [ e< ] > AirPort ¼⑨❡ 3 %D2 Time Capsule ÁÂ×jê [ e*]❡ 56; / ➝§¨ I¼❤56nWindows XP fg❝FnB [ J ] > [ e< ] > AirPort ¼⑨❡ 2 %D2 Time Capsule ÁÂ×jê [ e*]❡ í2%3G÷ Time Capsule❝20uî"1÷❝Á ÂÃG Time Capsule ❡ íî3 Macintosh fg4%D2îG❝ý%i¶a AirPort %i❡3Windows XP fg4❝dŽ ï3"‘ 4❝ $h2r’Š“ (SSID) '(❝í”iaÑĂ❝ý%D2❡ 3 ýèéfg4 +h ! Time Capsule  Internet "❡ ➜AirPort ➝z{Tc Time Capsule à7❡562î ž%&❝5¯•"❝:n#$ DHCP %&❝ý ➜AirPort ➝ ➜wLx➝%ia%D ➜þY➝❡ 2  Time Capsule 21 í2î#$ Time Capsule %& ⑧5#$çW%&❞–—❞DHCP ˜ ™l¦❞"®¯•❞fûü❞3€ ^ž⑨❝ý ➜AirPort ➝þY Time Capsule❡ 9F"G✐ 1 c ➜AirPort ➝⑧B Macintosh fg4 ➜> / ➝§ ¨I¼❤^Windows XP fg [ J ] > [ e< ] > AirPort ¼⑨❡ 2 í¶EaÑĂZ❝ý%D2îZ❡56;❝20^Z[fg4e<& â❝w¬2é­❞®¯❞°­±`❡32dTime Machine r#Â❝€ ªXYZ[2fg❡ 562n Mac OS X v10.5.2 :^4_`❝~2²H"1 Time Capsule l❝Time Machine €vÝ2n³îZ[2§¨❡ý×jê ➜\'Z[´¹➝❝ ÁÂTime Machine €XYr#µêY\❡  Mac OS X Leopard ➜j➝ Time Machine ÈCXYZ[❞ ¶j‚Z[´¹❝:nsž❡ 5 Mac OS X Leopard 678,VWTime Machine✐ 1 ý%D ➜i6➝ > ➜j♠➝❝ÁÂ×jêTime Machine❡ 2 dh ➜➝❡ 3 ×jê ➜G´¹➝❡ 4 %D2 Time Capsule £×jê ➜Z[➝❡24  2  Time Capsule ·Z[½¾I¸❝2 ➜Mac QR+h➝❝ÁÂ3mnÆBa+, Time Machine❡3 25 3 XYZ[\]^ Time Capsule Internet  ý£G$12fg"1 Internet❡5627"1❝ý&2n%& ❡56%&❝Ǥn7"1❝ýÈÉ2 Internet  z{{>~ ⑧ISP⑨❡  ý&2"1n%&❡ Time Capsule 20^ÖK Time Capsule ”Ÿ AirPort -.: Time Capsule -.❡ _` Time Capsule PQ✐ 1 ÊËÌ ⑧ˆ58^Í⑨×ÎÖK×Øj ❡ 7k lmnolpqrst❝u+,Y vwx❡26  3  2 %D2 AirPort ❡  5 Macintosh 678❝%i¶a AirPort %i%D Time Capsule  ⑧Š“€Ï⑨❡  5Windows XP ab678❝dŽ ï3"‘ 4❝$h2 r’ [AirPort Š“ ] (SSID) '(❝í”iaÑĂ❝ý%D2 AirPort ❡ 3 c ➜AirPort ➝⑧B Macintosh fg4 ➜> / ➝§ ¨I¼❤^Windows XP fg [ J ] > [ e< ] > AirPort ¼⑨❡ 4 %D2 Time Capsule❝£ ➜wLx➝%ia%D ➜þY➝❡ 5 ׶a AirPort jê❝ÁÂ×jê ➜wLx➝❡ 6 +, Time Capsule -.❡ 7 ×jê ➜➝£ ➜çWЛ➝A%ia%DŽ-àŽ- tu❝£–'2 AirPort Y-. ¡❡íqŽ-tu❝ý+, AirPort -.❡ 8 × ➜G➝jêÖY Time Capsule❝£–Ñ,❡ Time Capsule GÒd AirPort Extreme fÓÂ❝ÃÖd=❡ í Time Capsule rW(=>❝20uîdwLxÖK'ÔÕÖ❡ / Time Capsule noyz{|Y}~v€‚Vƒ„Y ❝… v/ Time Capsule noyz{|Y}❡ 3  27 c Time Capsule defghi✐ m ÊËÌ⑧ˆ58^Í⑨×ÎÖK×Ø❝$h „?@'(⑧™ 5 ⑨❡ Time Capsule d€^ê¶ÖK✐  Time Capsule € DHCP 1 IP B„❡  Š“d€ÖK# ➜Apple Network XXXXXX➝⑧a XXXXXX €^ AirPort ID a Â×.».⑨❡  Time Capsule -.€ÖK# public❡ k Time Capsule lmnopq❝rst;uv✐ 1 ÓØ Time Capsule f❡ 2 ~2, Time Capsule l❝ýÊËÌ×ÎÖK×Ø❡ Time Capsule 0un›œ;<1❝Time Capsule ¡ AirPort PQÙÚ❝:n Internet z{{>~ ⑧ISP⑨ÛÕ45qÝÞ❡562n DSL :ÎÏÐ F"1 Internet❝m0unÏÐF: Internet ¥¦"÷6aÜ❡œ ÏÐFr"?\%@❝mý£GaÜÏÐFf❝¤ÝÞ ¥ÂÃÖ" 1❡3Ö14ÏÐFf¥ß❝ý& Time Capsule n™š›œ$1 "1hÏÐF4❡28  3  5GÄ ?@89“½Q❝ýc ➜AirPort ➝❝%D2 Time Capsule❝Á ➜wLx➝%ia%D ➜þY➝❡×jê ➜wLx ➝á ?@“½Q❡ 2m0^3 AirPort j¼%D ➜·wLxn³<ÝÞ➝❡56wLx4 5ÝÞ❝➜AirPort ➝€❝£|R2ÙÚÝÞ❡ í2÷dDEF"1h Time Capsule 4 USB Ë❝Çn AirPort 4fg7 #V¶D❝ýUV궇ˆ✐ 1 &÷14£÷DEF❡ 2 &1÷ßß14DEF Time Capsule 4 USB Ë❡ 3 &÷3)*fg4 ➜DEF¶E➝·à¼%DDEF❡ 5 Mac OS X v10.5 ,8?@ Macintosh 678✐  ý%D ➜i6➝ > ➜j♠➝❝ÁÂ×jê ➜¶DÊl➝❡  ×jê ➜Ž,➝⑧+⑨£%D¶EaDEF❝ÁÂ×jê ➜Ž,➝⑧+⑨❡ 5 Mac OS X v10.2.7 ,8?@ Macintosh 678✐  c ➜DEF➝⑧B ➜> / ➝§¨Io⑨❡  íDEF3¶E¥o❝ý× ➜Ž,➝jê❡  A%ia%D Bonjour❝%DDEF❝ÁÂ×jê ➜Ž,➝⑧+⑨❡ 3  29 5Windows XP 678✐   [ J ] tuEac [ ¶DÊl ]❡  %DDEF❡í”ia2ÑDEF❝× [ áDEF ] jê❝ÁÂèéfg4 +h #V❡ 4 —DEF❝¤ÝÞ ¥ÂÃÖYDEF❡ AirPort Apple €ªz{G AirPort ❡â2G Time Capsule  ❡ 20^3 AirPort j¼%D ➜~c AirPort lãäG&â➝: ➜ãäG&â➝❡562å% ➜ãäG&â➝❝ý3A%i¼%Dj‚ æªl¦ ⑧ˆ5¼æ⑨❝«¬XYãäG&â❡ Time Capsule ê¶âR&0|R2 Time Capsule çhPQÙڐ‘è éêÙÚ❡  d2 Time Capsule KëìÌ ⑧5í:îï⑨‰ðJñe❡òIî SóôõöEÈ❡  í2d Time Capsule KíÂà❝ýS Time Capsule íÕ÷¥¦ )ú ð 2.5 øW ⑧1 ùú⑨ûü❡  ýþd2 Time Capsule JK3<ÒÈ^4õöÈñe❡30  3   í2d Time Capsule K¬®Z¯a❝>ýþ Time Capsule  Ò®❞·Q:f❡d21¿aJK Time Capsule j ❡ 0uS Time Capsule 1¥¦ÕV ¦❡  ± Time Capsule BK❝>ûü ❞2.4 : 5 gigahertz ⑧GHz⑨f ^žNOð 7.6 ø ⑧25 ù⑨❡  ýdžÌ` ⑧❞❞ ̤⑨J3Time Capsule 4È❡Ž€N OTime Capsule ❡ AirPort ûüNO❝uð#ÝÞ0u•❡ ê¶&â0u€NO AirPort PQ✐   $z{ ⑧DSS⑨f}  !Æy‹¹‹¨eãäk"fÎ❡ýZ#~ÈÉ^»b‹ fÎ❡  !Æf$%❝ˆ5f❞f&è'()^4fÔ¤   2.4 : 5 GHz }*f❡562f: AirPort PQ45ÝÞ❝ý GwLx: Time Capsule e})❝:Gfe})❡  “ôwLx“+})❡ˆ5❝56wLx A '}) 1❝wLx B K>'}) 6 :}) 11❡4 31 4 wxyz❞|}~€ Time Capsule 5 Time Capsule “½Q❝ýß, www.apple.com/tw/airport S❡ íî-. Time Capsule⑧56~²23ç± Time Capsule å¹4l£2- .⑨❝ýß, www.apple.com/tw/register S❡ 5 AirPort ²³½Q❞‚/0½Q3/’12Ó❝^ Apple  êÑ❝ýß, www.apple.com/tw/support/airport S❡ 534^·²³z{❝ýß, www.apple.com/tw/support S❝£%D2 4¢:LÓ❡32  4  íî7ÙGÄ3 Time Capsule 4 ➜AirPort ➝“½Q❝ýc ➜AirPort ➝£%D ➜QR+h➝ > ➜AirPort QR+h➝❡ í2 Time Capsule Û567:n7%@?\❝ýèé`þ.a+h ❞ fgQR+h4½ü❡ í Time Capsule 8Á7,9?\❝ýß, www.apple.com/tw/support S^7 Ù5»b ƒz{½Q❡ Time Capsule 2 Time Capsule :oD<- ❡33 Time Capsule ‚ƒ„~C… †‡ Time Capsule  ˆ‰Š‹✐2.4  5 GHz  LŒMf3‹✐ƒ 23 dBm ⑧;⑨  Ž✐802.11 DSSS 1  2 Mbps ïð❝802.11a❞802.11b❞802.11g ñò draft 802.11n ñò  1 RJ-45 10/100/1000Base-T Gigabit ›œ WAN ⑧<⑨  3 RJ-45 10/100/1000Base-T Gigabit ›œ LAN ⑧G⑨  P-¶<=> ⑧USB d⑨ 2.0  802.11 a/b/g/n AirPort Extreme   v‘✐0° C ú 35° C ⑧32° F ú 95° F⑨  ’“‘✐–25° C ú 60° C ⑧–13° F ú 140° F⑨  ”•–‘ ⑧v—⑨✐20% ú 80%  ”•–‘ ⑧’“—⑨✐10% ú 90%❝?@A 34 ˜ Time Capsule  ™‘✐197.0 øB ⑧7.75 ùú⑨  š‘✐197.0 øB ⑧7.75 ùú⑨  ›‘✐36.33 øB ⑧1.43 ùú⑨  _œ✐1.6 øC ⑧3.5 ùD⑨ MAC Time Capsule :oD<҂¸B„✐  AirPort ID✐Ł‚B„nEF4 Time Capsule❡  žNO ID✐íîd Time Capsule "1 Internet❝20uîz{µB„½Q° 2 ISP❡ Time Capsule  d Time Capsule frW—Gjà7naÜf❡  ~"1:ÓØ Time Capsule l❝ý{óHÎI❡îSþ óôI õöo[❡  2n89❝œn Time Capsule ;<14f❝´0^dJÙ❡í 2 Time Capsule îz{❝ý:;< 31 ì ➋GÄ+h❞z{²³➌❡  ý Vd1I,Ê+Ëa❡í27^öü%$d1I,Ê+Ëa❝ ÛK«ñò0u£“õ❡ý&21IÊ+ËL¬“õ❝–2nd 1I, >Ê+Ëa❡˜ Time Capsule 35  ~2 Time Capsule l❝·MN Oƒn%@ÑP❡Time Capsule ·M <t❝uʆooQ`N❝4ú·o‰R &a❡  S Time Capsule üS❝5T¾❞UV❞WX❞YW¦¤ñe❡  ý ¡ Time Capsule❝ýþŸhZå$[❝£–ýþ9\]:ž9^¸Ÿ _❡  ý îS`Ì:Sab32 Time Capsule 4❡í454PcË❝ ýӟfÔüabS❡  ýî3d· Time Capsule❡Time Capsule nTdo/0❡ 3KJ:¿elíü~❝0u€ Time Capsule #6f❡~23?Œš a❝ý îgh Time Capsule❡ !†‡ˆ0‰Š‹ŒŽ❝(A‘’“”•–ƒ  Time Capsule❡ (—˜™š  Time Capsule ›œ/žŸ❡7a/Œˆ0 ¡… ¢„£¤¥¦§x¨❡AirPort Express ©ª…^«h¬­®¯°❡36 Regulatory Compliance Information Wireless Radio Use This device is restricted to indoor use due to its operation in the 5.15 to 5.25 GHz frequency range to reduce the potential for harmful interference to cochannel Mobile Satellite systems. Cet appareil doit être utilisé à l’intérieur. Exposure to Radio Frequency Energy The radiated output power of this device is well below the FCC and EU radio frequency exposure limits. However, this device should be operated with a minimum distance of at least 20 cm between its antennas and a person’s body and the antennas used with this transmitter must not be colocated or operated in conjunction with any other antenna or transmitter subject to the conditions of the FCC Grant. FCC Declaration of Conformity This device complies with part 15 of the FCC rules. Operation is subject to the following two conditions: (1) This device may not cause harmful interference, and (2) this device must accept any interference received, including interference that may cause undesired operation. See instructions if interference to radio or television reception is suspected. Radio and Television Interference This computer equipment generates, uses, and can radiate radio-frequency energy. If it is not installed and used properly—that is, in strict accordance with Apple’s instructions—it may cause interference with radio and television reception. This equipment has been tested and found to comply with the limits for a Class B digital device in accordance with the specifications in Part 15 of FCC rules. These specifications are designed to provide reasonable protection against such interference in a residential installation. However, there is no guarantee that interference will not occur in a particular installation. You can determine whether your computer system is causing interference by turning it off. If the interference stops, it was probably caused by the computer or one of the peripheral devices. If your computer system does cause interference to radio or television reception, try to correct the interference by using one or more of the following measures:  Turn the television or radio antenna until the interference stops.  Move the computer to one side or the other of the television or radio.  Move the computer farther away from the television or radio.  Plug the computer into an outlet that is on a different circuit from the television or radio. (That is, make certain the computer and the television or radio are on circuits controlled by different circuit breakers or fuses.) If necessary, consult an Apple Authorized Service Provider or Apple. See the service and support information that came with your Apple product. Or, consult an experienced radio/television technician for additional suggestions. Important: Changes or modifications to this product not authorized by Apple Inc. could void the EMC compliance and negate your authority to operate the product.37 This product was tested for FCC compliance under conditions that included the use of Apple peripheral devices and Apple shielded cables and connectors between system components. It is important that you use Apple peripheral devices and shielded cables and connectors between system components to reduce the possibility of causing interference to radios, television sets, and other electronic devices. You can obtain Apple peripheral devices and the proper shielded cables and connectors through an Apple-authorized dealer. For non-Apple peripheral devices, contact the manufacturer or dealer for assistance. Responsible party (contact for FCC matters only) Apple Inc., Corporate Compliance, 1 Infinite Loop M/S 26-A, Cupertino, CA 95014-2084 Industry Canada Statement This Class B device meets all requirements of the Canadian interference-causing equipment regulations. Cet appareil numérique de la Class B respecte toutes les exigences du Règlement sur le matériel brouilleur du Canada. VCCI Class B Statement Europe—EU Declaration of Conformity For more information, see www.apple.com/euro/ compliance. European Union — Disposal Information This symbol means that according to local laws and regulations your product should be disposed of separately from household waste. When this product reaches its end of life, take it to a collection point designated by local authorities. Some collection points accept products for free. The separate collection and recycling of your product at the time of disposal will help conserve natural resources and ensure that it is recycled in a manner that protects human health and the environment. Disposal and Recycling Information This product has an internal battery. Please dispose of it according to your local environmental laws and guidelines. For information about Apple’s recycling program, go to www.apple.com/environment. California: The coin cell battery in your product contains perchlorates. Special handling and disposal may apply. Refer to www.dtsc.ca.gov/hazardouswaste/ perchlorate. Deutschland: Dieses Gerät enthält Batterien. Bitte nicht in den Hausmüll werfen. Entsorgen Sie dieses Gerätes am Ende seines Lebenszyklus entsprechend der maßgeblichen gesetzlichen Regelungen. Nederlands: Gebruikte batterijen kunnen worden ingeleverd bij de chemokar of in een speciale batterijcontainer voor klein chemisch afval (kca) worden gedeponeerd.38 Ÿ ✐ Singapore Wireless Certification Taiwan Warning Statements Korea Warning Statements © 2009 Apple Inc.  j®9❡ Apple❞i6❞Apple ïi❞AirPort❞AirPort Express❞ AirPort Extreme❞Apple TV❞Bonjour❞iPod❞ Leopard❞Macintosh❞Mac OS Time Capsule n Apple Inc. 334ž4¢LÓ-.~ï❡ Finder❞iPhone  Time Machine n Apple Inc. ~ï❡ ¬zžøj/0Š“0u'eöøj ~ï❡www.apple.com/airport www.apple.com/support/airport TA019-1384-A Time Capsule3  5 1 7  Time Capsule 8  AirPort  9  11 Time Capsule  13 2 Time Capsule 14  Time Capsule  17  AirPort  19  19  !"# Internet $% 21 &'()*+ 22 ,-./0123456$%7 23 8 Time Capsule  Time Machine 25 3 25 9:;<= Internet 25 >?34@ Time Capsule 34 26 Time Capsule ABCD 27 Time Capsule  EFGHIJK4 28 LMNABCD 29 O AirPort  29 P Time Capsule QRS+ 30 TU AirPort VWXY&Z 31 4 33 Time Capsule 36 Regulatory Compliance Information1 5 1  Time Capsule  Time Capsule  Wi-Fi [\]Z^_`ab❞d Mac OS X v10.5.2 Leopard @O(efg Time Machine DhijklmnopBqrs\]Z^ t Time Capsule o❞ Time Capsule uvw[x: AirPort Extreme yzj{|}~€‚❞ & ƒ Time Capsule „j…T†(‡ Wi-Fi ˆ   2.4 ‰Š‹ (GHz) j 802.11b❝ 802.11g ! 802.11n &Zj iPhone❝ iPod touch !Žqr   5 GHz j 802.11n ! 802.11a &Zjqr! Apple TV &ZT:‘’{|“”•:–—˜•j™š Time Capsule T› oqr!&Z"#œ Internet ;<❞6  1 Bž Time Capsulej76Ÿˆ  d Mac OS X v10.5.2 @O(ef¡g Time Machine DhiZ^ opBqrŸ–Ÿ¢;? Time Capsule  Time Machine@❞  £34¤¥¦j§„;? Mac OS X Leopard D Time Machine  Time Capsule  Mac OS X v10.5.2 aST❞  Macintosh  Time Capsule  wäåB AirPort @ AirPort Extreme ù Macintosh qrjŸ°& …µ¶ ;<ú@wŸ¢q´;❞7â ã? @Ab dâAirPort ãâAirPort & ãây zãÈBg¡g*4âC]üJKãjD TF I JKj+C]'=❞ &()*10*-. 6:Edí]%2❞ Time Capsule EFí]¨GHIJ❞12  1 E Time Capsule q„j âAirPort ã& …jŸ› Internet ;<❝USB LMN❝ USB ¼½@ÒB8❞d¶ Mac OS X q rojâAirPort ãËâDhiã¬Kâã¬Kgú™ d¶ Windows XP @ Windows Vista qrojDË âLã> âpBhiã> âAirPortãg❞ &'2* Time Capsule ìïZƒ,-./0$%❞9: ; 22 é â,-./0123456$%7 ã❞ /2 13 2  Time Capsule Time Capsule Internet AirPort fM{|žBE Time Capsule ;âp Bhiã > âAirPortãg¡j*]7 Time Capsulej§„^Ù â_`ã❞ 4 Ùæab ❞ 4 Mac OS X v10.5 56789:; 1 *4cb > âdefƒ& ãj§„^Ù âLM›ghã❞ 2 ^ÙiÙÚ (+) ¨÷+g*]7LMN❞ 3 ^ÙiÙÚ❞ 7LMN9d÷+gjgÙÚjk…❞ 4 Mac OS X v10.3 < 10.4 56789:; 1 LâLMN& ã ËâDhiã¬Kâã¬Kg¡❞ 2 ÷+g*]LMN❞ LMN9d÷+gj^ÙiÙÚ¨?@Abg*4âBonjourãj§„ ÷+g*]LMN❞ =>?9 Windows XP < Windows Vista 567:;@ 1  Time Capsule » CD äå Bonjour  Windows e¡❞ 2 Ùæab ; âpBhiã > âAirPortã❞ 2 *]7 Time Capsulej§„^Ù â_`ã❞18  2 Time Capsule 3 Ùæab & Time Capsule !❞ âAirPort ã& NþEs%7Bátu!á0vU% 2j¨wN728& ❞ 7á Time Capsule ;<= InternetjD1á Internet vUx (ISP) {|œ  DSL ÎÏÐο@´ÎÏÐο¡y/j@ÑÒBŸ¢ < Internet ;<❞7 ISP 3`žz'Á { IP m|@ DHCP . / ID¡j76:1ád âAirPort ãg2}ÁÂ❞à& 7 Time Capsule ü34ºÁÂ❞ 2 Time Capsule 19 76Ÿ âAirPort ã& Nþ❞º& NþT~ 57%W€❝34¤¥–&'’©*+pô1~❞ 7Ld7o"# USB LMN@ USB ¼½ˆ 1 ELMN@¼½;<= Time Capsule  USB 0Ê (d) o❞ 2 LâAirPort ã Macintosh qrˆËâDhiã¬Kâ ã¬Kgú¶ Windows XP qrˆËâLã>âpBhiã>âAirPortã g¡❞ 3 *]7 Time Capsulej§„^Ù â_`ã❞ o9tpá  Time Capsulej^ÙâFqrãŸqr6&Zj §„÷+g*]7 Time Capsule❞ 4 Ùæab ❞ Internet 7L›oB‚x:@;<=Ÿ¢0Êqr"# Internet ; âpBhiã > âAirPortãg¡❞ 2 *]7 Time Capsulej§„^Ù â_`ã❞ áUìƒ& ƒ Time Capsule µ¶O„j76:ô;âpBhiã>âAirPortã g¡❞ 2 ÷+gBÄ&Zj*]7pá &Z❞o9tpá  Time Capsulej^Ù âFqrãŸqr6&Zj§„÷+g*]7  Time Capsule❞ 7áUìƒ& ƒ Time Capsule µ¶O„j76:ô;<=… j…:U Time Capsule µ¶O„❞ á*47páO„jd Macintosh qrobg AirPort b❞däåž Windows XP qrojE †Pd;<‡îoj&t7 ot€ˆ (SSID)j§„÷+g*4  BÄ6¡❞ 3  âyzãbg*4 â]& ã❞{7234jD234❞ B âAirPort ãg]& x:OÄÁÂj9:www.apple.com.cn/ support/airport oâDesigning AirPort Networks Using AirPort Utility (Mac OS X v10.5 + Windows)ã  Airport &Q AirPort  (MacOS X v10.5 + Windows)¡❞22  2 Time Capsule 7 WPA Personal @ WPA/WPA2 Personal µ¶34¤¥jD76Ÿ‘ ./0{|U7$%x:j™91©*234❞ à7,-./0$%7üjº./0€ˆ! MAC m|  @ AirPort ID¡T/E”d âAirPort ã$%Ï÷+gj&t7÷+g •–º./0❞7û6Ÿ{| 24 —ü$%j®ü«³„j./0E9:G$% 7❞ à7,-./0$%7üjº./01234❞ NOPQRSTUVWXYZ[\!5UV 1 LâAirPort ãj*]7 Time Capsulej§„âyzãb*4â ]& ã❞ôáü234❞ 2  âyzãbg*4 âi./0ã❞ 3 *]º./0$%‰Aˆ  *] PIN Ÿ2./0ø$%ü{|˜ËT™❞  *] âšHIJãŸ,-;IJ./0$%❞ à Time Capsule d“›./0üj LED TFœI#$❞ 2 Time Capsule 23 p‘7{|žü«$%j*] âE./0$%‹Ï‘ 24 — üã❞9*]}*+j./0E6Ÿ&$%j&t7÷+g•–º./0❞ Time Capsule Time Machine d Mac OS X Leopard g Time Machine Dhij76ŸZ^qroŸ ˜j ¡7æ¢❝£¤❝¥¢!¬¦❞ & ƒ Time Machine ª„j…T'§\]Z^7qr❞ 7v Mac OS X v10.5.2 @O(efjD;H;Z^©½ãj§ „ Time Machine Tª¶«ç¬>❞  Mac OS X Leopard g âdefƒ& ã âTime MachineãÈB& \ ]Z^❝O„=9}Z^©½@α’©& ❞ A?9 Mac OS X Leopard 567I<]^ Time Machine 1 *4cb > âdefƒ& ãj§„^Ù âTime Machineã❞ 2 E­]= âã❞ 3 ^Ù âO„©½ã❞ 4 *47 Time Capsule ¨^Ù âZ^ã❞24  2 Time Capsule šH Time Capsule ! Time Machine Z^6:1á±®@O¯ü«j4° 7Z^T±IJ❞ᐳLZ^‡jŸ¢E Time Capsule ; âMac wNãj§„djkÄ âTime Machineã❞3 25 3 _`abcde Time Capsule Internet  IJ&<7qr;<= Internet❞79:;âpBhiã>âAirPortã g¡❞ 4 *]7 Time Capsulej§„ âyzãbg*4 â]& ã❞ 5 dg^Ù âAirPortãj§„^Ù âyzã❞ 6 ‘7 Time Capsule 234❞ 7 ^Ùâã¨âä[•ã?@Abg*4ý3‰ŠjŸ°‘ AirPort í3¨ÓC34¤¥❞7Lž3x:j‘7 AirPort 2 34❞ 8 ^Ù âOãŸFí] Time Capsule ¨Ô& ❞ Time Capsule IJÕç„GE…q❞  Time Capsule %[ÂÃCDjD76:1áE’ØËt@Ö& ❞ , Time Capsule ij0vwxyUVsz{|4}RUV~,Qi j0 Time Capsule €CUV❞ 3 27 h Time Capsule ifjkl m ËÌÍÎ  ÏÐÑ¡ÙÒØËÙÚj&t ‡JK  S× 5 ! "¡❞ Time Capsule EØ˨BŸç& ˆ  Time Capsule  DHCP <ؒ IP m|❞  €ˆEØˑ Apple Network XXXXXX ®Ù XXXXXX  AirPort ID “„Ú ËT™ÛÜ¡❞  Time Capsule 34Øˑ public❞ mn!5 Time Capsule opqrstuvwxy 1 E Time Capsule Þq❞ 2 E Time Capsule q}üjËÌÍÎÙÒØËÙÚ❞ Time Capsule Ÿ¢q´6:Ý'(;<❝ Time Capsule 6:9d AirPort ÞßàáŸ@Ñ 7 Internet vUx6:Ed%2❞7 DSL ÎÏÐο@´ÎÏÐο ;<= InternetjDºÎÏÐο6:ìâãž;<@ Internet ;<❞5°Î ÏÐοäå>'=jûIJÞ…qj“›è!"j§„‘ÎÏÐο Fˆ 1 ('LMNìƒq¨ìq❞ 2 ('q´ìƒëìm;<=LMN! Time Capsule  USB 0Êo❞ 3 (¤ìƒd./0qr âLMN÷+ãíÊg*]žºLMN❞ ABCD Mac OS X v10.5 âdefƒ& ãj§„^Ù âLM›ghã❞  ^ÙiÙÚ (+) ¨d÷+g*]7LMNj§„^ÙiÙÚ (+)❞ ABCD Mac OS X v10.2.7 ❞ 4 LMNj“›è!ýj§„Gí…❞ AirPort Apple '§O AirPort ❞î7O Time Capsule Ÿ“❞ 7û6Ÿd AirPort fƒ& g*] âL AirPort üÅÆOãj@*] âÅÆOã❞7*] âÅÆOãjD?@Abg*4ü«ï   â´ð㡟\]ÅÆO❞ Time Capsule ŸçîBN Time Capsule 3`“”²Áàá!Þßàá❞  E Time Capsule P dèåABÜñÍ Sò@óô¡õö÷Íg❞I JE’P døùúû+ÈË ❞  7E Time Capsule P dò„ÈjD Time Capsule !ò×ü«ýD= ²B 25.4 þ  1 ¡❞  E Time Capsule P dÓÈ@Óȟosvúû+È÷Íg❞30  3  ád ¤g gE Time Capsule !0 &ZPd$j£€q ´❝ €q´@q Time Capsule❞P Time Capsule üjq´áPd ❞ Time Capsule !q´ª«á¤¸6:Sõ«❞  IJE Time Capsule P dù❝ 2.4 @ 5 ‰Š‹ (GHz) q!’©X Y=² 7.6   25 ¡Ë ❞  E’©ÍΠf❝@—͓“¡P d Time Capsule ❞®6: T¥C Time Capsule ❞ AirPort ùXY øjVW%26:•ûR —❞ŸçS+TU AirPort ²Á!"XYˆ    &<#$vU (DSS) €’%&  'Ætu()#$žp»*§}+q´❞‚d&Z"!xŸ3`u q´❞  'Æq,&Zj(-q❝q,./0❝qz““  2.4 GHz @ 5 GHz q€’àáŸq❞7q@ AirPort ²ÁE d%2jO„7yz@ Time Capsule €0j@ÑO„7q €0❞  »1B21€0yz❞Սjyz A & ‘€0 1jDyz B Dº& ‘€0 6 @ 11❞4 31 4 DdEz{|❝~1€ Web Time Capsule B Time Capsule “ÁÂj$% www.apple.com.cn/airport❞ áQ3 Time Capsule 7däå Time Capsule CD oüAB®¯4¡j $% www.apple.com/register/cn/❞ B AirPort ·¸ÁÂ❝›z'!ÎmÁÂ!56À7Ÿ–“ Apple  çÔj$% www.apple.com.cn/support/airport❞ B89Ÿ¾·¸ÁÂj$% www.apple.com/supportj§„*47pd9 ò@m÷❞32  4 ážÐB Time Capsule » âAirPort ãOÄÁÂjL âAirPort ã¨*4 âwNã > âAirPort wNã❞  Time Capsule o$ì:;@9:'=>jÙæf3❝abwN!d <g¬>❞  Time Capsule È9:>j$% www.apple.com.cn/support ŸžÐB 3`¤=vUÁÂ❞ Time Capsule i÷ M Time Capsule >❞33 Time Capsule ‚ƒ1B„…† Time Capsule  ‡ˆ2.4 = 5 GHz  S‰TkŠ‹“(6? 23 dBm  îˆ@¡  Œ802.11 DSSS 1 ! 2 Mbps îï❝ 802.11a❝802.11b❝ 802.11g ðñjŸ–òó 802.11n ðñ  1 RJ-45 10/100/1000Base-T ‰ŠËŸ¢ÌÍ (<)  3 RJ-45 10/100/1000Base-T ‰ŠËŸ¢ÔÍ (G)  ²A¶B (USB d) 2.0  802.11 a/b/g/n AirPort Extreme   xyŽ0° C = 35° C  32° F = 95° F¡  ‘Ž–25° C = 60° C  –13° F = 140° F¡  ’“” •xy–—20% = 80% mUC  ’“” •‘–—10% = 90% mUC  DEF¡34 ˜ Time Capsule  ™197.0 þ  7.75 ¡  š197.0 þ  7.75 ¡  F36.33 þ  1.43 ¡  ›œ1.6 ‰G  3.5 H¡ (MAC) Time Capsule d¾I>JMBÓ¼m|ˆ  AirPort ID’g†m|KLo Time Capsule❞  U ID76:1áE}m|{|æ ISP Ÿ°E Time Capsule ; Time Capsule qN‰ŠvE’qoÕç❞  à;<@Þ Time Capsule üjUôOÒP†❞ áøùPúû Q❞  9¹8‘çè78js9DR Time Capsulej5à…ìÞqüû9:R ❞7 Time Capsule 1áS=j9:; 31 é âžÐOÄÁÂ❝vU! ·¸ã❞  9áEj E&ZŸt¾ÈZXõ,g❞   Time Capsule øù[ j\]❝^_¼❝`a❝b`c“❞  ¤¥ Time Capsule 9£dn&‘!ef@’©C,g❞  — 9áEhÍ@[ ijd Time Capsule o❞ìkÍÎjæ… Þqj§„GÉ^ijÍ❞  dc¾ Time Capsule❞ Time Capsule vcŸ!Î❞ E”@¬>9àj6:T:; Time Capsule❞d2 Time Capsule ³hgj— 9áE…–dmo❞ ‚*ƒ„…†‡&ˆ‰Šc‹ŒjV Time Capsule❞ \ Ž‘’ Time Capsule❞ s“”*ƒ~4•–— ˜™š›❞œž4Ÿ '€ ¡—¢L❞36 Regulatory Compliance Information Wireless Radio Use This device is restricted to indoor use due to its operation in the 5.15 to 5.25 GHz frequency range to reduce the potential for harmful interference to cochannel Mobile Satellite systems. Cet appareil doit être utilisé à l’intérieur. Exposure to Radio Frequency Energy The radiated output power of this device is well below the FCC and EU radio frequency exposure limits. However, this device should be operated with a minimum distance of at least 20 cm between its antennas and a person’s body and the antennas used with this transmitter must not be colocated or operated in conjunction with any other antenna or transmitter subject to the conditions of the FCC Grant. FCC Declaration of Conformity This device complies with part 15 of the FCC rules. Operation is subject to the following two conditions: (1) This device may not cause harmful interference, and (2) this device must accept any interference received, including interference that may cause undesired operation. See instructions if interference to radio or television reception is suspected. Radio and Television Interference This computer equipment generates, uses, and can radiate radio-frequency energy. If it is not installed and used properly—that is, in strict accordance with Apple’s instructions—it may cause interference with radio and television reception. This equipment has been tested and found to comply with the limits for a Class B digital device in accordance with the specifications in Part 15 of FCC rules. These specifications are designed to provide reasonable protection against such interference in a residential installation. However, there is no guarantee that interference will not occur in a particular installation. You can determine whether your computer system is causing interference by turning it off. If the interference stops, it was probably caused by the computer or one of the peripheral devices. If your computer system does cause interference to radio or television reception, try to correct the interference by using one or more of the following measures:  Turn the television or radio antenna until the interference stops.  Move the computer to one side or the other of the television or radio.  Move the computer farther away from the television or radio.  Plug the computer into an outlet that is on a different circuit from the television or radio. (That is, make certain the computer and the television or radio are on circuits controlled by different circuit breakers or fuses.) If necessary, consult an Apple Authorized Service Provider or Apple. See the service and support information that came with your Apple product. Or, consult an experienced radio/television technician for additional suggestions. Important: Changes or modifications to this product not authorized by Apple Inc. could void the EMC compliance and negate your authority to operate the product.37 This product was tested for FCC compliance under conditions that included the use of Apple peripheral devices and Apple shielded cables and connectors between system components. It is important that you use Apple peripheral devices and shielded cables and connectors between system components to reduce the possibility of causing interference to radios, television sets, and other electronic devices. You can obtain Apple peripheral devices and the proper shielded cables and connectors through an Apple-authorized dealer. For non-Apple peripheral devices, contact the manufacturer or dealer for assistance. Responsible party (contact for FCC matters only) Apple Inc., Corporate Compliance, 1 Infinite Loop M/S 26-A, Cupertino, CA 95014-2084 Industry Canada Statement This Class B device meets all requirements of the Canadian interference-causing equipment regulations. Cet appareil numérique de la Class B respecte toutes les exigences du Règlement sur le matériel brouilleur du Canada. VCCI Class B Statement Europe—EU Declaration of Conformity For more information, see www.apple.com/euro/ compliance. European Union — Disposal Information This symbol means that according to local laws and regulations your product should be disposed of separately from household waste. When this product reaches its end of life, take it to a collection point designated by local authorities. Some collection points accept products for free. The separate collection and recycling of your product at the time of disposal will help conserve natural resources and ensure that it is recycled in a manner that protects human health and the environment. žŸ1 ¡{| f!Π-Ÿ q¼❞l±àm¤Šðþ …❞B Apple mØQnÁÂj$% www.apple.com.cn/environment❞ California: The coin cell battery in your product contains perchlorates. Special handling and disposal may apply. Refer to www.dtsc.ca.gov/hazardouswaste/ perchlorate. Deutschland: Dieses Gerät enthält Batterien. Bitte nicht in den Hausmüll werfen. Entsorgen Sie dieses Gerätes am Ende seines Lebenszyklus entsprechend der maßgeblichen gesetzlichen Regelungen. Nederlands: Gebruikte batterijen kunnen worden ingeleverd bij de chemokar of in een speciale batterijcontainer voor klein chemisch afval (kca) worden gedeponeerd.38 Taiwan: Singapore Wireless Certification Taiwan Warning Statements Korea Warning Statements © 2009 Apple Inc. ¤opq❞ Apple❝c❝Apple îr❝AirPort❝ AirPort Express❝ AirPort Extreme❝Apple TV❝Bonjour❝iPod❝Leopard❝ Macintosh❝Mac OS ! Time Capsule v Apple Inc. d8 9–’©9ò!m÷Q3xî❞Finder❝iPhone ! Time Machine v Apple Inc. xî❞ ®Ù{–’©!Î!st€ˆ6:v’mDst xî❞www.apple.com/airport www.apple.com/support/airport CH019-1384-A Time Capsule Setup Guide3 Contents 5 Getting Started 8 About Your Time Capsule 9 About the AirPort Software 10 What You Need to Get Started 12 The Time Capsule Status Light 14 Setting Up Your Time Capsule 15 Using Your Time Capsule to Create Your Wireless Network 18 Using AirPort Utility 20 Creating a New Wireless Network 20 Configuring and Sharing Internet Access 22 Setting Advanced Options 23 Allowing Wireless Clients to Access Your Network Without Entering a Password 24 Using Time Machine with Your Time Capsule 26 Tips and Troubleshooting 26 If You Can’t Connect to the Internet 26 If You Forgot Your Network Password or Time Capsule Password 28 If Your Time Capsule Isn’t Responding 29 If Your Time Capsule Status Light Flashes Amber4 30 If Your Printer Isn’t Responding 31 Updating AirPort Software 31 Time Capsule Placement Considerations 32 Items That Can Cause Interference with AirPort 33 Learning More, Service, and Support 35 Time Capsule Specifications and Safety Guidelines 38 Regulatory Compliance Information1 5 Getting Started Congratulations on purchasing your Time Capsule. Read this guide to get started. Time Capsule offers you the simplicity of fully automated backup for your Wi-Fi network. Using the Time Machine application in Mac OS X v10.5.7 Leopard or later, it’s easy and automatic to back up all the computers on your network to a single Time Capsule. The Time Capsule is also a fully featured AirPort Extreme Base Station that provides simultaneous dual-band wireless networking.When you set up your Time Capsule, it creates two high-speed Wi-Fi networks:  A 2.4 gigahertz (GHz) network for 802.11b, 802.11g, and 802.11n devices, such as iPhone, iPod touch, and older computers  A 5 GHz network for 802.11n and 802.11a devices, such as newer computers, iPad, and Apple TV Wireless devices join the network that provides them the best performance and compatibility, and the Time Capsule shares your broadband Internet connection with computers and devices on your network.6 Chapter 1 Getting Started With your Time Capsule, you can:  Use the Time Machine application in Mac OS X v10.5.7 (or later) to back up all the computers on your wireless network, as well as computers connected to your Time Capsule using Ethernet. Note:  Your first backup with Time Capsule and Time Machine could take overnight or longer, depending on how much data you’re backing up. To speed up the initial backup, use an Ethernet cable to connect your computer to the LAN port on your Time Capsule. For more information about using Time Machine, see “Using Time Machine with Your Time Capsule” on page 24.  Create a password-protected wireless home network, and then connect to the Internet and share the connection with other computers and Wi-Fi devices, such as iPad, iPhone, iPod touch, and Apple TV. You can also share files among computers connected to the network.  Create a guest network, with or without password protection to provide Internet-only access to wireless devices, such as computers, iPad, iPhone, iPod touch, and Apple TV.  Connect your Time Capsule to your Ethernet network.Wireless-equipped Mac, Windows XP, Windows Vista, or Windows 7 computers can then have access to an entire network without being connected by a cable.  Connect a supported USB printer to your Time Capsule. Compatible computers on the AirPort network, both wireless and wired, can print to it.  Connect an additional USB hard drive to your Time Capsule. Compatible computers on the AirPort network, both wireless and wired, can access information on the hard disk.Chapter 1 Getting Started 7  Connect a USB hub to your Time Capsule, and then connect multiple USB devices, such as printers or hard disks. All computers on the network have access to those devices. Important:  Use AirPort Utility to set up your Time Capsule. Previous versions of AirPort Setup Assistant and AirPort Admin Utility are not compatible with this Time Capsule. AirPort Utility is installed in the Utilities folder in the Applications folder on a computer using Mac OS X, and in Start > All Programs > AirPort on a computer using Windows. If AirPort Utility isn’t installed on your computer, you can download it from www.apple.com/support/airport. Apple periodically updates AirPort software. It’s recommended that you update your software to keep your Time Capsule up to date. Note:  To download a copy of this setup guide in your language, open AirPort Utility and choose Help > AirPort Service and Support, and click Manuals.8 Chapter 1 Getting Started About Your Time Capsule Your Time Capsule has five ports on the back:  One 10/100/1000Base-T Gigabit Ethernet Wide Area Network (WAN) port for connecting a DSL or cable modem, or for connecting to an existing Ethernet network  Three 10/100/1000Base-T Gigabit Ethernet Local Area Network (LAN) ports for connecting Ethernet devices, such as printers or computers, or for connecting to an existing Ethernet network  One USB port for connecting a compatible USB printer, hard drive, or hub for connecting several devices Status light Internet WAN port Power port Power cord USB port Reset button Ethernet ports Security slot Ethernet activity light The reset button next to the ports is used for troubleshooting your Time Capsule. The status light on the front shows the current status.Chapter 1 Getting Started 9 About the AirPort Software Your Time Capsule works with AirPort Utility, installed in the Utilities folder in the Applications folder on a computer using Mac OS X, and in Start > All Programs > AirPort on a computer using Windows. If AirPort Utility isn’t installed on your computer, you can download it from www.apple.com/support/airport. Use AirPort Utility and follow the instructions on the following pages to set up your Time Capsule and your AirPort wireless network. Note:  You must use AirPort Utility v5.5.3 (or later) to set up your Time Capsule. This Time Capsule is not compatible with previous versions of AirPort software. AirPort Utility Use AirPort Utility to set up your Time Capsule to create a wireless network, connect to the Internet, and share compatible USB printers and hard disks. You can also connect your Time Capsule to an existing AirPort Extreme wireless network. AirPort Utility is also an advanced tool for setting up and managing the Time Capsule, AirPort Extreme, and AirPort Express Base Stations. Use it to manually adjust network, routing, and security settings and other advanced options. Z AirPort status menu Use the AirPort status menu in the menu bar to switch quickly between AirPort networks, monitor the signal quality of the current network, create a computer-to-computer network, and turn AirPort on or off. The status menu is available on computers using Mac OS X.10 Chapter 1 Getting Started What You Need to Get Started To use your Time Capsule, you need a wireless-enabled computer that’s compliant with IEEE 802.11a, 802.11b, 802.11g, or IEEE 802.11n standards. To set up your Time Capsule, your computer must meet the requirements listed below. Note:  To use your Time Capsule with Time Machine in Mac OS X, you need to use Mac OS X v10.5.7 or later. To set up your Time Capsule using a Mac, you need the following:  A Mac computer with an AirPort or AirPort Extreme Card installed to set it up wirelessly, or a Mac computer connected to your Time Capsule with an Ethernet cable to set it up using Ethernet  Mac OS X v10.5.7 or later  AirPort Utility v5.5.3 or later To set up your Time Capsule using a Windows computer, you need the following:  A Windows computer with 300 MHz or higher processor speed and a compatible 802.11a, 802.11b, or 802.11g, IEEE 802.11n wireless card, or a Windows computer connected to a Time Capsule with an Ethernet cable to set it up using Ethernet  Windows XP Home or Professional (SP3), Windows Vista (SP2), or Windows 7 (SP1)  AirPort Utility v5.5.3 or laterChapter 1 Getting Started 11 Plugging In Your Time Capsule Before you plug in your Time Capsule, first connect the appropriate cables to the ports you want to use:  Connect the Ethernet cable that’s connected to your DSL or cable modem (if you will connect to the Internet) to the Ethernet WAN (<) port.  Connect a USB cable connected from the USB (d) port on your Time Capsule to a compatible USB printer (if you will print to a USB printer), a hard disk, or a hub.  Connect an Ethernet cable from any Ethernet device to the Ethernet LAN (G) ports. After you’ve connected the cables for all the devices you plan to use, connect the power cord to the power port and plug your Time Capsule into a power outlet. There is no power switch. Important:  Use only the power cord that came with your Time Capsule. When you plug your Time Capsule into a power outlet, the status light flashes green for one second and then glows amber while your Time Capsule starts up. After your Time Capsule has started up completely, the status light flashes amber until your Time Capsule has been updated with the correct settings. The status light glows solid green after your Time Capsule is properly set up and connected to the Internet or a network. When you connect Ethernet cables to the Ethernet ports, the lights above them glow solid green.12 Chapter 1 Getting Started The Time Capsule Status Light The following table explains the Time Capsule light sequences and what they indicate. Light Status/description Off Your Time Capsule is unplugged. Solid amber Your Time Capsule is completing its startup sequence. Flashing amber Your Time Capsule can’t establish a connection to the network or the Internet, or is encountering a problem. Make sure you have installed AirPort Utility and use it to get information about what might cause the status light to flash amber. See “If Your Time Capsule Status Light Flashes Amber” on page 29. Solid green Your Time Capsule is on and working properly. If you choose Flash On Activity from the Status Light pop-up menu (in the Base Station pane of AirPort settings in AirPort Utility), the status light may flash green to indicate normal activity. Flashing amber and green There may be a problem starting up. Your Time Capsule will restart and try again. Solid blue Your Time Capsule is ready to allow a wireless client access to the network. See “Allowing Wireless Clients to Access Your Network Without Entering a Password” on page 23.Chapter 1 Getting Started 13 What’s Next After you plug in your Time Capsule, use AirPort Utility to set it up to work with your Internet connection, USB printer or hard disk, or an existing network. AirPort Utility is located in the Utilities folder in the Applications folder on a computer using Mac OS X, and in Start > All Programs > AirPort on a computer using Windows XP or Windows Vista.14 2 Setting Up Your Time Capsule This chapter provides information and instructions for connecting your Time Capsule to the Internet, and using AirPort Utility to set it up to create or join a wireless network. This chapter provides an overview of connecting your Time Capsule to the Internet, and using the setup assistant in AirPort Utility to set up your network and other features of your Time Capsule. For more information about wireless networking, and for information about the advanced features of AirPort Utility, refer to “Apple AirPort Networks” at www.apple.com/support/airport. You can do most of your network setup and configuration tasks using the setup assistant in AirPort Utility. To set advanced options, choose Manual Setup from the Base Station menu of AirPort Utility. See “Setting Advanced Options” on page 22.Chapter 2 Setting Up Your Time Capsule 15 Using Your Time Capsule to Create Your Wireless Network When you set up your Time Capsule to provide network and Internet access, the following computers and devices can access the wireless AirPort network to share files, play games, and use Internet applications such as web browsers and email applications:  Mac computers with AirPort or AirPort Extreme Cards  802.11a, 802.11b, 802.11g, and IEEE 802.11n wireless-equipped computers  Other Wi-Fi devices, such as iPad, iPhone, iPod Touch, and Apple TV Computers connected to your Time Capsule using Ethernet can also access the network to share files and connect to the Internet. With Mac OS X v10.5.7 or later you can set up Time Machine to back up all the computers on the network to your Time Capsule. See “Using Time Machine with Your Time Capsule” on page 24 for more information. When you connect a compatible USB printer to your Time Capsule, supported computers on the network (wired and wireless) can print to it.16 Chapter 2 Setting Up Your Time Capsule Using Time Capsule to create a wireless network to Internet DSL or cable modem < Internet WAN port Shared printer Time Capsule to USB port 2.4 or 5 GHz 2.4 GHz 2.4 or 5 GHz To set it up: 1 Connect your DSL or cable modem to your Time Capsule using the Ethernet WAN (<) port. 2 If you plan to share a USB printer on the network, connect it to the Time Capsule USB (d) port or to a USB hub using a USB cable.Chapter 2 Setting Up Your Time Capsule 17 3 Open AirPort Utility (located in the Utilities folder in the Applications folder on a computer using Mac OS X, and in Start > All Programs > AirPort on a computer using Windows), select your Time Capsule, and then click Continue. 4 Follow the onscreen instructions to create a new network. To print from a computer using Mac OS X v10.5 or later: 1 Choose Apple > System Preferences, and then click Print & Fax. 2 Click Add (+) and select your printer from the list. 3 Click the Add button. If your printer isn’t in the list, use the buttons in the toolbar to search for it. To print from a computer using Mac OS X v10.2.7 or later: 1 Open Printer Setup Utility (located in the Utilities folder in the Applications folder). 2 Select your printer from the list. If your printer isn’t in the list, click Add and choose Bonjour from the pop-up menu, and then select your printer from the list. To print from a computer using Windows XP, Windows Vista, or Windows 7: Use Bonjour for Windows and follow the onscreen instructions to connect to your printer. Computers using AirPort or other compatible wireless cards or adapters can connect to the Internet through your Time Capsule. Computers connected to the Time Capsule Ethernet ports can also access the network and connect to the Internet. Wireless computers and computers connected to the Ethernet ports can also communicate with each other through your Time Capsule.18 Chapter 2 Setting Up Your Time Capsule Using AirPort Utility To set up and configure your Time Capsule, use the setup assistant in AirPort Utility. On a Mac computer using Mac OS X v10.5.7 or later: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder. 2 Select your Time Capsule and click Continue. If you don’t see the Time Capsule you want to configure, click Rescan to scan for available wireless devices, and then select your Time Capsule from the list. 3 Follow the onscreen instructions to set up your Time Capsule and your wireless network. On a computer using Windows XP (SP3), Windows Vista (SP2), or Windows 7 (SP1): 1 Open AirPort Utility, located in Start > All Programs > AirPort. 2 Select your Time Capsule and click Continue. If AirPort Utility isn’t installed on your computer, you can download it from www.apple.com/support/airport.Chapter 2 Setting Up Your Time Capsule 19 3 Follow the onscreen instructions to set up your Time Capsule and your wireless network. The AirPort Utility setup assistant asks you questions about the type of network you want to use and the services you want to set up, and helps you enter the appropriate settings. If you’re using your Time Capsule to connect to the Internet, you need a broadband (DSL or cable modem) account with an Internet service provider (ISP), or a connection to the Internet using an existing Ethernet network. If you received specific information from your ISP (such as a static IP address or a DHCP client ID), you may need to enter it in AirPort Utility. Have this information available when you set up your Time Capsule.20 Chapter 2 Setting Up Your Time Capsule Creating a New Wireless Network You can use the AirPort Utility setup assistant to create a new wireless network. The setup assistant guides you through the steps necessary to name your network, protect your network with a password, and set other options. If you plan to share a USB printer or USB hard disk on your network: 1 Connect the printer or hard disk to the Time Capsule USB (d) port. 2 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or in Start > All Programs > AirPort on a computer using Windows. 3 Select your Time Capsule and click Continue. If you don’t see the Time Capsule you want to configure, click Rescan to scan for available wireless devices, and then select your Time Capsule from the list. 4 Follow the onscreen instructions to create a new network. Configuring and Sharing Internet Access If you plan to share your Internet connection with wireless-enabled computers on your network or with computers connected to the Ethernet ports, you need to set up your Time Capsule as an AirPort base station. After your Time Capsule is set up, computers access the Internet through the AirPort network. Your Time Capsule connects to the Internet and transmits information to the computers over the wireless network. Before you use AirPort Utility to set up your Time Capsule, connect your DSL or cable modem to the Time Capsule Ethernet WAN (<) port. If you’re connecting your Time Capsule to an Ethernet network that already has Internet access, connect it to the Ethernet network.Chapter 2 Setting Up Your Time Capsule 21 Use the AirPort Utility setup assistant to enter your ISP settings and configure how your Time Capsule shares the settings with other computers. 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a computer using Mac OS X, or in Start > All Programs > AirPort on a computer using Windows. If AirPort Utility isn’t installed on your computer, you can download it from www.apple.com/support/airport. 2 Select your Time Capsule and click Continue. If you’re making changes to a Time Capsule that has already been set up, you might have to connect to the network it’s created before making changes to the Time Capsule. To choose the wireless network you want to change on a Mac, use the AirPort status menu in the menu bar. On a computer using Windows, hold the pointer over the wireless connection icon until you see the network name (SSID), and then choose it from the list if there are multiple networks available. 3 Follow the onscreen instructions to configure and share Internet access on your Time Capsule. AirPort Utility provides a quick and easy way to set up your Time Capsule and network. If you want to set additional options for your network, such as restricting access to your network or setting advanced DHCP options, choose Manual Setup from the Base Station menu of AirPort Utility.22 Chapter 2 Setting Up Your Time Capsule Setting Advanced Options Use AirPort Utility to set up your Time Capsule manually if you want to set advanced Time Capsule options such as advanced security options, closed networks, DHCP lease time, access control, power controls, user accounts, and more. To set advanced options: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, and in Start > All Programs > AirPort on a computer using Windows. If AirPort Utility isn’t installed on your computer, you can download it from www.apple.com/support/airport. 2 If there’s more than one wireless device in the list, select the one you want to configure. If you don’t see the Time Capsule you want to configure, click Rescan to scan for available wireless devices, and then select your Time Capsule from the list. If you’re making changes to a Time Capsule that has already been set up, you might have to connect to the network it’s created before making changes to your Time Capsule. To choose the wireless network you want to change on a Mac, use the AirPort status menu in the menu bar. On a computer using Windows, hold the pointer over the wireless connection icon until you see the network name (SSID), and then choose it from the list if there are multiple networks available. 3 Choose Manual Setup from the Base Station menu. If you’re prompted for a password, enter it. For more about the manual setup features in AirPort Utility, see “Apple AirPort Networks” at www.apple.com/support/airport.Chapter 2 Setting Up Your Time Capsule 23 Allowing Wireless Clients to Access Your Network Without Entering a Password If your network is password-protected using WPA Personal or WPA/WPA2 Personal, you can provide wireless clients access to your network without requiring them to enter the network password. When you allow a client access to your network, the client’s name and wireless MAC address (or AirPort ID) are stored in the access control list of AirPort Utility until you remove the client from the list. You can also provide 24 hours of access, after which time the client can no longer access your network. When you give a client access to your wireless network, the client doesn’t need to enter the network password. To allow a client to access your network without entering the network password: 1 Open AirPort Utility, select your Time Capsule, and then choose Manual Setup from the Base Station menu. Enter the password if necessary. 2 Choose Add Wireless Clients from the Base Station menu. 3 Select how you want the client to access the network:  Select PIN to enter the eight-digit number provided by the client requesting network access.  Select“First attempt”to allow network access to the first client attempting to join the network. While the Time Capsule waits for a client to join the network, the LED glows blue.24 Chapter 2 Setting Up Your Time Capsule Select“Limit client’s access to 24 hours”if you want to provide just one day of access to your network. If you don’t select this option, the client has access until you remove the client from the list. Using Time Machine with Your Time Capsule With the Time Machine application in Mac OS X (Leopard or later) you can back up everything on your computer, including your photos, music, movies, and documents. After you set up Time Machine, it automatically backs up your computer on a regular basis. If you’re using Mac OS X v10.5.7 or later, the first time you connect to your Time Capsule, Time Machine asks if you’d like to use it to back up your files. Click “Use as Backup Disk,” and Time Machine takes care of the rest. Use the Time Machine pane of System Preferences to set up automatic backups, change to a different backup disk, or adjust other settings. To set up or adjust Time Machine on a computer using Mac OS X Leopard or later: 1 Choose Apple > System Preferences, and then click Time Machine. 2 Slide the switch to ON. 3 Click Change Disk. 4 Choose your Time Capsule and click “Use for Backup.”Chapter 2 Setting Up Your Time Capsule 25 Your first backup with Time Capsule and Time Machine could take overnight or longer, depending on how much data you’re backing up. To speed up the initial backup, connect your Time Capsule to your computer using Ethernet. In each subsequent backup, Time Machine backs up only files that have changed since the previous backup, so the backups don’t take as long. Time Capsule is a great wireless backup solution for portable computers. Since the first backup can take some time, plug your portable into a power adapter—this conserves battery power and guarantees that backups won’t be interrupted. Also, for the best wireless performance, place your portable computer in the same room as your Time Capsule. If you shut down your Mac or put it to sleep during a backup, Time Machine stops the backup and then continues from where it left off after your Mac starts up again. For more information about Time Machine, choose Help > Mac Help from the Finder menu on a computer using Mac OS X Leopard or later, and then type Time Machine in the search field.26 3 Tips and Troubleshooting You can quickly solve most problems with your Time Capsule by following the advice in this chapter. If You Can’t Connect to the Internet  Try connecting to the Internet directly from your computer. If you can’t connect, check to make sure your network settings are correct. If they appear to be correct and you still can’t connect, contact your Internet service provider (ISP).  Make sure you’re connecting to the correct wireless network. If You Forgot Your Network Password or Time Capsule Password You can clear the AirPort network password or Time Capsule password by resetting your Time Capsule. To reset the Time Capsule password: 1 Use something pointed (such as a ballpoint pen) to press and hold down the reset button for one second. Important:  If you hold the reset button for more than one second, you may lose your network settings.Chapter 3 Tips and Troubleshooting 27 2 Select your AirPort network.  On a Mac, use the AirPort status menu in the menu bar to select the network created by your Time Capsule (the network name doesn’t change).  On a computer using Windows, hold the pointer over the wireless connection icon until you see your AirPort network name (SSID), and choose it from the list if there are multiple networks available. 3 Open AirPort Utility (in the Utilities folder in the Applications folder on a Mac, and in Start > All Programs > AirPort on a computer using Windows). If AirPort Utility isn’t installed on your computer, you can download it from www.apple.com/support/airport. 4 Select your Time Capsule, and then choose Manual Setup from the Base Station menu. 5 Click AirPort in the toolbar, and then click Base Station. 6 Enter a new password for your Time Capsule. 7 Click Wireless and choose an encryption method from the Wireless Security pop-up menu to turn on encryption and activate password protection for your AirPort network. If you turn on encryption, enter a new password for your AirPort network. 8 Click Update to restart your Time Capsule and load the new settings.28 Chapter 3 Tips and Troubleshooting If Your Time Capsule Isn’t Responding Try unplugging it and plugging it back in. If your Time Capsule stops responding completely, you may need to reset it to the factory default settings. Important:  Resetting your Time Capsule to factory default settings erases all of the current settings and resets them to the settings that came with your Time Capsule. To return your Time Capsule to the factory settings: m Use something pointed (such as a ballpoint pen) to press down and hold the reset button until the status light flashes quickly (about 5 seconds). Your Time Capsule resets with the following settings:  Your Time Capsule receives its IP address using DHCP.  The network name is reset to Apple Network XXXXXX (where XXXXXX is replaced with the last six digits of the AirPort ID).  The Time Capsule password is reset to public. If your Time Capsule still isn’t responding, try the following: 1 Unplug your Time Capsule. 2 Use something pointed to press and hold down the reset button while you plug in your Time Capsule.Chapter 3 Tips and Troubleshooting 29 If Your Time Capsule Status Light Flashes Amber The Ethernet cable may not be connected properly, your Time Capsule may be out of range of an AirPort network, or there may be a problem with your Internet service provider. If you’re connected to the Internet with a DSL or cable modem, the modem may have lost its connection to the network or the Internet. Even if the modem seems to be working properly, try disconnecting it from its power supply, waiting a few seconds, and then reconnecting it. Make sure your Time Capsule is connected directly to the modem via Ethernet before reconnecting power to the modem. For more information about why the light is flashing, open AirPort Utility, select your Time Capsule, and then choose Manual Setup from the Base Station menu. Click Base Station Status to display information about the flashing light. You can also select“Monitor base station for problems”in AirPort preferences. If the base station has a problem, AirPort Utility opens and walks you through solving the problem.30 Chapter 3 Tips and Troubleshooting If Your Printer Isn’t Responding If you connected a printer to the USB port on your Time Capsule and the computers on the AirPort network can’t print, try the following: 1 Make sure the printer is plugged in and turned on. 2 Make sure the cables are securely connected to the printer and to the Time Capsule USB port. 3 Make sure the printer is selected in the Printer List window on client computers. On a Mac using Mac OS X v10.5 or later:  Choose Apple > System Preferences, and then click Print & Fax.  Click Add (+) and select your printer in the list, and then click Add (+). On a Mac using Mac OS X v10.2.7 or later:  Open Printer Setup Utility, located in the Utilities folder in the Applications folder.  If the printer isn’t in the list, click Add.  Choose Bonjour from the pop-up menu, select the printer and click Add (+). On a computer using Windows:  Open “Printers and Faxes”from the Start menu.  Select the printer. If the printer isn’t in the list, click Add Printer and then follow the onscreen instructions.  If Bonjour for Windows is installed, click the Bonjour Printer, click the Bonjour Printer Wizard on the desktop, and then follow the onscreen instructions for setting up a printer. 4 Turn off the printer, wait a few seconds, and then turn it back on.Chapter 3 Tips and Troubleshooting 31 Updating AirPort Software Apple periodically updates AirPort software. It is recommended that you update your Time Capsule to use the latest software. You can select“Check for updates when opening AirPort Utility,” or“Check for updates” in AirPort preferences. If you select“Check for updates,” choose an increment of time, such as weekly, from the pop-up menu to automatically check for updates. Time Capsule Placement Considerations The following recommendations can help your Time Capsule achieve the best wireless range and network coverage.  Place your Time Capsule in an open area where there are few obstructions, such as large pieces of furniture or walls. Try to place it away from metallic surfaces.  If you place your Time Capsule behind furniture, keep at least an inch of space between the Time Capsule and the edge of the furniture.  Avoid placing your Time Capsule in areas surrounded by metal surfaces on three or more sides.  If you place your Time Capsule in an entertainment center with your stereo equipment, avoid surrounding your Time Capsule with audio, video, or power cables. Place your Time Capsule so that the cables are to one side. Maintain as much space as possible between your Time Capsule and the cables.  Try to place your Time Capsule at least 25 feet (7.6 meters) from any microwave oven, 2.4 or 5 gigahertz (GHz) cordless phone, and other sources of interference.  Do not place other objects (books, papers, small pets, etc.) on top of the Time Capsule. It may interfere with Time Capsule cooling.32 Chapter 3 Tips and Troubleshooting Items That Can Cause Interference with AirPort The farther away the interference source, the less likely it is to cause a problem. The following can interfere with AirPort communication:  Microwave ovens  Direct Satellite Service (DSS) radio frequency leakage  The original coaxial cable that came with certain types of satellite dishes. Contact the device manufacturer and obtain newer cables.  Certain electrical devices such as power lines, electrical railroad tracks, and power stations.  Cordless telephones that operate in the 2.4 or 5 GHz range. If you have problems with your phone or AirPort communication, change the channel your base station or Time Capsule uses, or change the channel your phone uses.  Nearby base stations using adjacent channels. For example, if base station A is set to channel 1, base station B should be set to channel 6 or 11.4 33 Learning More, Service, and Support You can find more information about using your Time Capsule on the web and in onscreen help. Online Resources For the latest information about the Time Capsule, go to www.apple.com/airport. To register your Time Capsule, go to www.apple.com/register. For AirPort support information, forums with product-specific information and feedback, and the latest Apple software downloads, go to www.apple.com/support/airport. For support outside of the United States, go to www.apple.com/support, and then choose your country.34 Chapter 4 Learning More, Service, and Support Onscreen Help To learn more about using AirPort Utility with your Time Capsule, open AirPort Utility and choose Help > AirPort Utility Help. Obtaining Warranty Service If your Time Capsule appears to be damaged or doesn’t function properly, follow the advice in this booklet, the onscreen help, and the online resources. If your Time Capsule still doesn’t function, go to www.apple.com/support for information about getting warranty service. Finding the Serial Number of Your Time Capsule The serial number is printed on the bottom of your Time Capsule.35 Appendix Time Capsule Specifications and Safety Guidelines Time Capsule Specifications  Frequency Band: 2.4 and 5 GHz  Radio Output Power: Up to 23 dBm (nominal)  Standards: 802.11 DSSS 1 and 2 Mbps standard, 802.11a, 802.11b, 802.11g, and 802.11n specifications Interfaces  1 RJ-45 10/100/1000Base-T Gigabit Ethernet WAN (<)  3 RJ-45 10/100/1000Base-T Gigabit Ethernet LAN (G)  Universal Serial Bus (USB d) 2.0  802.11 a/b/g/n AirPort Extreme wireless Environmental Specifications  Operating Temperature: 32° F to 95° F (0° C to 35° C)  Storage Temperature: –13° F to 140° F (–25° C to 60° C)  Relative Humidity (Operational): 20% to 80% relative humidity  Relative Humidity (Storage): 10% to 90% relative humidity, noncondensing36 Appendix Time Capsule Specifications and Safety Guidelines Size and Weight  Length: 7.75 inches (197.0 mm)  Width: 7.75 inches (197.0 mm)  Height: 1.43 inches (36.33 mm)  Weight: 3.5 pounds (1.6 kilograms) Hardware Media Access Control (MAC) Addresses The Time Capsule has three hardware addresses printed on the bottom of the case:  AirPort ID: The two addresses used to identify the Time Capsule on a wireless network.  Ethernet ID: You may need to provide this address to your ISP to connect your Time Capsule to the Internet. Using Your Time Capsule Safely  The only way to shut off power completely to your Time Capsule is to disconnect it from the power source.  When connecting or disconnecting your Time Capsule, always hold the plug by its sides. Keep fingers away from the metal part of the plug.  Your Time Capsule should not be opened for any reason, even when it’s unplugged. If your Time Capsule needs service,see“Learning More, Service, and Support”on page 33.  Never force a connector into a port. If the connector and port don’t join with reasonable ease, they probably don’t match. Make sure that the connector matches the port and that you’ve positioned the connector correctly in relation to the port.Appendix Time Capsule Specifications and Safety Guidelines 37 About Operating and Storage Temperatures When you’re using your Time Capsule, it is normal for the case to get warm. The Time Capsule case functions as a cooling surface that transfers heat from inside the unit to the cooler air outside. Avoid Wet Locations WARNING:  To reduce the chance of shock or injury, do not use your Time Capsule in or near water or wet locations.  Keep your Time Capsule away from sources of liquid, such as drinks, washbasins, bathtubs, shower stalls, and so on.  Protect your Time Capsule from direct sunlight and rain or other moisture.  Take care not to spill any food or liquid on your Time Capsule. If you do, unplug it before cleaning up the spill.  Do not use your Time Capsule outdoors. The Time Capsule is an indoor product. Do Not Make Repairs Yourself WARNING:  Do not attempt to open your Time Capsule or disassemble it. You run the risk of electric shock and voiding the limited warranty. No user-serviceable parts are inside. About Handling Your Time Capsule may be damaged by improper storage or handling. Be careful not to drop your Time Capsule when transporting it.38 FCC Declaration of Conformity This device complies with part 15 of the FCC rules. Operation is subject to the following two conditions: (1) This device may not cause harmful interference, and (2) this device must accept any interference received, including interference that may cause undesired operation. See instructions if interference to radio or television reception is suspected. Radio and Television Interference This computer equipment generates, uses, and can radiate radiofrequency energy. If it is not installed and used properly—that is, in strict accordance with Apple’s instructions—it may cause interference with radio and television reception. This equipment has been tested and found to comply with the limits for a Class B digital device in accordance with the specifications in Part 15 of FCC rules. These specifications are designed to provide reasonable protection against such interference in a residential installation. However, there is no guarantee that interference will not occur in a particular installation. You can determine whether your computer system is causing interference by turning it off. If the interference stops, it was probably caused by the computer or one of the peripheral devices. If your computer system does cause interference to radio or television reception, try to correct the interference by using one or more of the following measures: • Turn the television or radio antenna until the interference stops. • Move the computer to one side or the other of the television or radio. • Move the computer farther away from the television or radio. • Plug the computer into an outlet that is on a different circuit from the television or radio. (That is, make certain the computer and the television or radio are on circuits controlled by different circuit breakers or fuses.) If necessary, consult an Apple Authorized Service Provider or Apple. See the service and support information that came with your Apple product. Or, consult an experienced radio/television technician for additional suggestions. Important:  Changes or modifications to this product not authorized by Apple Inc. could void the EMC compliance and negate your authority to operate the product. This product was tested for FCC compliance under conditions that included the use of Apple peripheral devices and Apple shielded cables and connectors between system components. It is important that you use Apple peripheral devices and shielded cables and connectors between system components to reduce the possibility of causing interference to radios, television sets, and other electronic devices. You can obtain Apple peripheral devices and the proper shielded cables and connectors through an Appleauthorized dealer. For non-Apple peripheral devices, contact the manufacturer or dealer for assistance. Responsible party (contact for FCC matters only) Apple Inc. Corporate Compliance 1 Infinite Loop M/S 26-A Cupertino, CA 95014 Wireless Radio Use This device is restricted to indoor use when operating in the 5.15 to 5.25 GHz frequency band. Cet appareil doit être utilisé à l’intérieur. Exposure to Radio Frequency Energy The radiated output power of the AirPort Card in this device is below the FCC and EU radio frequency exposure limits for uncontrolled equipment. This device should be operated with a minimum distance of at least 20 cm between the AirPort Card antennas and a person’s body and must not be co-located or operated with any other antenna or transmitter subject to the conditions of the FCC Grant.39 Canadian Compliance Statement This device complies with Industry Canada license-exempt RSS standard(s). Operation is subject to the following two conditions: (1) this device may not cause interference, and (2) this device must accept any interference, including interference that may cause undesired operation of the device. Cet appareil est conforme aux normes CNR exemptes de licence d’Industrie Canada. Le fonctionnement est soumis aux deux conditions suivantes : (1) cet appareil ne doit pas provoquer d’interférences et (2) cet appareil doit accepter toute interférence, y compris celles susceptibles de provoquer un fonctionnement non souhaité de l’appareil. Industry Canada Statement Complies with the Canadian ICES-003 Class B specifications. Cet appareil numérique de la classe B est conforme à la norme NMB-003 du Canada. This device complies with RSS 210 of Industry Canada. Europe–EU Declaration of Conformity Български Apple Inc. декларира, че това WLAN Access Point е в съответствие със съществените изисквания и другите приложими правила на Директива 1999/5/ЕС. Česky Společnost Apple Inc. tímto prohlašuje, že tento WLAN Access Point je ve shodě se základními požadavky a dalšími příslušnými ustanoveními směrnice 1999/5/ES. Dansk Undertegnede Apple Inc. erklærer herved, at følgende udstyr WLAN Access Point overholder de væsentlige krav og øvrige relevante krav i direktiv 1999/5/EF. Deutsch Hiermit erklärt Apple Inc., dass sich das Gerät WLAN Access Point in Übereinstimmung mit den grundlegenden Anforderungen und den übrigen einschlägigen Bestimmungen der Richtlinie 1999/5/EG befinden. Eesti Käesolevaga kinnitab Apple Inc., et see WLAN Access Point vastab direktiivi 1999/5/EÜ põhinõuetele ja nimetatud direktiivist tulenevatele teistele asjakohastele sätetele. English Hereby, Apple Inc. declares that this WLAN Access Point is in compliance with the essential requirements and other relevant provisions of Directive 1999/5/EC. Español Por medio de la presente Apple Inc. declara que este WLAN Access Point cumple con los requisitos esenciales y cualesquiera otras disposiciones aplicables o exigibles de la Directiva 1999/5/CE. Ελληνικά Mε την παρούσα, η Apple Inc. δηλώνει ότι αυτή η συσκευή WLAN Access Point συμμορφώνεται προς τις βασικές απαιτήσεις και τις λοιπές σχετικές διατάξεις της Οδηγίας 1999/5/ΕΚ. Français Par la présente Apple Inc. déclare que l’appareil WLAN Access Point est conforme aux exigences essentielles et aux autres dispositions pertinentes de la directive 1999/5/CE. Islenska Apple Inc. lýsir því hér með yfir að þetta tæki WLAN Access Point fullnægir lágmarkskröfum og öðrum viðeigandi ákvæðum Evróputilskipunar 1999/5/EC. Italiano Con la presente Apple Inc. dichiara che questo dispositivo WLAN Access Point è conforme ai requisiti essenziali ed alle altre disposizioni pertinenti stabilite dalla direttiva 1999/5/CE. Latviski Ar šo Apple Inc. deklarē, ka WLAN Access Point ierīce atbilst Direktīvas 1999/5/EK būtiskajām prasībām un citiem ar to saistītajiem noteikumiem. Lietuvių Šiuo „Apple Inc.“ deklaruoja, kad šis WLAN Access Point atitinka esminius reikalavimus ir kitas 1999/5/EB Direktyvos nuostatas. Magyar Alulírott, Apple Inc. nyilatkozom, hogy a WLAN Access Point megfelel a vonatkozó alapvetõ követelményeknek és az 1999/5/EC irányelv egyéb elõírásainak. 40 Malti Hawnhekk, Apple Inc., jiddikjara li dan WLAN Access Point jikkonforma mal-ħtiġijiet essenzjali u ma provvedimenti oħrajn relevanti li hemm fid-Dirrettiva 1999/5/EC. Nederlands Hierbij verklaart Apple Inc. dat het toestel WLAN Access Point in overeenstemming is met de essentiële eisen en de andere bepalingen van richtlijn 1999/5/EG. Norsk Apple Inc. erklærer herved at dette WLAN Access Point -apparatet er i samsvar med de grunnleggende kravene og øvrige relevante krav i EU-direktivet 1999/5/EF. Polski Niniejszym Apple Inc. oświadcza, że ten WLAN Access Point są zgodne z zasadniczymi wymogami oraz pozostałymi stosownymi postanowieniami Dyrektywy 1999/5/EC. Português Apple Inc. declara que este dispositivo WLAN Access Point está em conformidade com os requisitos essenciais e outras disposições da Directiva 1999/5/CE. Română Prin prezenta, Apple Inc. declară că acest aparat WLAN Access Point este în conformitate cu cerinţele esenţiale şi cu celelalte prevederi relevante ale Directivei 1999/5/CE. Slovensko Apple Inc. izjavlja, da je ta WLAN Access Point skladne z bistvenimi zahtevami in ostalimi ustreznimi določili direktive 1999/5/ES. Slovensky Apple Inc. týmto vyhlasuje, že toto WLAN Access Point spĺňa základné požiadavky a všetky príslušné ustanovenia Smernice 1999/5/ES. Suomi Apple Inc. vakuuttaa täten, että tämä WLAN Access Point tyyppinen laite on direktiivin 1999/5/EY oleellisten vaatimusten ja sitä koskevien direktiivin muiden ehtojen mukainen. Svenska Härmed intygar Apple Inc. att denna WLAN Access Point står i överensstämmelse med de väsentliga egenskapskrav och övriga relevanta bestämmelser som framgår av direktiv 1999/5/EG. A copy of the EU Declaration of Conformity is available at: www.apple.com/euro/compliance This Apple WLAN Access Point can be used in the following countries: AT EE BG FI BE FR CY DE CZ GR DK HU IE IT LV LT LU MT NL PL PT RO SK SL ES SE GB IS LI NO CH Korea Warning Statements B૶ૺૺ(ਜ਼ႜဧ෮໽ቛཅૺၴႁ) ၦૺૺ௴ਜ਼ႜဧ(B૶) ႖ၴኒ႕ጁૺૺച໏჎ച ਜ਼ႜ࿝໏ຫဧዻ௴ઇၕඛ႕ၒചዻඑ, ක౷ხ ࿦࿝໏ຫဧዾ༘ၰཀఁఋ. ෮ቛ၁ધགྷ࿝ಋ൏ધხຫጃ ጄఙඳ໓໕๗௴ဪဧთ႖ኒጯཅਜ਼௻ໜၦၰၗ ၦૺૺ௴ၨ඗ྦ႖઴શഏౘ໏๗༺࿝ຫဧዾ༘࿖ཀఁఋ ఝዽූ૑ ૬ႜ ෟ ა༘ Singapore Wireless Certification41 Taiwan Wireless Statements Taiwan Class B Statement 警告 本電池如果更換不正確會有爆炸的危險 請依製造商說明書處理用過之電池 Japan VCCI Class B Statement Russia Disposal and Recycling Information This symbol indicates that your product must be disposed of properly according to local laws and regulations.When your product reaches its end of life, contact Apple or your local authorities to learn about recycling options. For information about Apple’s recycling program, go to www.apple.com/recycling. European Union — Disposal Information This symbol means that according to local laws and regulations your product should be disposed of separately from household waste.When this product reaches its end of life, take it to a collection point designated by local authorities. Some collection points accept products for free. The separate collection and recycling of your product at the time of disposal will help conserve natural resources and ensure that it is recycled in a manner that protects human health and the environment. Türkiye EEE yönetmeliğine (Elektrikli ve Elektronik Eşyalarda Bazı Zararlı Maddelerin Kullanımının Sınırlandırılmasına Dair Yönetmelik) uygundur.42 Brasil—Informações sobre descarte e reciclagem O símbolo acima indica que este produto e/ou sua bateria não devem ser descartadas no lixo doméstico. Quando decidir descartar este produto e/ou sua bateria, faça-o de acordo com as leis e diretrizes ambientais locais. Para informações sobre o programa de reciclagem da Apple, pontos de coleta e telefone de informações, visite www.apple.com/br/environment Battery Disposal Information Dispose of batteries according to your local environmental laws and guidelines. Deutschland: Dieses Gerät enthält Batterien. Bitte nicht in den Hausmüll werfen. Entsorgen Sie dieses Gerät am Ende seines Lebenszyklus entsprechend der maßgeblichen gesetzlichen Regelungen. Nederlands:  Gebruikte batterijen kunnen worden ingeleverd bij de chemokar of in een speciale batterijcontainer voor klein chemisch afval (kca) worden gedeponeerd. China Battery Statement Taiwan Battery Statementwww.apple.com/airport www.apple.com/support/airport © 2011 Apple Inc. All rights reserved. Apple, the Apple logo, AirPort, AirPort Express, AirPort Extreme, Apple TV, Bonjour, Finder, iPhone, iPod touch, Leopard, Mac, Mac OS, Time Capsule, and Time Machine are trademarks of Apple Inc., registered in the U.S. and other countries. iPad is a trademark of Apple Inc. Other product and company names mentioned herein may be trademarks of their respective companies. 034-5910-A Printed in XXXX Time Capsule Setup Guide3 Contents 5 Chapter 1: Getting Started 7 About Your Time Capsule 8 About the AirPort Software 9 What You Need to Get Started 11 The Time Capsule Status Light 13 Chapter 2: Setting Up Your Time Capsule 14 Using Your Time Capsule to Create Your Wireless Network 17 Using AirPort Utility 19 Creating a New Wireless Network 19 Configuring and Sharing Internet Access 21 Setting Advanced Options 22 Allowing Wireless Clients to Access Your Network Without Entering a Password 23 Using Time Machine with Your Time Capsule 25 Chapter 3: Tips and Troubleshooting 25 If You Can’t Connect to the Internet 25 If You Forgot Your Network Password or Time Capsule Password 26 If Your Time Capsule Isn’t Responding 27 If Your Time Capsule Status Light Flashes Amber4 Contents 28 If Your Printer Isn’t Responding 29 Updating AirPort Software 29 Time Capsule Placement Considerations 30 Items That Can Cause Interference with AirPort 31 Chapter 4: Learning More, Service, and Support 33 Appendix: Time Capsule Specifications and Safety Guidelines 36 Regulatory Compliance Information1 5 1 Getting Started Congratulations on purchasing your Time Capsule. Read this guide to get started. The new Time Capsule offers you the simplicity of fully automated backup for your Wi-Fi network. Using the Time Machine application in Mac OS X v10.5.2 Leopard or later, it’s easy and automatic to back up all the computers on your network to a single Time Capsule. The Time Capsule is also a fully featured AirPort Extreme Base Station that provides simultaneous dual-band wireless networking. When you set up your Time Capsule, it creates two high-speed Wi-Fi networks:  A 2.4 gigahertz (GHz) network for 802.11b, 802.11g, and 802.11n devices, such as iPhone, iPod touch, and older computers  A 5 GHz network for 802.11n and 802.11a devices, such as newer computers and Apple TV Wireless devices join the network that provides them the best performance and compatibility, and the Time Capsule shares your broadband Internet connection with computers and devices on your network.6 Chapter 1 Getting Started With your Time Capsule, you can:  Use the Time Machine application in Mac OS X v10.5.2 (or later) to back up all the computers on your wireless network, as well as computers connected to your Time Capsule using Ethernet. Note: Your first backup with Time Capsule and Time Machine could take overnight or longer, depending on how much data you’re backing up. To speed up the initial backup, use an Ethernet cable to connect your computer to the LAN port on your Time Capsule. For more information about using Time Machine, see “Using Time Machine with Your Time Capsule” on page 23.  Create a password-protected wireless home network, and then connect to the Internet and share the connection with other computers and Wi-Fi devices, such as iPhone, iPod touch, and Apple TV. You can also share files among computers connected to the network.  Create a guest network with or without password protection, to provide Internetonly access to wireless devices, such as computers, iPhone, iPod touch, and Apple TV.  Connect your Time Capsule to your Ethernet network. Wireless-equipped Macintosh, Windows XP, or Windows Vista computers can then have access to an entire network without being connected by a cable.  Connect a supported USB printer to your Time Capsule. Compatible computers on the AirPort network, both wireless and wired, can print to it.  Connect an additional USB hard drive to your Time Capsule. Compatible computers on the AirPort network, both wireless and wired, can access information on the hard disk.Chapter 1 Getting Started 7  Connect a USB hub to your Time Capsule, and then connect multiple USB devices, such as printers or hard disks. All computers on the network have access to those devices. Important: Install AirPort Utility 5.4 from the CD that came with your Time Capsule, or download it using Software Update. Previous versions of AirPort Setup Assistant and AirPort Admin Utility are not compatible with this Time Capsule. About Your Time Capsule Your Time Capsule has five ports on the back:  One 10/100/1000Base-T Gigabit Ethernet Wide Area Network (WAN) port for connecting a DSL or cable modem, or for connecting to an existing Ethernet network  Three 10/100/1000Base-T Gigabit Ethernet Local Area Network (LAN) ports for connecting Ethernet devices, such as printers or computers, or for connecting to an existing Ethernet network 8 Chapter 1 Getting Started  One USB port for connecting a compatible USB printer, hard drive, or hub for connecting several devices The reset button next to the ports is used for troubleshooting your Time Capsule. The status light on the front shows the current status. About the AirPort Software Your Time Capsule works with AirPort Utility, included on the Time Capsule CD. Install AirPort Utility and follow the instructions on the following pages to set up your Time Capsule and your AirPort wireless network. Status light Internet WAN port Power port Power cord USB port Reset button Ethernet ports Security slot Ethernet activity lightChapter 1 Getting Started 9 Note: You must use AirPort Utility v5.4 to set up your Time Capsule. This Time Capsule is not compatible with previous versions of AirPort software. What You Need to Get Started To use your Time Capsule, you need a wireless-enabled computer that’s compliant with IEEE 802.11a, 802.11b, or 802.11g standards, or with an IEEE 802.11n draft specification. To set up your Time Capsule, your computer must meet the requirements listed below. Note: To use your Time Capsule with Time Machine in Mac OS X Leopard, you need to use Mac OS X v10.5.2 or later. To set up your Time Capsule using a Macintosh, you need the following:  A Macintosh computer with an AirPort or AirPort Extreme Card installed to set it up wirelessly, or a Macintosh computer connected to your Time Capsule with an Ethernet cable to set it up using Ethernet AirPort Utility Use AirPort Utility to set up your Time Capsule to create a wireless network, connect to the Internet, and share compatible USB printers and hard disks. You can also connect your Time Capsule to an existing AirPort Extreme wireless network. AirPort Utility is also an advanced tool for setting up and managing the Time Capsule, AirPort Extreme, and AirPort Express Base Stations. Use it to manually adjust network, routing, and security settings and other advanced options. Z AirPort status menu Use the AirPort status menu in the menu bar to switch quickly between AirPort networks, monitor the signal quality of the current network, create a computer-tocomputer network, and turn AirPort on or off. The status menu is available on computers using Mac OS X. 10 Chapter 1 Getting Started  Mac OS X v10.4 or later  AirPort Utility v5.4 or later To set up your Time Capsule using a Windows PC, you need the following:  A Windows PC with 300 MHz or higher processor speed and a compatible 802.11a, 802.11b, or 802.11g wireless card, or a wireless card that complies with an IEEE 802.11n draft specification  Windows XP Home or Professional (with Service Pack 2 installed) or Windows Vista  AirPort Utility v5.4 or later Plugging In Your Time Capsule Before you plug in your Time Capsule, first connect the appropriate cables to the ports you want to use:  Connect the Ethernet cable that’s connected to your DSL or cable modem (if you will connect to the Internet) to the Ethernet WAN (<) port.  Connect a USB cable connected from the USB (d) port on your Time Capsule to a compatible USB printer (if you will print to a USB printer), a hard disk, or a hub.  Connect an Ethernet cable from any Ethernet device to the Ethernet LAN (G) ports. After you’ve connected the cables for all the devices you plan to use, connect the power cord to the power port and plug your Time Capsule into a power outlet. There is no power switch. Important: Use only the power cord that came with your Time Capsule.Chapter 1 Getting Started 11 When you plug your Time Capsule into a power outlet, the status light flashes green for one second and then glows amber while your Time Capsule starts up. After your Time Capsule has started up completely, the status light flashes amber until your Time Capsule has been updated with the correct settings. The status light glows solid green after your Time Capsule is properly set up and connected to the Internet or a network. When you connect Ethernet cables to the Ethernet ports, the lights above them glow solid green. The Time Capsule Status Light The following table explains the Time Capsule light sequences and what they indicate. Light Status/description Off Your Time Capsule is unplugged. Solid amber Your Time Capsule is completing its startup sequence. Flashing amber Your Time Capsule can’t establish a connection to the network or the Internet, or is encountering a problem. Make sure you have installed AirPort Utility and use it to get information about what might cause the status light to flash amber. See “If Your Time Capsule Status Light Flashes Amber” on page 27. Solid green Your Time Capsule is on and working properly. If you choose Flash On Activity from the Status Light pop-up menu (in the Base Station pane of AirPort settings in AirPort Utility), the status light may flash green to indicate normal activity. Flashing amber and green There may be a problem starting up. Your Time Capsule will restart and try again.12 Chapter 1 Getting Started What’s Next After you plug in your Time Capsule, use AirPort Utility to set it up to work with your Internet connection, USB printer or hard disk, or an existing network. AirPort Utility is located in the Utilities folder in the Applications folder on a computer using Mac OS X, and in Start > All Programs > AirPort on a computer using Windows XP or Windows Vista. Solid blue Your Time Capsule is ready to allow a wireless client access to the network. See “Allowing Wireless Clients to Access Your Network Without Entering a Password” on page 22. Light Status/description2 13 2 Setting Up Your Time Capsule This chapter provides information and instructions for connecting your Time Capsule to the Internet, and using AirPort Utility to set it up to create or join a wireless network. This chapter provides an overview of connecting your Time Capsule to the Internet, and using the setup assistant in AirPort Utility to set up your network and other features of your Time Capsule. For more information about wireless networking, and for information about the advanced features of AirPort Utility, refer to “Designing AirPort Networks Using AirPort Utility (Mac OS X v10.5 + Windows)” at www.apple.com/support/airport. After you install AirPort Utility from the CD that came with your Time Capsule, you can do most of your network setup and configuration tasks using the setup assistant in AirPort Utility. To set advanced options, choose Manual Setup from the Base Station menu of AirPort Utility. See “Setting Advanced Options” on page 21.14 Chapter 2 Setting Up Your Time Capsule Using Your Time Capsule to Create Your Wireless Network When you set up your Time Capsule to provide network and Internet access, the following computers and devices can access the wireless AirPort network to share files, play games, and use Internet applications such as web browsers and email applications:  Macintosh computers with AirPort or AirPort Extreme Cards  802.11a, 802.11b, 802.11g, and IEEE 802.11n draft specification wireless-equipped computers  Other Wi-Fi devices Computers connected to your Time Capsule using Ethernet can also access the network to share files and connect to the Internet. With Mac OS X v10.5.2 or later you can set up Time Machine to back up all the computers on the network to your Time Capsule. See “Using Time Machine with Your Time Capsule” on page 23 for more information. When you connect a compatible USB printer to your Time Capsule, supported computers on the network (wired and wireless) can print to it.Chapter 2 Setting Up Your Time Capsule 15 Using Time Capsule to create a wireless network To set it up: 1 Connect your DSL or cable modem to your Time Capsule using the Ethernet WAN (<) port. to Internet DSL or cable modem < Internet WAN port Shared printer Time Capsule to USB ports 2.4 or 5 GHz 2.4 GHz 2.4 or 5 GHz16 Chapter 2 Setting Up Your Time Capsule 2 If you plan to share a USB printer on the network, connect it to the Time Capsule USB (d) port or to a USB hub, using a USB cable. 3 Open AirPort Utility (located in the Utilities folder in the Applications folder on a computer using Mac OS X, and in Start > All Programs > AirPort on a computer using Windows), select your Time Capsule, and then click Continue. 4 Follow the onscreen instructions to create a new network. To print from a computer using Mac OS X v10.5: 1 Choose Apple > System Preferences, and then click Print & Fax. 2 Click Add (+) and select your printer from the list. 3 Click the Add button. If your printer isn’t in the list, use the buttons in the toolbar to search for it. To print from a computer using Mac OS X v10.3 or 10.4: 1 Open Printer Setup Utility (located in the Utilities folder in the Applications folder). 2 Select the printer from the list. If the printer isn’t in the list, click Add and choose Bonjour from the pop-up menu, and then select the printer from the list. To print from a computer using Windows XP or Windows Vista: 1 Install Bonjour for Windows from the CD that came with your Time Capsule. 2 Follow the onscreen instructions to connect to your printer. Computers using AirPort or other compatible wireless cards or adapters can connect to the Internet through your Time Capsule. Computers connected to the Time Capsule Ethernet ports can also access the network and connect to the Internet.Chapter 2 Setting Up Your Time Capsule 17 Wireless computers and computers connected to the Ethernet ports can also communicate with each other through your Time Capsule. Using AirPort Utility To set up and configure your Time Capsule, use the setup assistant in AirPort Utility. AirPort Utility is installed on your computer when you install the software from the Time Capsule CD. On a Macintosh computer using Mac OS X v10.4 or later: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder. 2 Select your Time Capsule and click Continue. If you don’t see the Time Capsule you want to configure, click Rescan to scan for available wireless devices, and then select your Time Capsule from the list. 3 Follow the onscreen instructions to set up your Time Capsule and your wireless network. On a computer using Windows XP (with Service Pack 2) or Windows Vista: 1 Open AirPort Utility, located in Start > All Programs > AirPort. 2 Select your Time Capsule and click Continue.18 Chapter 2 Setting Up Your Time Capsule 3 Follow the onscreen instructions to set up your Time Capsule and your wireless network. The AirPort Utility setup assistant asks you questions about the type of network you want to use and the services you want to set up, and helps you enter the appropriate settings. If you’re using your Time Capsule to connect to the Internet, you need a broadband (DSL or cable modem) account with an Internet service provider (ISP), or a connection to the Internet using an existing Ethernet network. If you received specific information from your ISP (such as a static IP address or a DHCP client ID), you may need to enter it in AirPort Utility. Have this information available when you set up your Time Capsule.Chapter 2 Setting Up Your Time Capsule 19 Creating a New Wireless Network You can use the AirPort Utility setup assistant to create a new wireless network. The setup assistant guides you through the steps necessary to name your network, protect your network with a password, and set other options. If you plan to share a USB printer or USB hard disk on your network: 1 Connect the printer or hard disk to the Time Capsule USB (d) port. 2 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Macintosh, or in Start > All Programs > AirPort on a computer using Windows XP. 3 Select your Time Capsule and click Continue. If you don’t see the Time Capsule you want to configure, click Rescan to scan for available wireless devices, and then select your Time Capsule from the list. 4 Follow the onscreen instructions to create a new network. Configuring and Sharing Internet Access If you plan to share your Internet connection with wireless-enabled computers on your network or with computers connected to the Ethernet ports, you need to set up your Time Capsule as an AirPort Base Station. After your Time Capsule is set up, computers access the Internet through the AirPort network. Your Time Capsule connects to the Internet and transmits information to the computers over the wireless network. Before you use AirPort Utility to set up your Time Capsule, connect your DSL or cable modem to the Time Capsule Ethernet WAN (<) port. If you’re connecting your Time Capsule to an Ethernet network that already has Internet access, connect it to the Ethernet network.20 Chapter 2 Setting Up Your Time Capsule Use the AirPort Utility setup assistant to enter your ISP settings and configure how your Time Capsule shares the settings with other computers. 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a computer using Mac OS X, or in Start > All Programs > AirPort on a computer using Windows XP. 2 Select your Time Capsule and click Continue. If you’re making changes to a Time Capsule that has already been set up, you might have to connect to the network it’s created before making changes to the Time Capsule. To choose the wireless network you want to change on a Macintosh, use the AirPort status menu in the menu bar. On a computer using Windows XP, hold the pointer over the wireless connection icon until you see the network name (SSID), and then choose it from the list if there are multiple networks available. 3 Follow the onscreen instructions to configure and share Internet access on your Time Capsule. AirPort Utility provides a quick and easy way to set up your Time Capsule and network. If you want to set additional options for your network, such as restricting access to your network or setting advanced DHCP options, choose Manual Setup from the Base Station menu of AirPort Utility. Chapter 2 Setting Up Your Time Capsule 21 Setting Advanced Options Use AirPort Utility to set up your Time Capsule manually if you want to set advanced Time Capsule options such as advanced security options, closed networks, DHCP lease time, access control, power controls, user accounts, and more. To set advanced options: 1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Macintosh, and in Start > All Programs > AirPort on a computer using Windows XP. 2 If there’s more than one wireless device in the list, select the one you want to configure. If you don’t see the Time Capsule you want to configure, click Rescan to scan for available wireless devices, and then select your Time Capsule from the list. If you’re making changes to a Time Capsule that has already been set up, you might have to connect to the network it’s created before making changes to your Time Capsule. To choose the wireless network you want to change, on a Macintosh use the AirPort status menu in the menu bar. On a computer using Windows XP, hold the pointer over the wireless connection icon until you see the network name (SSID), and then choose it from the list if there are multiple networks available. 3 Choose Manual Setup from the Base Station menu. If you’re prompted for a password, enter it. For more about the manual setup features in AirPort Utility, see “Designing AirPort Networks Using AirPort Utility (Mac OS X v10.5 + Windows)” at www.apple.com/ support/airport.22 Chapter 2 Setting Up Your Time Capsule Allowing Wireless Clients to Access Your Network Without Entering a Password If your network is password-protected using WPA Personal or WPA/WPA2 Personal, you can provide wireless clients access to your network without requiring them to enter the network password. When you allow a client access to your network, the client’s name and wireless MAC address (or AirPort ID) are stored in the access control list of AirPort Utility until you remove the client from the list. You can also provide 24 hours of access, after which time the client will no longer be able to access your network. When you give a client access to your wireless network, the client doesn’t need to enter the network password. To allow a client to access your network without entering the network password: 1 Open AirPort Utility, select your Time Capsule, and then choose Manual Setup from the Base Station menu. Enter the password if necessary. 2 Choose Add Wireless Clients from the Base Station menu. 3 Select how you want the client to access the network:  Select PIN to enter the eight-digit number provided by the client requesting network access.  Select “First attempt” to allow network access to the first client attempting to join the network. While the Time Capsule waits for a client to join the network, the LED glows blue.Chapter 2 Setting Up Your Time Capsule 23 Select “Limit client’s access to 24 hours” if you want to provide just one day of access to your network. If you don’t select this option, the client will have access until you remove the client from the list. Using Time Machine with Your Time Capsule With the Time Machine application in Mac OS X Leopard you can back up everything on your computer, including your photos, music, movies, and documents. After you set up Time Machine, it automatically backs up your computer on a regular basis. If you’re using Mac OS X v10.5.2 or later, the first time you connect to your Time Capsule, Time Machine asks if you’d like to use it to back up your files. Click “Use as Backup Disk,” and Time Machine takes care of the rest. Use the Time Machine pane of System Preferences in Mac OS X Leopard to set up automatic backups, change to a different backup disk, or adjust other settings. To set up or adjust Time Machine on a computer using Mac OS X Leopard: 1 Choose Apple > System Preferences, and then click Time Machine. 2 Slide the switch to ON. 3 Click Change Disk. 4 Choose your Time Capsule and click “Use for Backup.”24 Chapter 2 Setting Up Your Time Capsule Your first backup with Time Capsule and Time Machine could take overnight or longer, depending on how much data you’re backing up. To speed up the initial backup, connect your Time Capsule to your computer using Ethernet. In each subsequent backup, Time Machine backs up only files that have changed since the previous backup, so the backups don’t take as long. Time Capsule is a great wireless backup solution for portable computers. Since the first backup can take some time, plug your portable into a power adapter—this conserves battery power and guarantees that backups won’t be interrupted. Also, for the best wireless performance, place your portable computer in the same room as your Time Capsule. If you shut down your Mac or put it to sleep during a backup, Time Machine stops the backup and then continues from where it left off after your Mac starts up again. For more information about Time Machine, choose Help > Mac Help from the Finder menu on a computer using Mac OS X Leopard, and then type Time Machine in the search field.3 25 3 Tips and Troubleshooting You can quickly solve most problems with your Time Capsule by following the advice in this chapter. If You Can’t Connect to the Internet  Try connecting to the Internet directly from your computer. If you can’t connect, check to make sure your network settings are correct. If they appear to be correct and you still can’t connect, contact your Internet service provider (ISP).  Make sure you’re connecting to the correct wireless network. If You Forgot Your Network Password or Time Capsule Password You can clear the AirPort network password or Time Capsule password by resetting your Time Capsule. To reset the Time Capsule password: 1 Use something pointed (such as a ballpoint pen) to press and hold down the reset button for one second. Important: If you hold the reset button for more than one second, you may lose your network settings.26 Chapter 3 Tips and Troubleshooting 2 Select your AirPort network.  On a Macintosh, use the AirPort status menu in the menu bar to select the network created by your Time Capsule (the network name doesn’t change).  On a computer using Windows XP, hold the pointer over the wireless connection icon until you see your AirPort network name (SSID), and choose it from the list if there are multiple networks available. 3 Open AirPort Utility (in the Utilities folder in the Applications folder on a Macintosh, and in Start > All Programs > AirPort on a computer using Windows XP). 4 Select your Time Capsule, and then choose Manual Setup from the Base Station menu. 5 Click AirPort in the toolbar, and then click Base Station. 6 Enter a new password for your Time Capsule. 7 Click Wireless and choose an encryption method from the Wireless Security pop-up menu to turn on encryption and activate password protection for your AirPort network. If you turn on encryption, enter a new password for your AirPort network. 8 Click Update to restart your Time Capsule and load the new settings. If Your Time Capsule Isn’t Responding Try unplugging it and plugging it back in. If your Time Capsule stops responding completely, you may need to reset it to the factory default settings. Important: Resetting your Time Capsule to factory default settings erases all of the current settings and resets them to the settings that came with your Time Capsule.Chapter 3 Tips and Troubleshooting 27 To return your Time Capsule to the factory settings: m Use something pointed (such as a ballpoint pen) to press down and hold the reset button until the status light flashes quickly (about 5 seconds). Your Time Capsule resets with the following settings:  Your Time Capsule receives its IP address using DHCP.  The network name is reset to Apple Network XXXXXX (where XXXXXX is replaced with the last six digits of the AirPort ID).  The Time Capsule password is reset to public. If your Time Capsule still isn’t responding, try the following: 1 Unplug your Time Capsule. 2 Use something pointed to press and hold down the reset button while you plug in your Time Capsule. If Your Time Capsule Status Light Flashes Amber The Ethernet cable may not be connected properly, your Time Capsule may be out of range of an AirPort network, or there may be a problem with your Internet service provider. If you’re connected to the Internet with a DSL or cable modem, the modem may have lost its connection to the network or the Internet. Even if the modem seems to be working properly, try disconnecting it from its power supply, waiting a few seconds, and then reconnecting it. Make sure your Time Capsule is connected directly to the modem via Ethernet before reconnecting power to the modem.28 Chapter 3 Tips and Troubleshooting For more information about why the light is flashing, open AirPort Utility, select your Time Capsule, and then choose Manual Setup from the Base Station menu. Click Base Station Status to display information about the flashing light. You can also select “Monitor base station for problems” in AirPort preferences. If the base station has a problem, AirPort Utility opens and walks you through solving the problem. If Your Printer Isn’t Responding If you connected a printer to the USB port on your Time Capsule and the computers on the AirPort network can’t print, try the following: 1 Make sure the printer is plugged in and turned on. 2 Make sure the cables are securely connected to the printer and to the Time Capsule USB port. 3 Make sure the printer is selected in the Printer List window on client computers. On a Macintosh using Mac OS X v10.5 or later:  Choose Apple > System Preferences, and then click Print & Fax.  Click Add (+) and select your printer in the list, and then click Add (+). On a Macintosh using Mac OS X v10.2.7 or later:  Open Printer Setup Utility, located in the Utilities folder in the Applications folder.  If the printer isn’t in the list, click Add.  Choose Bonjour from the pop-up menu, select the printer and click Add (+).Chapter 3 Tips and Troubleshooting 29 On a computer using Windows XP:  Open “Printers and Faxes” from the Start menu.  Select the printer. If the printer isn’t in the list, click Add Printer and then follow the onscreen instructions. 4 Turn off the printer, wait a few seconds, and then turn it back on. Updating AirPort Software Apple periodically updates AirPort software. It is recommended that you update your Time Capsule to use the latest software. You can select “Check for updates when opening AirPort Utility,” or “Check for updates” in AirPort preferences. If you select “Check for updates,” choose an increment of time, such as weekly, from the pop-up menu to automatically check for updates. Time Capsule Placement Considerations The following recommendations can help your Time Capsule achieve the best wireless range and network coverage.  Place your Time Capsule in an open area where there are few obstructions, such as large pieces of furniture or walls. Try to place it away from metallic surfaces.  If you place your Time Capsule behind furniture, keep at least an inch of space between the Time Capsule and the edge of the furniture.  Avoid placing your Time Capsule in areas surrounded by metal surfaces on three or more sides. 30 Chapter 3 Tips and Troubleshooting  If you place your Time Capsule in an entertainment center with your stereo equipment, avoid surrounding your Time Capsule with audio, video, or power cables. Place your Time Capsule so that the cables are to one side. Maintain as much space as possible between your Time Capsule and the cables.  Try to place your Time Capsule at least 25 feet (7.6 meters) from any microwave oven, 2.4 or 5 gigahertz (GHz) cordless phone, and other sources of interference.  Do not place other objects (books, papers, small pets, etc.) on top of the Time Capsule. It may interfere with Time Capsule cooling. Items That Can Cause Interference with AirPort The farther away the interference source, the less likely it is to cause a problem. The following can interfere with AirPort communication:  Microwave ovens  Direct Satellite Service (DSS) radio frequency leakage  The original coaxial cable that came with certain types of satellite dishes. Contact the device manufacturer and obtain newer cables.  Certain electrical devices such as power lines, electrical railroad tracks, and power stations  Cordless telephones that operate in the 2.4 or 5 GHz range. If you have problems with your phone or AirPort communication, change the channel your base station or Time Capsule uses, or change the channel your phone uses.  Nearby base stations using adjacent channels. For example, if base station A is set to channel 1, base station B should be set to channel 6 or 11.4 31 4 Learning More, Service, and Support You can find more information about using your Time Capsule on the web and in onscreen help. Online Resources For the latest information about the Time Capsule, go to www.apple.com/airport. To register your Time Capsule (if you didn’t do it when you installed the software on the Time Capsule CD), go to www.apple.com/register. For AirPort support information, forums with product-specific information and feedback, and the latest Apple software downloads, go to www.apple.com/support/ airport. For support outside of the United States, go to www.apple.com/support, and then choose your country.32 Chapter 4 Learning More, Service, and Support Onscreen Help To learn more about using AirPort Utility with your Time Capsule, open AirPort Utility and choose Help > AirPort Utility Help. Obtaining Warranty Service If your Time Capsule appears to be damaged or doesn’t function properly, please follow the advice in this booklet, the onscreen help, and the online resources. If your Time Capsule still doesn’t function, go to www.apple.com/support for information about getting warranty service. Finding the Serial Number of Your Time Capsule The serial number is printed on the bottom of your Time Capsule.33 Appendix Time Capsule Specifications and Safety Guidelines Time Capsule Specifications  Frequency Band: 2.4 and 5 GHz  Radio Output Power: Up to 23 dBm (nominal)  Standards: 802.11 DSSS 1 and 2 Mbps standard, 802.11a, 802.11b, 802.11g specifications, and a draft 802.11n specification Interfaces  1 RJ-45 10/100/1000Base-T Gigabit Ethernet WAN (<)  3 RJ-45 10/100/1000Base-T Gigabit Ethernet LAN (G)  Universal Serial Bus (USB d) 2.0  802.11 a/b/g/n AirPort Extreme wireless Environmental Specifications  Operating Temperature: 32° F to 95° F (0° C to 35° C)  Storage Temperature: –13° F to 140° F (–25° C to 60° C)  Relative Humidity (Operational): 20% to 80% relative humidity  Relative Humidity (Storage): 10% to 90% relative humidity, noncondensing34 Appendix Time Capsule Specifications and Safety Guidelines Size and Weight  Length: 7.75 inches (197.0 mm)  Width: 7.75 inches (197.0 mm)  Height: 1.43 inches (36.33 mm)  Weight: 3.5 pounds (1.6 kilograms) Hardware Media Access Control (MAC) Addresses The Time Capsule has three hardware addresses printed on the bottom of the case:  AirPort ID: The two addresses used to identify the Time Capsule on a wireless network.  Ethernet ID: You may need to provide this address to your ISP to connect your Time Capsule to the Internet. Using Your Time Capsule Safely  The only way to shut off power completely to your Time Capsule is to disconnect it from the power source.  When connecting or disconnecting your Time Capsule, always hold the plug by its sides. Keep fingers away from the metal part of the plug.  Your Time Capsule should not be opened for any reason, even when it’s unplugged. If your Time Capsule needs service, see “Learning More, Service, and Support” on page 31.  Never force a connector into a port. If the connector and port don’t join with reasonable ease, they probably don’t match. Make sure that the connector matches the port and that you’ve positioned the connector correctly in relation to the port.Appendix Time Capsule Specifications and Safety Guidelines 35 About Operating and Storage Temperatures  When you’re using your Time Capsule, it is normal for the case to get warm. The Time Capsule case functions as a cooling surface that transfers heat from inside the unit to the cooler air outside. Avoid Wet Locations  Keep your Time Capsule away from sources of liquid, such as drinks, washbasins, bathtubs, shower stalls, and so on.  Protect your Time Capsule from direct sunlight and rain or other moisture.  Take care not to spill any food or liquid on your Time Capsule. If you do, unplug it before cleaning up the spill.  Do not use your Time Capsule outdoors. The Time Capsule is an indoor product. Do Not Make Repairs Yourself About Handling Your Time Capsule may be damaged by improper storage or handling. Be careful not to drop your Time Capsule when transporting it. WARNING: To reduce the chance of shock or injury, do not use your Time Capsule in or near water or wet locations. WARNING: Do not attempt to open your Time Capsule or disassemble it. You run the risk of electric shock and voiding the limited warranty. No user-serviceable parts are inside.36 Regulatory Compliance Information Wireless Radio Use This device is restricted to indoor use due to its operation in the 5.15 to 5.25 GHz frequency range to reduce the potential for harmful interference to cochannel Mobile Satellite systems. Cet appareil doit être utilisé à l’intérieur. Exposure to Radio Frequency Energy The radiated output power of this device is well below the FCC and EU radio frequency exposure limits. However, this device should be operated with a minimum distance of at least 20 cm between its antennas and a person’s body and the antennas used with this transmitter must not be colocated or operated in conjunction with any other antenna or transmitter subject to the conditions of the FCC Grant. FCC Declaration of Conformity This device complies with part 15 of the FCC rules. Operation is subject to the following two conditions: (1) This device may not cause harmful interference, and (2) this device must accept any interference received, including interference that may cause undesired operation. See instructions if interference to radio or television reception is suspected. Radio and Television Interference This computer equipment generates, uses, and can radiate radio-frequency energy. If it is not installed and used properly—that is, in strict accordance with Apple’s instructions—it may cause interference with radio and television reception. This equipment has been tested and found to comply with the limits for a Class B digital device in accordance with the specifications in Part 15 of FCC rules. These specifications are designed to provide reasonable protection against such interference in a residential installation. However, there is no guarantee that interference will not occur in a particular installation. You can determine whether your computer system is causing interference by turning it off. If the interference stops, it was probably caused by the computer or one of the peripheral devices. If your computer system does cause interference to radio or television reception, try to correct the interference by using one or more of the following measures:  Turn the television or radio antenna until the interference stops.  Move the computer to one side or the other of the television or radio.  Move the computer farther away from the television or radio.  Plug the computer into an outlet that is on a different circuit from the television or radio. (That is, make certain the computer and the television or radio are on circuits controlled by different circuit breakers or fuses.) If necessary, consult an Apple Authorized Service Provider or Apple. See the service and support information that came with your Apple product. Or, consult an experienced radio/television technician for additional suggestions. Important: Changes or modifications to this product not authorized by Apple Inc. could void the EMC compliance and negate your authority to operate the product.37 This product was tested for FCC compliance under conditions that included the use of Apple peripheral devices and Apple shielded cables and connectors between system components. It is important that you use Apple peripheral devices and shielded cables and connectors between system components to reduce the possibility of causing interference to radios, television sets, and other electronic devices. You can obtain Apple peripheral devices and the proper shielded cables and connectors through an Apple-authorized dealer. For non-Apple peripheral devices, contact the manufacturer or dealer for assistance. Responsible party (contact for FCC matters only) Apple Inc., Corporate Compliance, 1 Infinite Loop M/S 26-A, Cupertino, CA 95014-2084 Industry Canada Statement This Class B device meets all requirements of the Canadian interference-causing equipment regulations. Cet appareil numérique de la Class B respecte toutes les exigences du Règlement sur le matériel brouilleur du Canada. VCCI Class B Statement Europe—EU Declaration of Conformity For more information, see www.apple.com/euro/ compliance. European Union — Disposal Information This symbol means that according to local laws and regulations your product should be disposed of separately from household waste. When this product reaches its end of life, take it to a collection point designated by local authorities. Some collection points accept products for free. The separate collection and recycling of your product at the time of disposal will help conserve natural resources and ensure that it is recycled in a manner that protects human health and the environment. Disposal and Recycling Information This product has an internal battery. Please dispose of it according to your local environmental laws and guidelines. For information about Apple’s recycling program, go to www.apple.com/environment. California: The coin cell battery in your product contains perchlorates. Special handling and disposal may apply. Refer to www.dtsc.ca.gov/hazardouswaste/ perchlorate. Deutschland: Dieses Gerät enthält Batterien. Bitte nicht in den Hausmüll werfen. Entsorgen Sie dieses Gerätes am Ende seines Lebenszyklus entsprechend der maßgeblichen gesetzlichen Regelungen. Nederlands: Gebruikte batterijen kunnen worden ingeleverd bij de chemokar of in een speciale batterijcontainer voor klein chemisch afval (kca) worden gedeponeerd.38 Taiwan: Singapore Wireless Certification Taiwan Warning Statements Korea Warning Statements © 2009 Apple Inc. All rights reserved. Apple, the Apple logo, AirPort, AirPort Express, AirPort Extreme, Apple TV, Bonjour, iPod, Leopard, Macintosh, Mac OS, and Time Capsule are trademarks of Apple Inc., registered in the U.S. and other countries. Finder, iPhone, and Time Machine are trademarks of Apple Inc. Other product and company names mentioned herein may be trademarks of their respective companies.www.apple.com/airport www.apple.com/support/airport 034-4704-A Printed in XXXX Code Signing GuideContents About Code Signing 4 At a Glance 5 Prerequisites 5 See Also 5 Code Signing Overview 6 The Benefits Of Signing Code 6 Digital Signatures and Signed Code 8 Code Requirements 8 The Role of Trust in Code Signing 9 Code Signing Tasks 11 Obtaining a Signing Identity 11 Adding an Info.plist to Single-File Tools 15 Signing Your Code 17 What to Sign 17 When to Sign 18 Using the codesign Command 18 Using the spctl Tool to Test Code Signing 21 Shipping and Updating Your Product 23 Code Signing Requirement Language 25 Language Syntax 25 Evaluation of Requirements 26 Constants 26 String Constants 26 Integer Constants 27 Hash Constants 27 Variables 27 Logical Operators 27 Comparison Operations 28 Equality 28 Inequality 29 Existence 29 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 2Constraints 29 Identifier 29 Info 30 Certificate 30 Trusted 32 Entitlement 33 Code Directory Hash 33 Requirement Sets 34 Document Revision History 36 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 3 ContentsCode signing is a security technology, used in OS X, that allows you to certify that an app was created by you. Once an app is signed, the system can detect any change to the app—whether the change is introduced accidentally or by malicious code. Hash Message digest Digital signature Encrypt Signer’s certificate Code-signed data Signer’s private key 10101100100 10111100001 Data Duis autem vel eum vulputate velit esse molestie consequat, vel illum dolore. 00/00/00 Lorem Ipsum Lorem Ipsum Dolor Lorem Ipsum Dolor Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. Users appreciate code signing. After installing a new version of a code-signed app, a user is not bothered with alerts asking again for permission to access the keychain or similar resources. As long as the new version uses the same digital signature, OS X can treat the new app exactly as it treated the previous one. Other OS X security features, such as App Sandbox and parental controls, also depend on code signing. In most cases, you can rely on Xcode’s automatic code signing (described in Tools Workflow Guide for Mac ), which requires only that you specify a code signing identity in the build settingsfor your project. This document is for readers who must go beyond automatic code signing—perhaps to troubleshoot an unusual problem, or to incorporate the codesign(1) tool into a build system. 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 4 About Code SigningAt a Glance The elements of code signing include code signatures, code signing identities, code signing certificates, and security trust policies. Be sure to understand these concepts if you need to perform code signing outside of Xcode. Relevant chapter: “Code Signing Overview” (page 6) Before you can sign code, you must obtain or create a code signing identity. You then sign your code and prepare it for distribution. Relevant chapter: “Code Signing Tasks” (page 11) To specify recommended criteria for verifiers to use when evaluating your app’s code signature, you use a requirements language specific to the codesign(1) and csreq(1) commands. You then save your criteria to a binary file as part of your Xcode project. Relevant chapter: “Code Signing Requirement Language” (page 25) Prerequisites Read Security Overview to understand the place of code signing in the OS X security picture. See Also For descriptions of the command-line toolsfor performing code signing,see the codesign(1) and csreq(1) man pages. About Code Signing At a Glance 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 5Code signing is a security technique that can be used to ensure code integrity, to determine who developed a piece of code, and to determine the purposes for which a developer intended a piece of code to be used. Although the code signing system performs policy checks based on a code signature, it is up to the caller to make policy decisions based on the results of those checks. When it is the operating system that makes the policy checks, whether your code will be allowed to run in a given situation depends on whether you signed the code and on the requirements you included in the signature. This chapter describes the benefits of signing code and introduces some of the basic concepts you need to understand in order to carry out the code signing process. Before you read this chapter, you should be familiar with the concepts described in Security Overview. The Benefits Of Signing Code When a piece of code has been signed, it is possible to determine reliably whether the code has been modified by someone other than the signer. The system can detect such alternation whether it was intentional (by a malicious attacker, for example) or accidental (as when a file gets corrupted). In addition, through signing, a developer can state that an app update is valid and should be considered by the system as the same app as the previous version. For example,suppose a user grantsthe SurfWriter app permission to access a keychain item. Each time SurfWriter attempts to access that item, the system must determine whether it is indeed the same app requesting access. If the app is signed, the system can identify the app with certainty. If the developer updates the app and signs the new version with the same unique identifier, the system recognizes the update as the same app and gives it access without requesting verification from the user. On the other hand, if SurfWriter is corrupted or hacked, the signature no longer matches the previous signature; the system detects the change and refuses access to the keychain item. Similarly, if you use Parental Controls to prevent your child from running a specific game, and that game has been signed by its manufacturer, your child cannot circumvent the control by renaming or moving files. Parental Controls uses the signature to unambiguously identify the game regardless of its name, location, or version number. All sorts of code can be signed, including tools, applications, scripts, libraries, plug-ins, and other “code-like” data. 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 6 Code Signing OverviewCode signing has three distinct purposes. It can be used to: ● ensure that a piece of code has not been altered ● identify code as coming from a specific source (a developer or signer) ● determine whether code is trustworthy for a specific purpose (for example, to access a keychain item). To enable signed code to fulfill these purposes, a code signature consists of three parts: ● A seal, which is a collection of checksums or hashes of the various parts of the code, such as the identifier, the Info.plist, the main executable, the resource files, and so on. The seal can be used to detect alterations to the code and to the app identifier. ● A digital signature, which signs the seal to guarantee its integrity. The signature includes information that can be used to determine who signed the code and whether the signature is valid. ● A unique identifier, which can be used to identify the code or to determine to which groups or categories the code belongs. This identifier can be derived from the contents of the Info.plist for the app, or can be provided explicitly by the signer. For more discussion of digital signatures, see the following section, “Digital Signatures and Signed Code.” To learn more about how a code signature is used to determine the signed code’s trustworthiness for a specific purpose, see “Code Requirements” (page 8). Note that code signing deals primarily with running code. Although it can be used to ensure the integrity of stored code (on disk, for example), that's a secondary use. To fully appreciate the uses of code signing, you should be aware of some things that signing cannot do: ● It can’t guarantee that a piece of code is free of security vulnerabilities. ● It can’t guarantee that an app will not load unsafe or altered code—such as untrusted plug-ins—during execution. ● It is not a digital rights management (DRM) or copy protection technology. Although the system could determine that a copy of your app had not been properly signed by you, or that its copy protection had been hacked, thus making the signature invalid, there is nothing to prevent a user from running the app anyway. Code Signing Overview The Benefits Of Signing Code 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 7Digital Signatures and Signed Code As explained in Security Overview, a digital signature uses public key cryptography to ensure data integrity. Like a signature written with ink on paper, a digital signature can be used to identify and authenticate the signer. However, a digital signature is more difficult to forge, and goes one step further: it can ensure that the signed data has not been altered. This is somewhat like designing a paper check or money order in such a way that if someone alters the written amount of money, a watermark with the text “Invalid” becomes visible on the paper. To create a digitalsignature, the signing software computes a special type of checksum called a hash (or digest) based on a piece of data or code and encrypts that hash with the signer’s private key. This encrypted hash is called a signature. To verify that signature, the verifying software computes a hash of the data or code. It then uses the signer’s public key to decrypt the signature, thus obtaining the original hash as computed by the signer. If the two hashes match, the data has not been modified since it was signed by someone in possession of the signer’s private key. Signed code contains several digital signatures: ● If the code is universal, the object code for each slice (architecture) is signed separately. This signature is stored within the binary file itself. ● Various components of the application bundle (such as the Info.plist file, if there is one) are also signed. These signatures are stored in a file called _CodeSignature/CodeResources within the bundle. Code Requirements It is up to the system or program that is launching or loading signed code to decide whether to verify the signature and, if it does, to determine how to evaluate the results of that verification. The criteria used to evaluate a code signature are called code requirements. The signer can specify requirements when signing the code; such requirements are referred to as internal requirements. A verifier can read any internal requirements before deciding how to treat signed code. However, it is up to the verifier to decide what requirements to use. For example, Safari could require a plug-in to be signed by Apple in order to be loaded, regardless of whether that plug-in’s signature included internal requirements. One major purpose of code signatures is to allow the verifier to identify the code (such as a program, plug-in, or script) to determine whether it is the same code the verifier has seen before. The criteria used to make this determination are referred to asthe code’s designated requirement. For example, the designated requirement for Apple Mail might be "was signed by Apple and the identifier is com.apple.Mail". Code Signing Overview Digital Signatures and Signed Code 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 8To see how this works in practice, assume the user has granted permission to the Apple Mail application to access a keychain item. The keychain uses Mail’s designated requirement to identify it: the keychain records the identifier (com.apple.Mail) and the signer of the application (Apple) to identify the program allowed to access the keychain item. Whenever Mail attempts to access this keychain item, the keychain looks at Mail’s signature to make sure that the program has not been corrupted, that the identifier is com.apple.Mail, and that the program wassigned by Apple. If everything checks out, the keychain gives Mail accessto the keychain item. When Apple issues a new version of Mail, the new version includes a signature, signed by Apple, that identifies the application as com.apple.Mail. Therefore, when the user installs the new version of Mail and it attempts to access the keychain item, the keychain recognizes the updated version as the same program and does not prompt the user for verification. Architecturally, a code requirement is a script, written in a dedicated language, that describes conditions (restrictions) the code mustsatisfy to be acceptable forsome purpose. It is up to you whether to specify internal requirements when you sign code. The program identifier or the entire designated requirement can be specified by the signer, or can be inferred by the codesign tool at the time of signing. In the absence of an explicitly specified designated requirement, the codesign utility typically builds a designated requirement from the name of the program found in its Info.plist file and the chain of signatures securing the code signature. Note that validation of signed code against a set of requirements is performed only when the system or some other program needs to determine whether it is safe to trust that code. For example, unsigned code injected into an application through a buffer overflow can still execute because it was not part of the application at launch time. Similarly, an app with an invalid code identifier may still run (depending on policy), but does not get automatic access to keychain items created by previous versions of the app. The Role of Trust in Code Signing Trust is determined by policy. A security trust policy determines whether a particular identity should be accepted for allowing something, such as access to a resource or service. Various parts of OS X have different policies, and make this determination differently. For example, a specialized client application might include a set of root certificatesthat it trusts when communicating with a specific set ofservers. However, these root certificates would not be trusted if those same servers were accessed using a web browser. In much the same way, many parts of OS X (the OS X keychain and parental controls, for example) do not care what entity signed an application; they care only whether the signer has changed since the last time the signature was checked. They use the code signature’s designated requirement for this purpose. Code Signing Overview The Role of Trust in Code Signing 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 9Other parts of OS X constrain acceptable signatures to only those drawn from certificate authorities (root certificates) that are trusted anchors on the system performing the validation. For those checks, the nature of the identity used matters. The Application Firewall is one example of this type of policy. Self-signed identities and self-created certificate authorities do not work for these purposes unless the user has explicitly told the operating system to trust the certificates. You can modify the code signing polices of OS X with the spctl(8) command. Code Signing Overview The Role of Trust in Code Signing 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 10This chapter gives procedures and examplesfor the code signing process. It covers what you need to do before you begin to sign code, how to sign code, and how to ship the code you signed. Obtaining a Signing Identity To sign code, you need a code signing identity, which is a private key plus a digital certificate. The digital certificate must have a usage extension that enables it to be used for signing and it must contain the public key that corresponds to the private key. You can use more than one signing identity, each for its own purpose, such as one to be used for beta seeds and one for final, released products. However, most organizations use only one identity. You can obtain two types of certificates from Apple using the developer portal: Developer ID certificates (for public distribution) and distribution certificates (for submitting to the Mac App Store). To learn more about this, read Tools Workflow Guide for Mac . Note: Apple uses the industry-standard form and format of code signing certificates. Therefore, if your company already has a third-party signing identity that you use to sign code on other systems, you can use it with the OS X codesign command. Similarly, if your company is a certificate issuing authority, contact your IT department to find out how to get a signing certificate issued by your company. If you do not have an existing identity, you should first create one using the Certificate Assistant, which is provided as part of the Keychain Access application. This tool creates a public key, puts it into your keychain, and optionally can produce a certificate signing request that you can then send to Apple (or another certificate authority). The certificate authority then sends you a certificate that, in combination with your private key, completes your digital identity. To import a signing certificate with Keychain Access 1. In Keychain Access (available in /Applications/Utilities), choose File > Import Items. 2. Choose a destination keychain for the identity. 3. Choose the certificate file. 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 11 Code Signing Tasks4. Click Open. Note: If the original private key is not already in your keychain (for example, if you are moving from one development machine to another), you must also import the private key in the same way. Before you obtain a code signing identity and sign your code, consider the following points: ● Do not ship applications signed by self-signed certificates. A self-signed certificate created with the Certificate Assistant is not recognized by users’ operating systems as a valid certificate for any purpose other than validating the designated requirement of your signed code. Because a self-signed certificate has not been signed by a recognized root certificate authority, the user can only verify that two versions of your application came from the same source; they cannot verify that your company is the true source of the code. For more information about root authorities, see “Security Concepts”. ● Depending on your company’s internal policies, you might have to involve your company’s Build and Integration, Legal, and Marketing departments in decisions about what sort of signing identity to use and how to obtain it. You should start this process well in advance of the time you need to actually sign the code for distribution to customers. ● Any signed version of your code that gets into the hands of users will appear to have been endorsed by your company for use. Therefore, you might not want to use your “final” signing identity to sign code that is still in development. ● A signing identity, no matter how obtained, is completely compromised if it is ever out of the physical control of whoever is authorized to sign the code. That means that the signing identity’s private key must never, under any circumstances, be given to end users, and should be restricted to one or a small number of trusted persons within your company. Before obtaining a signing identity and proceeding to sign code, you must determine who within your company will possess the identity, who can use it, and how it will be kept safe. For example, if the identity must be used by more than one person, you can keep it in the keychain of a secure computer and give the password of the keychain only to authorized users, or you can put the identity on a smart card to which only authorized users have the PIN. ● A self-signed certificate created by the Certificate Assistant is adequate for internal testing and development, regardless of what procedures you put in place to sign released products. To use the Certificate Assistant to create a self-signed signing identity 1. Open Applications > Utilities > Keychain Access. Code Signing Tasks Obtaining a Signing Identity 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 122. From the Keychain Access menu, choose Certificate Assistant > Create a Certificate. 3. Fill in a name for the certificate. This name appears in the Keychain Access utility as the name of the certificate. 4. Choose Self Signed Root from the Type popup menu. Code Signing Tasks Obtaining a Signing Identity 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 135. Check the Let me override defaults checkbox. Click Continue. 6. Specify a serial number for the certificate. Any number will do as long as you have no other certificate with the same name and serial number. Code Signing Tasks Obtaining a Signing Identity 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 147. Choose Code Signing from the Certificate Type popup menu. Click Continue. 8. Fill in the information for the certificate. Click Continue. 9. Accept the defaults for the rest of the dialogs. Adding an Info.plist to Single-File Tools As discussed in “Code Requirements” (page 8), the system often uses the Info.plist file of an application bundle to determine the code’s designated requirement. Although single-file tools don’t normally have an Info.plist, you can add one. To do so, use the following procedure: 1. Add an Info.plist file to your project (including adding it to your source control). 2. Make sure the Info.plist file has the following keys: ● CFBundleIdentifier ● CFBundleName Code Signing Tasks Adding an Info.plist to Single-File Tools 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 153. The value for CFBundleIdentifier is used asthe default unique name of your program for Code Signing purposes. Because the CFBundleIdentifier value is also used when your application accessesresources in the application bundle, it may sometimes be necessary to use a non-unique CFBundleIdentifier value for a helper. If you do this, you must provide a different, unique identifier for code signing purposes by passing the -i or --identifier flag to the codesign command. The identifier used for signing must be globally unique. To ensure uniqueness, you should include your company’s name in the value. The usual form for this identifier is a hierarchical name in reverse DNS notation,starting with the top level domain, followed by the company name, followed by the organization within the company, and ending with the product name. For example, the CFBundleIdentifier value for the codesign command is com.apple.security.codesign. 4. The value for CFBundleName shows up in system dialogs asthe name of your program,so itshould match your marketing name for the product. 5. Add the following arguments to your linker flags: -sectcreate __TEXT __info_plist Info.plist_path where Info.plist_path is the complete path of the Info.plist file in your project. In Xcode, for example, you would add these linker flags to the OTHER_LDFLAGS build variable (Other Linker Flags in the target’s build rules). For example, here are the contents of the Info.plist file for the codesign command: CFBundleDevelopmentRegion English CFBundleIdentifier com.apple.security.codesign CFBundleInfoDictionaryVersion 6.0 CFBundleName codesign CFBundleVersion 0.3 Code Signing Tasks Adding an Info.plist to Single-File Tools 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 16Signing Your Code You use the codesign command to sign your code. This section discusses what to sign and gives some examples of the use of codesign. See the codesign(1) manual page for a complete description of its use. What to Sign You should sign every executable in your product, including applications, tools, hidden helper tools, utilities and so forth. Signing an application bundle covers its resources, but not its subcomponents such as tools and sub-bundles. Each of these must be signed independently. If your application consists of a big UI part with one or more little helper tools that try to present a single face to the user, you can make them indistinguishable to code signing by giving them all the exact same code signing identifier. (You can do that by making sure that they all have the same CFBundleIdentifier value in their Info.plist, or by using the -i option in the codesign command, to assign the same identifier.) In that case, all your program components have access to the same keychain items and validate as the same program. Do this only if the programs involved are truly meant to form a single entity, with no distinctions made. A universal binary (bundle or tool) automatically has individual signatures applied to each architecture component. These are independent, and usually only the native architecture on the end user'ssystem is verified. In the case of installer packages (.pkg and .mpkg bundles), everything is implicitly signed: The CPIO archive containing the payload, the CPIO archive containing install scripts, and the bill of materials (BOM) each have a hash recorded in the XAR header, and that header in turn is signed. Therefore, if you modify an install script (for example) after the package has been signed, the signature will be invalid. You may also want to sign your plug-ins and libraries. Although this is not currently required, it will be in the future, and there is no disadvantage to having signatures on these components. Important: When code signing a framework, you must sign a particular version of the framework, not the framework as a whole. For example: codesign -s my-signing-identity ../MyCustomFramework/Versions/A Depending on the situation, codesign may add to your Mach-O executable file, add extended attributes to it, or create new files in your bundle's Contents directory. None of your other files is modified. Code Signing Tasks Signing Your Code 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 17When to Sign You can run codesign at any time on any system running OS X v10.5 or later, provided you have access to the signing identity. You can run it from a shell script phase in Xcode if you like, or as a step in your Makefile scripts, or anywhere else you find suitable. Signing is typically done as part of the product mastering process, after quality assurance work has been done. Avoid signing pre-final copies of your product so that no one can mistake a leaked or accidentally released incomplete version of your product for the real thing. Your final signing must be done after you are done building your product, including any post-processing and assembly of bundle resources. Code signing detects any change to your program after signing, so if you make any changes at all after signing, your code will be rejected when an attempt is made to verify it. Sign your code before you package the product for delivery. Because each architecture component is signed independently, it is all right to perform universal-binary operations (such as running the lipo command) on signed programs. The result will still be validly signed as long as you make no other changes. Using the codesign Command The codesign command is fully described in the codesign(1) manual page. This section provides some examples of common uses of the command. Note that your signing identity must be in a keychain for these commands to work. Signing Code To sign the code located at , using the signing identity , use the following command: codesign -s … The value may be a bundle folder or a specific code binary. See “What to Sign” (page 17) for more details. The identity can be named with any (case sensitive) substring of the certificate's common name attribute, as long as the substring is unique throughout your keychains. (Signing identities are discussed in “Obtaining a Signing Identity” (page 11).) As is typical of Unix-style commands, this command gives no confirmation of success. To get some feedback, include the -v option: codesign -s -v … Code Signing Tasks Signing Your Code 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 18Use the -r option to specify an internal requirement. With this option you can specify a text file containing the requirements, a precompiled requirements binary, or the actual requirement text prefixed with an equal sign (=). For example, to add an internal requirement that all libraries be signed by Apple, you could use the following option: -r="library => anchor apple" The code requirement language is described in “Code Signing Requirement Language” (page 25). If you have built your own certificate hierarchy (perhaps using Certificate Assistant—see “Obtaining a Signing Identity” (page 11)), and want to use your certificate’s anchor to form a designated requirement for your program, you could use the following command: codesign -s signing-identity -r="designated => anchor /my/anchor/cert and identifier com.mycorp.myprog" Note that the requirement source language accepts either an SHA1 hash of a certificate (for example H"abcd....") or a path to the DER encoded certificate in a file. It does not currently accept a reference to the certificate in a keychain, so you have to export the certificate before executing this command. You can also use the csreq command to write the requirements out to a file, and then use the path to that file as the input value for the -r option in the codesign command. See the manual page for csreq(1) for more information on that command. Here are some other samples of requirements: ● anchor apple –the code is signed by Apple ● anchor trusted –the anchor is trusted (for code signing) by the system ● certificate leaf = /path/to/certificate –the leaf (signing) certificate is the one specified ● certificate leaf = /path/to/certificate and identifier "com.mycorp.myprog" –the leaf certificate and program identifier are as specified ● info[mykey] = myvalue – the Info.plist key mykey exists and has the value myvalue Except for the explicit anchor trusted requirement, the system does not consult its trust settings database when verifying a code requirement. Therefore, as long as you don’t add this designated requirement to your code signature, the anchor certificate you use for signing your code does not have to be introduced to the user’s system for validation to succeed. Code Signing Tasks Signing Your Code 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 19Adding Entitlements for Sandboxing If you want to enable App Sandbox for an application, you must add an entitlement property list during the signing process. To do this, add the --entitlements flag and an appropriate property list. For example: codesign --entitlements /path/to/entitlements.plist -s … For a list of entitlement keys that can appear in the entitlement property list, see Entitlement Key Reference . Verifying Code To verify the signature on a signed binary, use the -v option with no other options: codesign -v … This checks that the code binaries at are actually signed, that the signature is valid, that all the sealed components are unaltered, and that the whole thing passes some basic consistency checks. It does not by default check that the code satisfies any requirements except its own designated requirement. To check a particular requirement, use the -R option. For example, to check that the Apple Mail application is identified as Mail,signed by Apple, and secured with Apple’srootsigning certificate, you could use the following command: codesign -v -R="identifier com.apple.mail and anchor apple" /Applications/Mail.app Note that, unlike the -r option, the -R option takes only a single requirement rather than a requirements collection (no => tags). Add one or more additional -v options to get details on the validation process. If you pass a number rather than a path to the verify option, codesign takes the number to be the process ID (pid) of a running process, and performs dynamic validation instead. Getting Information About Code Signatures To get information about a code signature, use the -d option. For example, to output the code signature’s internal requirements to standard out, use the following command: codesign -d -r code-path Note that this option does not verify the signature. Code Signing Tasks Signing Your Code 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 20Using the spctl Tool to Test Code Signing The spctl(8) tool can be used to test your code signatures against various system policies that the user may set. The basic syntax for code signing assessment is shown below: # Assess an application or tool spctl --assess --type execute myTool # Assess an installer package spctl --assess --type install myInstallerPackage.pkg If your application or package signature is valid, these tools exit silently with an exit status of 0. (Type echo $? to display the exit status of the last command.) If the signature is invalid, these tools print an error message and exit with a nonzero exit status. For more detailed information about why the assessment failed, you can add the --verbose flag. For example: spctl --assess --verbose=4 /bin/ls This prints the following output: /bin/ls: accepted source=Apple System To see everything the system has to say about an assessment, pass the --raw option. With this flag, the spctl tool prints a detailed assessment as a property list. To whitelist a program (exactly as if the UI did it), type: spctl --add --label mytest /some/program The --label is an optional tag that you can add to your own rules. This tag allows you to remove the rule easily by typing: spctl --remove --label mytest Note that this removes all rules that match the label, which means that it is a handy way to clean up after testing. You can also temporarily suspend your rules by typing: Code Signing Tasks Using the spctl Tool to Test Code Signing 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 21spctl --disable --label mytest and reenable them later by typing: spctl --enable --label mytest To see a list of the current assessment rules, use the --list flag. For example: spctl --list --type execute The resulting list of rules might look like this: 3[Apple System] P0 allow execute anchor apple 4[Mac App Store] P0 allow execute anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.9] exists 5[Developer ID] P0 allow execute anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists 7[UNLABELED] P0 allow execute [/var/tmp/firefly/RUN-FIREFLY-JOBS/test1.app] cdhash H"f34c03450da53c07ac69282089b68723327f278a" 8[UNLABELED] P0 allow execute [/var/tmp/firefly/RUN-FIREFLY-JOBS/test1.app] identifier "org.tpatko.Run-Firefly-Job-X-Cores" and certificate root = H"5056a3983e3b7f44e17e3db8e483b35b6745b236" Notice that the list above includes a number of predefined rules that describe the handling of certain classes of code. For example, rule 5 captures all applicationssigned by a Developer ID. You can disable those applications by typing: spctl --disable --label "Developer ID" This command tells the system to no longer allow execution of any Developer ID-signed applications that the user has not previously run. This is exactly what happens when you use the preference UI to switch to "Mac App Store only". Each rule in the list has a unique number that can be used to address it. For example, if you type: Code Signing Tasks Using the spctl Tool to Test Code Signing 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 22spctl --list --label "Developer ID" you might get a list of rules that looks like this: 5[Developer ID] P0 allow execute anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists 6[Developer ID] P0 allow install anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.14] exists Notice that there are separate rules for execution (5) and installation (6), and you can enable and disable them separately. For example, to enable installation of new applications signed with a Developer ID, you can type: spctl --enable --rule 6 Finally, spctl allows you to enable or disable the security assessment policy subsystem. By default, assessment isturned off, which meansthat missing or invalid code signatures do not prevent an application from launching. However, it is strongly recommended that you test your application with assessment enabled to ensure that your application works correctly. To enable or disable assessment, issue one of the following commands. sudo spctl --master-enable # enables assessment sudo spctl --master-disable # disables assessment spctl --status # shows whether assessment is enabled For more information, see the manual page for spctl(8). Shipping and Updating Your Product The only thing that matters to the code signing system is that the signed code installed on the user’s system identical to the code that you signed. It does not matter how you package, deliver, or install your product as long as you don’t introduce any changesinto the product. Compression, encoding, encrypting, and even binary patching the code are all right as long as you end up with exactly what you started with. You can use any installer you like, as long as it doesn't write anything into the product as it installs it. Drag-installs are fine as well. Code Signing Tasks Shipping and Updating Your Product 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 23When you have qualified a new version of your product, sign it just as you signed the previous version, with the same identifier and the same designated requirement. The user’s system will consider the new version of your product to be the same program as the previous version. In particular, the keychain will not distinguish older and newer versions of your program aslong as both were signed and the unique Identifier hasn't changed. You can take a partial-update approach to revising your code on the user’s system. To do so, sign the new version as usual, then calculate the differences between the new and the old signed versions, and transmit the differences. Because the differences include the new signature data, the result of installing the changes on the end-user's system will be the newly signed version. You cannot patch a signed application in the field. If you do so, the system will notice that the application has changed and will invalidate the signature, and there is no way to re-validate or resign the application in the field. Code Signing Tasks Shipping and Updating Your Product 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 24When you use the codesign command to sign a block of code, you can specify internal requirements; that is, the criteria that you recommend should be used to evaluate the code signature. It is up to the verifier to decide whether to apply the internal requirements or some other set of requirements when deciding how to treat the signed code. You use the code requirement language described in this chapter when specifying requirementsto the codesign or csreq command (see the manual pagesfor codesign(1) and csreq(1)). This chapter describes the requirement language source code. You can compile a set of requirements and save them in binary form using the csreq command. You can provide requirements to the codesign command either as source code or as a binary file. Both the codesign and csreq commands can convert a binary requirement set to text. Although there is some flexibility in the source code syntax (for example, quotes can always be used around string constants but are not always required), conversion from binary to text always uses the same form: ● Parentheses are placed (usually only) where required to clarify operator precedence. ● String constants are quoted (usually only) where needed. ● Whether originally specified as constants or through file paths, certificate hashes are always returned as hash constants. ● Comments in the original source are not preserved in the reconstructed text. Language Syntax Some basic features of the language syntax are: ● Expressions use conventional infix notation (that is, the operator is placed between the two entities being acted on; for example quantity < constant). ● Keywords are reserved, but can be quoted to be included as part of ordinary strings. ● Comments are allowed in C, Objective C, and C++. ● Unquoted whitespace is allowed between tokens, but strings containing whitespace must be quoted. ● Line endings have no special meaning and are treated as whitespace. 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 25 Code Signing Requirement LanguageEvaluation of Requirements A requirement constitutes an expression without side effects. Each requirement can have any number of subexpressions, each of which is evaluated with a Boolean (succeed-fail) result. There is no defined order of evaluation. The subexpressions are combined using logical operators in the expression to yield an overall Boolean result for the expression. Depending on the operators used, an expression can succeed even if some subexpressions fail. For example, the expression anchor apple or anchor = "/var/db/yourcorporateanchor.cert" succeeds if either subexpression succeeds—that is, if the code was signed either by Apple or by your company—even though one of the subexpressions is sure to fail. If an error occurs during evaluation, on the other hand, evaluation stops immediately and the codesign or csreq command returns with a result code indicating the reason for failure. Constants Thissection describesthe use ofstring, integer, hash-value, and binary constantsin the code signing requirement language. String Constants String constants must be enclosed by double quotes (" ") unless the string contains only letters, digits, and periods (.), in which case the quotes are optional. Absolute file paths, which start with a slash, do not require quotes unless they contain spaces. For example: com.apple.mail //no quotes are required "com.apple.mail" //quotes are optional "My Company's signing identity" //requires quotes for spaces and apostrophe /Volumes/myCA/root.crt //no quotes are required "/Volumes/my CA/root.crt" //space requires quotes "/Volumes/my_CA/root.crt" //underscore requires quotes It’s never incorrect to enclose the string in quotes—if in doubt, use quotes. Use a backslash to “escape” any character. For example: Code Signing Requirement Language Evaluation of Requirements 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 26"one \" embedded quote" //one " embedded quote "one \\ embedded backslash" //one \ embedded backslash There is nothing special about the single quote character ('). Integer Constants Integer constants are written as decimal constants are in C. The language does not allow radix prefixes (such as 0x) or leading plus or minus (+ or -) signs. Hash Constants Hash values are written either as a hexadecimal number in quotes preceded by an H, or as a path to a file containing a binary certificate. If you use the first form, the number must include the exact number of digits in the hash value. A SHA-1 hash (the only kind currently supported) requires exactly 40 digits; for example: H"0123456789ABCDEFFEDCBA98765432100A2BC5DA" You can use either uppercase or lowercase letters (A..F or a..f) in the hexadecimal numbers. If you specify a file path, the compiler readsthe binary certificate and calculatesthe hash for you. The compiled version of the requirement code includes only the hash; the certificate file and the path are not retained. If you convert the requirement back to text, you get the hexadecimal hash constant. The file path must point to a file containing an X.509 DER encoded certificate. No container forms (PKCS7, PKCS12) are allowed, nor is the OpenSSL "PEM" form supported. Variables There are currently no variables in the requirement language. Logical Operators The requirement language includes the following logical operators, in order of decreasing precedence: ● ! (negation) ● and (logical AND) ● or (logical OR) Code Signing Requirement Language Variables 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 27These operators can be used to combine subexpressionsinto more complex expressions. The negation operator (!) is a unary prefix operator. The others are infix operators. Parentheses can be used to override the precedence of the operators. Because the language is free of side effects, evaluation order of subexpressions is unspecified. Comparison Operations The requirement language includes the following comparison operators: ● = (equals) ● < (less than) ● > (greater than) ● <= (less than or equal to) ● >= (greater than or equal to) ● exists (value is present) The value-present (exists) operator is a unary suffix operator. The others are infix operators. There are no operators for non-matches (not equal to, not greater than, and so on). Use the negation operator (!) together with the comparison operators to make non-match comparisons. Equality All equality operations compare some value to a constant. The value and constant must be of the same type: a string matches a string constant, a data value matches a hexadecimal constant. The equality operation evaluates to true if the value exists and is equal to the constant. String matching uses the same matching rules as CFString (see CFString Reference ). In match expressions (see “Info” (page 30), “Part of a Certificate” (page 31), and “Entitlement” (page 33)), substrings of string constants can be matched by using the * wildcard character: ● value = *constant* is true if the value exists and any substring of the value matches the constant; for example: ● thunderbolt = *under* ● thunderbolt = *thunder* ● thunderbolt = *bolt* ● value = constant* is true if the value exists and begins with the constant; for example: Code Signing Requirement Language Comparison Operations 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 28● thunderbolt = thunder* ● thunderbolt = thun* ● value = *constant is true if the value exists and ends with the constant; for example: ● thunderbolt = *bolt ● thunderbolt = *underbolt If the constant is written with quotation marks, the asterisks must be outside the quotes. An asterisk inside the quotation marks is taken literally. For example: ● "ten thunderbolts" = "ten thunder"* is true ● "ten thunder*bolts" = "ten thunder*"* is true ● "ten thunderbolts" = "ten thunder*" is false Inequality Inequality operations compare some value to a constant. The value and constant must be of the same type: a string matches a string constant, a data value matches a hexadecimal constant. String comparisons use the same matching rules as CFString with the kCFCompareNumerically option flag; for example, "17.4" is greater than "7.4". Existence The existence operator tests whether the value exists. It evaluates to false only if the value does not exist at all or is exactly the Boolean value false. An empty string and the number 0 are considered to exist. Constraints Several keywords in the requirement language are used to require that specific certificates be present or other conditions be met. Identifier The expression identifier = constant succeedsif the unique identifierstring embedded in the code signature is exactly equal to constant. The equal sign is optional in identifier expressions. Signing identifiers can be tested only for exact equality; the wildcard character (*) can not be used with the identifier constraint, nor can identifiers be tested for inequality. Code Signing Requirement Language Constraints 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 29Info The expression info [key]match expression succeedsif the value associated with the top-level key in the code’s info.plist file matches match expression , where match expression can include any of the operators listed in “Logical Operators” (page 27) and “Comparison Operations” (page 28). For example: info [CFBundleShortVersionString] < "17.4" or info [MySpecialMarker] exists You must specify key as a string constant. If the value of the specified key is a string, the match is applied to it directly. If the value is an array, it must be an array of strings and the match is made to each in turn, succeeding if any of them matches. Substrings of string constants can be matched by using any match expression (see “Comparison Operations” (page 28)). If the code has no info.plist file, or the info.plist does not contain the specified key, this expression evaluates to false without returning an error. Certificate Certificate constraints refer to certificates in the certificate chain used to validate the signature. Most uses of the certificate keyword accept an integer that indicatesthe position of the certificate in the chain: positive integers count from the leaf (0) toward the anchor. Negative integers count backward from the anchor (-1). For example, certificate 1 is the intermediate certificate that was used to sign the leaf (that is, the signing certificate), and certificate -2 indicates the certificate that was directly signed by the anchor. Note that this convention is the same as that used for array indexing in the Perl and Ruby programming languages: Anchor First intermediate Second intermediate Leaf certificate 3 certificate 2 certificate 1 certificate 0 certificate -1 certificate -2 certificate -3 certificate -4 Other keywords include: Code Signing Requirement Language Constraints 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 30● certificate root—the anchor certificate; same as certificate 0 ● anchor—same as certificate root ● certificate leaf—the signing certificate; same as certificate -1 Note: The short form cert is allowed for the keyword certificate. If there is no certificate at the specified position, the constraint evaluates to false without returning an error. If the code was signed using an ad-hoc signature, there are no certificates at all and all certificate constraints evaluate to false. (An ad-hoc signature is created by signing with the pseudo-identity - (a dash). An ad-hoc signature does not use or record a cryptographic identity, and thusidentifies exactly and only the one program being signed.) If the code was signed by a self-signed certificate, then the leaf and root refer to the same single certificate. Whole Certificate To require a particular certificate to be present in the certificate chain, use the form certificate position = hash or one of the equivalent forms discussed above, such as anchor = hash . Hash constants are described in “Hash Constants” (page 27). For Apple’s own code, signed by Apple, you can use the short form anchor apple For code signed by Apple, including code signed using a signing certificate issued by Apple to other developers, use the form anchor apple generic Part of a Certificate To match a well-defined element of a certificate, use the form certificate position[element]match expression where match expression can include the * wildcard character and any of the operators listed in “Logical Operators” (page 27) and “Comparison Operations” (page 28). The currently supported elements are asfollows: Code Signing Requirement Language Constraints 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 31Note: Case is significant in element names. Element name Meaning Comments subject.CN Subject common name Shown in Keychain Access utility subject.C Subject country name subject.D Subject description subject.L Subject locality subject.O Subject organization Usually company or organization subject.OU Subject organizational unit subject.STREET Subject street address Certificate field by OID To check for the existence of any certificate field identified by its X.509 object identifier (OID), use the form certificate position [field.OID] exists The object identifier must be written in numeric form (x.y.z ...) and can be the OID of a certificate extension or of a conventional element of a certificate as defined by the CSSM standard (see Chapter 31 in Common Security: CDSA and CSSM, version 2 (with corrigenda) by the Open Group (http://www.opengroup.org/security/cdsa.htm)). Trusted The expression certificate position trusted succeeds if the certificate specified by position is marked trusted for the code signing certificate policy in the system’s Trust Settings database. The position argument is an integer or keyword that indicates the position of the certificate in the chain; see the discussion under “Certificate” (page 30). The expression anchor trusted Code Signing Requirement Language Constraints 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 32succeeds if any certificate in the signature’s certificate chain is marked trusted for the code signing certificate policy in the system’s Trust Settings database, provided that no certificate closer to the leaf certificate is explicitly untrusted. Thus, using the trusted keyword with a certificate position checks only the specified certificate, while using it with the anchor keyword checks all the certificates, giving precedence to the trust setting found closest to the leaf. Important: The syntax anchor trusted is not a synonym for certificate anchor trusted. Whereas the former checks all certificates in the signature, the latter checks only the anchor certificate. Certificates can have per-user trust settings and system-wide trust settings, and trust settings apply to specific policies. The trusted keyword in the code signing requirement language causes trust to be checked for the specified certificate or certificates for the user performing the validation. If there are no settings for that user, then the system settings are used. In all cases, only the trust settings for the code-signing policy are checked. Policies and trust are discussed in Certificate, Key, and Trust Services Programming Guide . Important: If you do not include an expression using the trusted keyword in your code signing requirement, then the verifier does not check the trust status of the certificates in the code signature at all. Entitlement The expression entitlement [key] match expression succeeds if the value associated with the specified key in the signature’s embedded entitlement dictionary matches match expression , where match expression can include the * wildcard character and any of the operators listed in “Logical Operators” (page 27) and “Comparison Operations” (page 28). You must specify key as a string constant. The entitlement dictionary is included in signatures for certain platforms. Code Directory Hash The expression cdhash hash-constant computes a SHA-1 hash of the program’s CodeDirectory resource and succeeds if the value of this hash exactly equals the specified hash constant. Code Signing Requirement Language Constraints 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 33The CodeDirectory resource is the master directory of the contents of the program. It consists of a versioned header followed by an array of hashes. This array consists of a set of optionalspecial hashesfor other resources, plus a vector of hashes for pages of the main executable. The CodeSignature and CodeDirectory resources together make up the signature of the code. You can use the codesign utility with (at least) three levels of verbosity to obtain the hash constant of a program’s CodeDirectory resource: $ codesign -dvvv /bin/ls ... CodeDirectory v=20001 size=257 flags=0x0(none) hashes=8+2 location=embedded CDHash=4bccbc576205de37914a3023cae7e737a0b6a802 ... Because the code directory changes whenever the program changes in a nontrivial way, this test can be used to unambiguously identify one specific version of a program. When the operating system signs an otherwise unsigned program (so that the keychain or Parental Controls can recognize the program, for example), it uses this requirement. Requirement Sets A requirementset is a collection of distinct requirements, each indexed (tagged) with a type code. The expression tag => requirement applies requirement to the type of code indicated by tag , where possible tags are ● host—thisrequirement is applied to the direct host of this code module; each code module in the hosting path can have its own host requirement, where the hosting path isthe chain of code signing hostsstarting with the most specific code known to be running, and ending with the root of trust (the kernel) ● guest—this requirement is applied to each code module that is hosted by this code module ● library—this requirement is applied to all libraries mounted by the signed code ● designated—this is an explicitly specified designated requirement for the signed code; if there is no explicitly specified designated requirement for the code, then there is no designated internal requirement The primary use of requirement sets is to represent the internal requirements of the signed code. For example: Code Signing Requirement Language Requirement Sets 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 34codesign -r='host => anchor apple and identifier com.apple.perl designated => anchor /my/root and identifier com.bar.foo' setsthe internal requirements ofsome code, having a host requirement of anchor apple and identifier com.apple.perl (“I'm a Perlscript and I want to be run by Apple's Perl interpreter”) and an explicit designated requirement of anchor /my/root and identifier com.bar.foo. Note that this command sets no guest or library requirements. You can also put the requirement set in a file and point to the file: codesign -r myrequirements.rqset where the file myrequirements.rqset might contain: //internal requirements host => anchor apple and identifier com.apple.perl //require Apple's Perl interpreter designated => anchor /my/root and identifier com.bar.foo Code Signing Requirement Language Requirement Sets 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 35This table describes the changes to Code Signing Guide . Date Notes 2012-07-23 Added information about new spctl features in OS X v10.8. Added information about Developer IDs and explanation of how to code sign a framework. 2012-05-15 2011-09-28 Revised document to focus exclusively on code signing. Some of the content in this document was previously in Code Signing and Application Sandboxing Guide . 2011-07-11 Added information about application sandboxing. 2009-10-19 Fixed typographical errors. 2009-10-13 Clarified explanation of CFBundleIdentifier and uniqueness. 2008-11-19 Added a chapter describing the code signing requirement language. New document that explains why you should sign your code and provides code signing procedures. 2007-05-15 2012-07-23 | © 2012 Apple Inc. All Rights Reserved. 36 Document Revision HistoryApple Inc. © 2012 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrievalsystem, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apple’s copyright notice. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Apple, the Apple logo, Keychain, Logic, Mac, OS X, Safari, Sand, and Xcode are trademarks of Apple Inc., registered in the U.S. and other countries. App Store and Mac App Store are service marks of Apple Inc. Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.ASARESULT, THISDOCUMENT IS PROVIDED “AS IS,” AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state. View Controller Programming Guide for iOSContents About View Controllers 9 At a Glance 10 A View Controller Manages a Set of Views 10 You Manage Your Content Using Content View Controllers 10 Container View Controllers Manage Other View Controllers 10 Presenting a View Controller Temporarily Brings Its View Onscreen 11 Storyboards Link User Interface Elements into an App Interface 11 How to Use This Document 12 Prerequisites 12 See Also 12 View Controller Basics 14 Screens, Windows, and Views Create Visual Interfaces 15 View Controllers Manage Views 17 A Taxonomy of View Controllers 19 Content View Controllers Display Content 19 Container View Controllers Arrange Content of Other View Controllers 21 A View Controller’s Content Can Be Displayed in Many Ways 26 View Controllers Work Together to Create an App’s Interface 28 Parent-Child Relationships Represent Containment 29 Sibling Relationships Represent Peers Inside a Container 29 Presentation Represents a Transient Display of Another Interface 30 Control Flow Represents Overall Coordination Between Content Controllers 31 Storyboards Help You Design Your User Interface 33 Using View Controllers in Your App 35 Working with View Controllers in Storyboards 36 The Main Storyboard Initializes Your App’s User Interface 37 Segues Automatically Instantiate the Destination View Controller 37 Instantiating a Storyboard’s View Controller Programmatically 39 Containers Automatically Instantiate Their Children 41 Instantiating a Non-Storyboard View Controller 41 Displaying a View Controller’s Contents Programmatically 41 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 2Creating Custom Content View Controllers 43 Anatomy of a Content View Controller 43 View Controllers Manage Resources 44 View Controllers Manage Views 45 View Controllers Respond to Events 45 View Controllers Coordinate with Other Controllers 45 View Controllers Often Work with Containers 46 View Controllers May Be Presented by Other View Controllers 46 Designing Your Content View Controller 47 Use a Storyboard to Implement Your View Controller 48 Know When Your Controller Is Instantiated 48 Know What Data Your View Controller Shows and Returns 48 Know What Tasks Your Controller Allows the User to Perform 49 Know How Your View Controller Is Displayed Onscreen 50 Know How Your Controller Collaborates with Other Controllers 50 Examples of Common View Controller Designs 50 Example: Game Title Screen 50 Example: Master View Controller 52 Example: Detail View Controller 53 Example: Mail Compose View Controller 54 Implementation Checklist for Custom Content View Controllers 54 Resource Management in View Controllers 56 Initializing a View Controller 56 Initializing a View Controller Loaded from a Storyboard 56 Initializing View Controllers Programmatically 57 A View Controller Instantiates Its View Hierarchy When Its View is Accessed 57 Loading a View Controller’s View from a Storyboard 59 Creating a View Programmatically 60 Managing Memory Efficiently 61 On iOS 6 and Later, a View Controller Unloads Its Own Views When Desired 63 On iOS 5 and Earlier, the System May Unload Views When Memory Is Low 64 Responding to Display-Related Notifications 66 Responding When a View Appears 66 Responding When a View Disappears 67 Determining Why a View’s Appearance Changed 67 Resizing the View Controller’s Views 69 A Window Sets the Frame of Its Root View Controller’s View 69 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 3 ContentsA Container Sets the Frames of Its Children’s Views 70 A Presented View Controller Uses a Presentation Context 70 A Popover Controller Sets the Size of the Displayed View 70 How View Controllers Participate in the View Layout Process 70 Using View Controllers in the Responder Chain 72 The Responder Chain Defines How Events Are Propagated to the App 72 Supporting Multiple Interface Orientations 74 Controlling What Interface Orientations Are Supported (iOS 6) 75 Declaring a View Controller’s Supported Interface Orientations 75 Dynamically Controlling Whether Rotation Occurs 76 Declaring a Preferred Presentation Orientation 76 Declaring the App’s Supported Interface Orientations 76 Understanding the Rotation Process (iOS 5 and earlier) 77 Declaring the Supported Interface Orientations 77 Responding to Orientation Changes in a Visible View Controller 78 Rotations May Occur When Your View Controller Is Hidden 80 Creating an Alternate Landscape Interface 80 Tips for Implementing Your Rotation Code 82 Accessibility from the View Controller’s Perspective 83 Moving the VoiceOver Cursor to a Specific Element 83 Responding to Special VoiceOver Gestures 84 Escape 85 Magic Tap 85 Three-Finger Scroll 85 Increment and Decrement 86 Observing Accessibility Notifications 86 Presenting View Controllers from Other View Controllers 88 How View Controllers Present Other View Controllers 88 Presentation Styles for Modal Views 91 Presenting a View Controller and Choosing a Transition Style 93 Presentation Contexts Provide the Area Covered by the Presented View Controller 95 Dismissing a Presented View Controller 95 Presenting Standard System View Controllers 96 Coordinating Efforts Between View Controllers 98 When Coordination Between View Controllers Occurs 98 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 4 ContentsWith Storyboards, a View Controller is Configured When It Is Instantiated 99 Configuring the Initial View Controller at Launch 100 Configuring the Destination Controller When a Segue is Triggered 101 Using Delegation to Communicate with Other Controllers 103 Guidelines for Managing View Controller Data 105 Enabling Edit Mode in a View Controller 106 Toggling Between Display and Edit Mode 106 Presenting Editing Options to the User 108 Creating Custom Segues 109 The Life Cycle of a Segue 109 Implementing a Custom Segue 109 Creating Custom Container View Controllers 111 Designing Your Container View Controller 111 Examples of Common Container Designs 113 A Navigation Controller Manages a Stack of Child View Controllers 113 A Tab Bar Controller Uses a Collection of Child Controllers 115 A Page Controller Uses a Data Source to Provide New Children 116 Implementing a Custom Container View Controller 116 Adding and Removing a Child 116 Customizing Appearance and Rotation Callback Behavior 119 Practical Suggestions for Building a Container View Controller 120 Document Revision History 122 Glossary 124 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 5 ContentsFigures, Tables, and Listings View Controller Basics 14 Figure 1-1 A window with its target screen and content views 15 Figure 1-2 Classes in the view system 16 Figure 1-3 A view controller attached to a window automatically adds its view as a subview of the window 17 Figure 1-4 Distinct views managed by separate view controllers 18 Figure 1-5 View controller classes in UIKit 19 Figure 1-6 Managing tabular data 21 Figure 1-7 Navigating hierarchical data 23 Figure 1-8 Different modes of the Clock app 24 Figure 1-9 A master-detail interface in portrait and landscape modes 25 Figure 1-10 Presenting a view controller 27 Figure 1-11 Parent-child relationships 29 Figure 1-12 Sibling relationships in a navigation controller 30 Figure 1-13 Modal presentation by a content view 30 Figure 1-14 The actual presentation is performed by the root view controller. 31 Figure 1-15 Communication between source and destination view controllers 32 Figure 1-16 A storyboard diagram in Interface Builder 33 Using View Controllers in Your App 35 Figure 2-1 A storyboard holds a set of view controllers and associated objects 36 Listing 2-1 Triggering a segue programmatically 38 Listing 2-2 Instantiating another view controller inside the same storyboard 39 Listing 2-3 Instantiating a view controller from a new storyboard 40 Listing 2-4 Installing the view controller as a window’s root view controller 42 Creating Custom Content View Controllers 43 Figure 3-1 Anatomy of a content view controller 44 Figure 3-2 A container view controller imposes additional demands on its children 46 Resource Management in View Controllers 56 Figure 4-1 Loading a view into memory 58 Figure 4-2 Connections in the storyboard 60 Figure 4-3 Unloading a view from memory 65 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 6Table 4-1 Places to allocate and deallocate memory 62 Listing 4-1 Custom view controller class declaration 59 Listing 4-2 Creating views programmatically 61 Listing 4-3 Releasing the views of a view controller not visible on screen 63 Responding to Display-Related Notifications 66 Figure 5-1 Responding to the appearance of a view 66 Figure 5-2 Responding to the disappearance of a view 67 Table 5-1 Methods to call to determine why a view’s appearance changed 68 Using View Controllers in the Responder Chain 72 Figure 7-1 Responder chain for view controllers 73 Supporting Multiple Interface Orientations 74 Figure 8-1 Processing an interface rotation 79 Listing 8-1 Implementing the supportedInterfaceOrientations method 75 Listing 8-2 Implementing the preferredInterfaceOrientationForPresentation method 76 Listing 8-3 Implementing the shouldAutorotateToInterfaceOrientation: method 78 Listing 8-4 Presenting the landscape view controller 81 Accessibility from the View Controller’s Perspective 83 Listing 9-1 Posting an accessibility notification can change the first element read aloud 84 Listing 9-2 Registering as an observer for accessibility notifications 86 Presenting View Controllers from Other View Controllers 88 Figure 10-1 Presented views in the Calendar app. 89 Figure 10-2 Creating a chain of modal view controllers 90 Figure 10-3 Presenting navigation controllers modally 91 Figure 10-4 iPad presentation styles 92 Table 10-1 Transition styles for modal view controllers 93 Table 10-2 Standard system view controllers 96 Listing 10-1 Presenting a view controller programmatically 94 Coordinating Efforts Between View Controllers 98 Listing 11-1 The app delegate configures the controller 100 Listing 11-2 Creating the window when a main storyboard is not being used 101 Listing 11-3 Configuring the destination controller in a segue 102 Listing 11-4 Delegate protocol for dismissing a presented view controller 104 Listing 11-5 Dismissing a presented view controller using a delegate 104 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 7 Figures, Tables, and ListingsEnabling Edit Mode in a View Controller 106 Figure 12-1 Display and edit modes of a view 107 Creating Custom Segues 109 Listing 13-1 A custom segue 110 Creating Custom Container View Controllers 111 Figure 14-1 A container view controller’s view hierarchy contains another controller’s views 112 Figure 14-2 A navigation controller’s view and view controller hierarchy 114 Figure 14-3 A tab bar controller’s view and view controller hierarchy 115 Listing 14-1 Adding another view controller’s view to the container’s view hierarchy 117 Listing 14-2 Removing another view controller’s view to the container’s view hierarchy 117 Listing 14-3 Transitioning between two view controllers 118 Listing 14-4 Disabling automatic appearance forwarding 119 Listing 14-5 Forwarding appearance messages when the container appears or disappears 119 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 8 Figures, Tables, and ListingsView controllers are a vital link between an app’s data and its visual appearance. Whenever an iOS app displays a user interface, the displayed content is managed by a view controller or a group of view controllers coordinating with each other. Therefore, view controllers provide the skeletal framework on which you build your apps. iOS provides many built-in view controller classesto supportstandard user interface pieces,such as navigation and tab bars. As part of developing an app, you also implement one or more custom controllers to display the content specific to your app. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 9 About View ControllersAt a Glance View controllers are traditional controller objects in the Model-View-Controller (MVC) design pattern, but they also do much more. View controllers provide many behaviors common to all iOS apps. Often, these behaviors are built into the base class. For some behaviors, the base class provides part of the solution and your view controllersubclassimplements custom code to provide the rest. For example, when the user rotatesthe device, the standard implementation attempts to rotate the user interface; however, your subclass decides whether the user interface should be rotated, and, if so, how the configuration of its views should change in the new orientation. Thus, the combination of a structured base class and specific subclassing hooks make it easy for you to customize your app’s behavior while conforming to the platform design guidelines. A View Controller Manages a Set of Views A view controller manages a discrete portion of your app’s user interface. Upon request, it provides a view that can be displayed or interacted with. Often, this view is the root view for a more complex hierarchy of views—buttons, switches, and other user interface elements with existing implementations in iOS. The view controller acts asthe central coordinating agent for this view hierarchy, handling exchanges between the views and any relevant controller or data objects. Relevant chapter: “View Controller Basics” (page 14) You Manage Your Content Using Content View Controllers To present content that is specific to your app, you implement your own content view controllers. You create new view controller classes by subclassing either the UIViewController class or the UITableViewController class, implementing the methods necessary to present and control your content. Relevant chapter: “Creating Custom Content View Controllers” (page 43) Container View Controllers Manage Other View Controllers Container view controllers display content owned by other view controllers. These other view controllers are explicitly associated with the container, forming a parent-child relationship. The combination of container and content view controllers creates a hierarchy of view controller objects with a single root view controller. Each type of container defines its own interface to manage its children. The container’s methods sometimes define specific navigational relationships between the children. A container can also set specific restrictions on the types of view controllers that can be its children. It may also expect the view controllers that are its children to provide additional content used to configure the container. About View Controllers At a Glance 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 10iOS provides many built-in container view controller types you can use to organize your user interface. Relevant chapter: “View Controller Basics” (page 14) Presenting a View Controller Temporarily Brings Its View Onscreen Sometimes a view controller wants to display additional information to the user. Or perhaps it wants the user to provide additional information or perform a task. Screen space is limited on iOS devices; the device might not have enough room to display all the user interface elements at the same time. Instead, an iOS app temporarily displays another view for the user to interact with. The view is displayed only long enough for the user to finish the requested action. To simplify the effort required to implement such interfaces, iOS allows a view controller to present another view controller’s contents. When presented, the new view controller’s views are displayed on a portion of the screen—often the entire screen. Later, when the user completes the task, the presented view controller tells the view controller that presented it that the task is complete. The presenting view controller then dismisses the view controller it presented, restoring the screen to its original state. Presentation behavior must be included in a view controller’s design in order for it to be presented by another view controller. Relevant chapter: “Presenting View Controllers from Other View Controllers” (page 88) Storyboards Link User Interface Elements into an App Interface A user interface design can be very complex. Each view controller references multiple views, gesture recognizers, and other user interface objects. In return, these objects maintain references to the view controller or execute specific pieces of code in response to actions the user takes. And view controllers rarely act in isolation. The collaboration between multiple view controllers also defines other relationships in your app. In short, creating a user interface means instantiating and configuring many objects and establishing the relationships between them, which can be time consuming and error prone. Instead, use Interface Builder to create storyboards. A storyboard holds preconfigured instances of view controllers and their associated objects. Each object’s attributes can be configured in Interface Builder, as can relationships between them. At runtime, your app loads storyboards and uses them to drive your app’s interface. When objects are loaded from the storyboard, they are restored to the state you configured in the storyboard. UIKit also provides methods you can override to customize behaviors that cannot be configured directly in Interface Builder. About View Controllers At a Glance 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 11By using storyboards, you can easily see how the objects in your app’s user interface fit together. You also write less code to create and configure your app’s user-interface objects. Relevant chapter: “View Controller Basics” (page 14), “Using View Controllers in Your App” (page 35) How to Use This Document Start by reading “View Controller Basics” (page 14), which explains how view controllers work to create your app’s interface. Next, read “Using View Controllers in Your App” (page 35) to understand how to use view controllers, both those built into iOS and those you create yourself. When you are ready to implement your app’s custom controllers, read “Creating Custom Content View Controllers” (page 43) for an overview of the tasks your view controller performs, and then read the remaining chapters in this document to learn how to implement those behaviors. Prerequisites Before reading this document, you should be familiar with the content in Start Developing iOS Apps Today and Your Second iOS App: Storyboards. The storyboard tutorial demonstrates many of the techniques described in this book, including the following Cocoa concepts: ● Defining new Objective-C classes ● The role of delegate objects in managing app behaviors ● The Model-View-Controller paradigm See Also For more information about the standard container view controllers provided by UIKit, see View Controller Catalog for iOS . For guidance on how to manipulate views in your view controller, see View Programming Guide for iOS . For guidance on how to handle events in your view controller, see Event Handling Guide for iOS . For more information about the overall structure of an iOS app, see iOS App Programming Guide . About View Controllers How to Use This Document 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 12For guidance on how to configure storyboards in your project, see Xcode 4 User Guide About View Controllers See Also 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 13Appsrunning on iOS–based devices have a limited amount ofscreen space for displaying content and therefore must be creative in how they present information to the user. Apps that have lots of information to display must therefore only show a portion to start, and then show and hide additional content as the user interacts with the app. View controller objects provide the infrastructure for managing content and for coordinating the showing and hiding of it. By having different view controller classes control separate portions of your user interface, you break up the implementation of your user interface into smaller and more manageable units. Before you can use view controllers in your app, you need a basic understanding of the major classes used to display content in an iOS app, including windows and views. A key part of any view controller’simplementation isto manage the views used to display its content. However, managing viewsis not the only job view controllers perform. Most view controllers also communicate and coordinate with other view controllers when transitions occur. Because of the many connections view controllers manage, both looking inward to views and associated objects and looking outward to other controllers, understanding the connections between objects can sometimes be difficult. Instead, use Interface Builder to create storyboards. Storyboards make it easier to visualize the relationships in your app and greatly simplify the effort needed to initialize objects at runtime. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 14 View Controller BasicsScreens, Windows, and Views Create Visual Interfaces Figure 1-1 shows a simple interface. On the left, you can see the objects that make up this interface and understand how they are connected to each other. Figure 1-1 A window with its target screen and content views There are three major objects at work here: ● A UIScreen object that identifies a physical screen connected to the device. ● A UIWindow object that provides drawing support for the screen. ● A set of UIView objectsto perform the drawing. These objects are attached to the window and draw their contents when the window asks them to. View Controller Basics Screens, Windows, and Views Create Visual Interfaces 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 15Figure 1-2 shows how these classes (and related important classes) are defined in UIKit. Figure 1-2 Classes in the view system Although you don’t need to understand everything about views to understand view controllers, it can be helpful to consider the most salient features of views: ● A view represents a user interface element. Each view covers a specific area. Within that area, it displays contents or responds to user events. ● Views can be nested in a view hierarchy. Subviews are positioned and drawn relative to their superview. Thus, when the superview moves, its subviews move with it. This hierarchy makes it easy to assemble a group of related views by placing them in a common superview. ● Views can animate their property values. When a change to a property value is animated, the value gradually changes over a defined period of time until it reachesthe new value. Changesto multiple properties across multiple views can be coordinated in a single animation. Animation is critically important to iOS app development. Because most apps display only a portion of their contents at one time, an animation allows the user to see when a transition occurred and where the new content came from. An instantaneous transition might confuse the user. ● Views rarely understand the role they play in your app. For example, Figure 1-1 shows a button (titled Hello), which is a special kind of view, known as a control . Controls know how to respond to user interaction in their area, but they don’t know what they control. Instead, when a user interacts with a control, it sends messages to other objects in your app. This flexibility allows a single class (UIButton) to provide the implementation for multiple buttons, each configured to trigger a different action. A complex app needs many views, often assembling them into view hierarchies. It needs to animate subsets of these views onto or off the screen to provide the illusion of a single larger interface. And finally, to keep view classes reusable, the view classes need to be ignorant of the specific role they perform in the app. So the app logic—the brains—needs to be placed somewhere else. Your view controllers are the brains that tie your app’s views together. View Controller Basics Screens, Windows, and Views Create Visual Interfaces 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 16View Controllers Manage Views Each view controller organizes and controls a view; this view is often the root view of a view hierarchy. View controllers are controller objects in the MVC pattern, but a view controller also has specific tasks iOS expects it to perform. These tasks are defined by the UIViewController class that all view controllers inherit from. All view controllers perform view and resource management tasks; other responsibilities depend on how the view controller is used. Figure 1-3 shows the interface from Figure 1-1, but updated here to use a view controller. You never directly assign the views to the window. Instead, you assign a view controller to the window, and the view controller automatically adds its view to the window. Figure 1-3 A view controller attached to a window automatically adds its view as a subview of the window A view controller is careful to load its view only when the view is needed. It can also release the view under certain conditions. For these reasons, view controllers play a key part in managing resources in your app. A view controller is the natural place to coordinate actions of its connected views. For example, when a button is pressed, it sends a message to the view controller. Although the view itself may be ignorant of the task it performs, the view controller is expected to understand what the button press means and how it should respond. The controller might update data objects, animate or change property values stored in its views, or even bring another view controller’s contents to the screen. Usually, each view controller instantiated by your app sees only a subset of your app’s data. It knows how to display that particular set of data, without needing to know about other kinds of data. Thus, an app’s data model, user interface design, and the view controllers you create are all influenced by each other. View Controller Basics View Controllers Manage Views 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 17Figure 1-4 shows an example of an app that managesrecipes. This app displaysthree related but distinct views. The first view lists the recipes that the app manages. Tapping a recipe shows the second view, which describes the recipe. Tapping the recipe’s picture in the detail view shows the third view, a larger version of the photo. Each view is managed by a distinct view controller object whose job isto present the appropriate view, populate the subviews with data, and respond to user interactions within the view hierarchy. Figure 1-4 Distinct views managed by separate view controllers This example demonstrates a few factors common to view controllers: ● Every view is controlled by only one view controller. When a view is assigned to the view controller’s view property, the view controller owns it. If the view is a subview, it might be controlled by the same view controller or a different view controller. You’ll learn more about how to use multiple view controllers to organize a single view hierarchy when you learn about container view controllers. ● Each view controller interacts with a subset of your app’s data. For example, the Photo controller needs to know only the photo to be displayed. ● Because each view controller provides only a subset of the user experience, the view controllers must communicate with each other to make this experience seamless. They may also communicate with other controllers, such as data controllers or document objects. View Controller Basics View Controllers Manage Views 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 18A Taxonomy of View Controllers Figure 1-5 showsthe view controller classes available in the UIKit framework along with other classesimportant to view controllers. For example, the UITabBarController object manages a UITabBar object, which actually displays the tabs associated with the tab bar interface. Other frameworks define additional view controller classes not shown in this figure. Figure 1-5 View controller classes in UIKit View controllers, both those provided by iOS and those you define, can be divided into two general categories—content view controllers and container view controllers—which reflect the role the view controller plays in an app. Content View Controllers Display Content A content view controller presents content on the screen using a view or a group of views organized into a view hierarchy. The controllers described up to this point have been content view controllers. A content view controller usually knows about the subset of the app’s data that is relevant to the role the controller plays in the app. View Controller Basics A Taxonomy of View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 19Here are common examples where your app uses content view controllers: ● To show data to the user ● To collect data from the user ● To perform a specific task ● To navigate between a set of available commands or options, such as on the launch screen for a game Content view controllers are the primary coordinating objects for your app because they know the specific details of the data and tasks your app offers the user. Each content view controller object you create is responsible for managing all the views in a single view hierarchy. The one-to-one correspondence between a view controller and the views in its view hierarchy is the key design consideration. You should not use multiple content view controllers to manage the same view hierarchy. Similarly, you should not use a single content view controller object to manage multiple screens’ worth of content. For information about defining your content view controller and implementing the required behaviors, see “Creating Custom Content View Controllers” (page 43). About Table View Controllers Many apps display tabular data. For this reason, iOS provides a built-in subclass of the UIViewController class designed specifically for managing tabular data. This class, UITableViewController, manages a table view and adds support for many standard table-related behaviors such as selection management, row editing, and table configuration. This additional support is there to minimize the amount of code you must write to create and initialize a table-based interface. You can also subclass UITableViewController to add other custom behaviors. View Controller Basics A Taxonomy of View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 20Figure 1-6 shows an example using a table view controller. Because it is a subclass of the UIViewController class, the table view controller still has a pointer to the root view of the interface (through its view property) but it also has a separate pointer to the table view displayed in that interface. Figure 1-6 Managing tabular data For more information about table views, see Table View Programming Guide for iOS . Container View Controllers Arrange Content of Other View Controllers A container view controller contains content owned by other view controllers. These other view controllers are explicitly assigned to the container view controller as its children. A container controller can be both a parent to other controllers and a child of another container. Ultimately, this combination of controllers establishes a view controller hierarchy. Each type of container view controller establishes a user interface that its children operate in. The visual presentation of this user interface and the design it imposes on its children can vary widely between different types of containers. For example, here are some ways that different container view controllers may distinguish themselves: ● A container provides its own API to manage its children. ● A container decides whether the children have a relationship between them and what that relationship is. View Controller Basics A Taxonomy of View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 21● A container manages a view hierarchy just as other view controllers do. A container can also add the views of any of its children into its view hierarchy. The container decides when such a view is added and how it should be sized to fit the container’s view hierarchy, but otherwise the child view controller remains responsible for the view and its subviews. ● A container might impose specific design considerations on its children. For example, a container might limit its children to certain view controller classes, or it might expect those controllersto provide additional content needed to configure the container’s views. The built-in container classes are each organized around an important user interface principle. You use the user interfaces managed by these containers to organize complex apps. About Navigation Controllers A navigation controller presents data that is organized hierarchically and is an instance of the UINavigationController class. The methods of this class provide support for managing a stack-based collection of content view controllers. Thisstack representsthe path taken by the user through the hierarchical data, with the bottom of the stack reflecting the starting point and the top of the stack reflecting the user’s current position in the data. Figure 1-7 shows screens from the Contacts app, which uses a navigation controller to present contact information to the user. The navigation bar at the top of each page is owned by the navigation controller. The rest of each screen displayed to the user is managed by a content view controller that presentsthe information View Controller Basics A Taxonomy of View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 22at that specific level of the data hierarchy. As the user interacts with controls in the interface, those controls tell the navigation controller to display the next view controller in the sequence or dismiss the current view controller. Figure 1-7 Navigating hierarchical data Although a navigation controller’s primary job is to manage its child view controllers, it also manages a few views. Specifically, it manages a navigation bar (that displays information about the user’s current location in the data hierarchy), a button (for navigating back to previous screens), and any custom controls the current view controller needs. You do not directly modify the views owned by the view controller. Instead, you configure the controls that the navigation controller displays by setting properties on each child view controller. For information about how to configure and use navigation controller objects, see “Navigation Controllers”. About Tab Bar Controllers A tab bar controller is a container view controller that you use to divide your app into two or more distinct modes of operation. A tab bar controller is an instance of the UITabBarController class. The tab bar has multiple tabs, each represented by a child view controller. Selecting a tab causes the tab bar controller to display the associated view controller’s view on the screen. View Controller Basics A Taxonomy of View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 23Figure 1-8 shows several modes of the Clock app along with the relationships between the corresponding view controllers. Each mode has a content view controller to manage the main content area. In the case of the Clock app, the Clock and Alarm view controllers both display a navigation-style interface to accommodate some additional controls along the top of the screen. The other modes use content view controllers to present a single screen. Figure 1-8 Different modes of the Clock app You use tab bar controllers when your app either presents different types of data or presents the same data in different ways. For information about how to configure and use a tab bar controller, see “Tab Bar Controllers”. About Split View Controllers A split view controller divides the screen into multiple parts, each of which can be updated separately. The appearance of a split view controller may vary depending on its orientation. A split view controller is an instance of the UISplitViewController class. The contents of a split view interface are derived from two child view controllers. View Controller Basics A Taxonomy of View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 24Figure 1-9 shows a split view interface from the MultipleDetailViews sample app. In portait mode, only the detail view is displayed. The list view is made available using a popover. However, when displayed in landscape mode, the split view controller displays the contents of both children side by side. Figure 1-9 A master-detail interface in portrait and landscape modes Split view controllers are supported on iPad only and are designed to help you take advantage of the larger screen of that device. They are the preferred way to implement master-detail interfaces in iPad apps. For information about how to configure and use a split view controller, see “Popovers”. About Popover Controllers Look again at Figure 1-9. When the split view controller is displayed in portrait mode, the master views is displayed in a special control, known as a popover. In an iPad app, you can use popover controllers (UIPopoverController) to implement popovers in your own app. A popover controller is not actually a container; it does not inherent from UIViewController at all. But, in practice, a popover controller is similar to a container, so you apply the same programming principles when you use them. For information about how to configure and use a popover controller, see “Popovers”. View Controller Basics A Taxonomy of View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 25About Page View Controllers A page view controller is a container view controller used to implement a page layout. That layout allows users to flip between discrete pages of content as if it were a book. A page view controller is an instance of the UIPageViewController class. Each content page is provided by a content view controller. The page view controller managesthe transitions between pages. When new pages are required, the page view controller calls an associated data source to retrieve a view controller for the next page. For information about how to configure and use a page view controller, see “Page View Controllers”. A View Controller’s Content Can Be Displayed in Many Ways For a view controller’s contents to be visible to the user, it must be associated with a window. There are many ways you can do this in your app: ● Make the view controller a window’s root view controller. ● Make the view controller a child of a container. ● Show the view controller in a popover control. ● Present it from another view controller. View Controller Basics A View Controller’s Content Can Be Displayed in Many Ways 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 26Figure 1-10 shows an example from the Contacts app. When the user clicks the plus button to add a new contact, the Contacts view controller presentsthe New Contact view controller. The New Contactscreen remains visible until the user cancels the operation or provides enough information about the contact that it can be saved to the contacts database. At that point the information is transmitted to the Contacts view controller, which then dismisses the controller it presented. Figure 1-10 Presenting a view controller A presented view controller isn’t a specific type of view controller—the presented view controller can be either a content or a container view controller with an attached content view controller. In practice, the content view controller is designed specifically to be presented by another controller, so it can be useful to think of it as a variant of a content view controller. Although container view controllers define specific relationships between the managed view controllers, using presentation allows you to define the relationship between the view controller being presented and the view controller presenting it. View Controller Basics A View Controller’s Content Can Be Displayed in Many Ways 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 27Most of the time, you present view controllersto gather information from the user or capture the user’s attention for some specific purpose. Once that purpose is completed, the presenting view controller dismisses the presented view controller and returns to the standard app interface. It is worth noting that a presented view controller can itself present another view controller. This ability to chain view controllers together can be useful when you need to perform several modal actions sequentially. For example, if the user taps the Add Photo button in the New Contact screen in Figure 1-10 and wants to choose an existing image, the New Contact view controller presents an image picker interface. The user must dismiss the image picker screen and then dismiss the New Contact screen separately to return to the list of contacts. When presenting a view controller, one view controller determines how much of the screen is used to present the view controller. The portion of the screen is called the presentation context By default, the presentation context is defined to cover the window. For more information about how to present view controllers in your app, see “Presenting View Controllers from Other View Controllers” (page 88). View Controllers Work Together to Create an App’s Interface View controllers manage their views and other associated objects, but they also work with other view controllers to provide a seamless user interface. The distribution of work and communication between your app’s view controllers is an essential part of working with them. Because these relationships are so important to building complex apps, this next section reviews the relationships already discussed and describes them in more detail. View Controller Basics View Controllers Work Together to Create an App’s Interface 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 28Parent-Child Relationships Represent Containment A view controller hierarchy starts with a single parent, the root view controller of a window. If that view controller is a container, it may have children that provide content. Those controllers, in turn, may also be containers with children of their own. Figure 1-11 shows an example of a view controller hierarchy. The root view controller is a tab view controller with four tabs. The first tab uses a navigation controller with children of its own and the other three tabs are managed by content view controllers with no children. Figure 1-11 Parent-child relationships The area each view controller fills is determined by its parent. The root view controller’s area is determined by the window. In Figure 1-11, the tab view controller gets its size from the window. It reserves space for its tab bar and gives the remainder of the space to its children. If the navigation controller were the control displayed right now, it reserves space for its navigation bar and hands the rest to its content controller. At each step, the child view controller’s view is resized by the parent and placed into the parent’s view hierarchy. This combination of views and view controllers also establishes the responder chain for events handled by your app. Sibling Relationships Represent Peers Inside a Container The kind of container defines the relationships (if any exists) shared by its children. For example, compare the tab view controller and navigation controller. ● In a tab view controller, the tabs represent distinct screens of content; tab bar controllers do not define a relationship between its children, although your app can choose to do so. ● In a navigation controller, siblings display related views arranged in a stack. Siblings usually share a connection with adjacent siblings. View Controller Basics View Controllers Work Together to Create an App’s Interface 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 29Figure 1-12 shows a common configuration of view controllers associated with a navigation controller. The first child, the master, shows the available content without showing all of the details. When an item is selected, it pushes a new sibling onto the navigation controller so that the user can see the additional details. Similarly, if the user needsto see more details, thissibling can push another view controller thatshowsthe most detailed content available. When siblings have a well defined relationship as in this example, they often coordinate with each other, either directly or through the container controller. See Figure 1-15 (page 32). Figure 1-12 Sibling relationships in a navigation controller Presentation Represents a Transient Display of Another Interface A view controller presents another view controller when it wants that view controller to perform a task. The presenting view controller is in charge of this behavior. It configures the presented view controller, receives information from it, and eventually dismisses it. However, while it is being presented, the presented view controller’s view is temporarily added to the window’s view hierarchy. In Figure 1-13, a content view controller attached to the tab view presents a view controller to perform a task. The content controller is the presenting view controller, and the modal view controller is the presented view controller. Figure 1-13 Modal presentation by a content view View Controller Basics View Controllers Work Together to Create an App’s Interface 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 30When a view controller is presented, the portion of the screen that it coversis defined by a presentation context provided to it by another view controller. The view controller that provides the presentation context does not need be the same view controller that presented it. Figure 1-14 shows the same view controller hierarchy that is presented in Figure 1-13. You can see that the content view presented the view controller, but it did not provide the presentation context. Instead, the view controller was presented by the tab controller. Because of this, even though the presenting view controller only covers the portion of the screen provided to it by the tab view controller, the presented view controller uses the entire area owned by the tab view controller. Figure 1-14 The actual presentation is performed by the root view controller. Control Flow Represents Overall Coordination Between Content Controllers In an app with multiple view controllers, view controllers are usually created and destroyed throughout the lifetime of the app. During their lifetimes, the view controllers communicate with each other to present a seamless user experience. These relationships represent the control flow of your app. Most commonly, this control flow happens when a new view controller isinstantiated. Usually, a view controller is instantiated because of actions in another view controller. The first view controller, known as the source view controller directs the second view controller, the destination view controller. If the destination view controller presents data to the user, the source view controller usually provides that data. Similarly, if the source view controller needsinformation from the destination view controller, it isresponsible for establishing the connection between the two view controllers. Figure 1-15 shows the most common examples of these relationships. In the figure: ● A child of a navigation controller pushes another child onto the navigation stack. ● A view controller presents another view controller. View Controller Basics View Controllers Work Together to Create an App’s Interface 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 31● A view controller displays another view controller in a popover. Figure 1-15 Communication between source and destination view controllers Each controller is configured by the one preceding it. When multiple controllers work together, they establish a communication chain throughout the app. The control flow at each link in this chain is defined by the destination view controller. The source view controller uses the conventions provided by the destination view controller. ● The destination view controller provides properties used to configure its data and presentation. ● If the destination view controller needs to communicate with view controllers preceding it in the chain, it uses delegation. When the source view controller configures the destination view controller’s other properties, it is also expected to provide an object that implements the delegate’s protocol. The benefit of using this control flow convention is that there is a clean division of responsibilities between each pair ofsource and destination view controllers. Data flows down the path when the source view controller asksthe destination view controller to perform a task; the source view controller drivesthe process. For example, it might provide the specific data object that the destination controller should display. In the other direction, data flows up the path when a view controller needsto communicatesinformation back to the source controller that spawned it. For example, it might communicate when the task completes. Also, by consistently implementing this control flow model, you ensure that destination view controllers never know too much about the source view controller that configured them. When it does know about a view controller earlier in the chain, it knows only that the class implements the delegate protocol, not the class of the class. By keeping view controllersfrom knowing too much about each other, individual controllers become more reusable. For someone reading your code, a consistently implemented control flow model makes it easy to see the communication path between any pair of controllers. View Controller Basics View Controllers Work Together to Create an App’s Interface 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 32Storyboards Help You Design Your User Interface When you implement your app using storyboards, you use Interface Builder to organize your app’s view controllers and any associated views. Figure 1-16 shows an example interface layout from Interface Builder. The visual layout of Interface Builder allows you to understand the flow through your app at a glance. You can see what view controllers are instantiated by your app and their order of instantiation. But more than that, you can configure complex collections of views and other objects in the storyboard. The resulting storyboard is stored as a file in your project. When you build your project, the storyboards in your project are processed and copied into the app bundle, where they are loaded by your app at runtime. Figure 1-16 A storyboard diagram in Interface Builder Often, iOS can automatically instantiate the view controllersin yourstoryboard at the moment they are needed. Similarly, the view hierarchy associated with each controller is automatically loaded when it needs to be displayed. Both view controllers and views are instantiated with the same attributes you configured in Interface Builder. Because most of this behavior is automated for you, it greatly simplifies the work required to use view controllers in your app. The full details of creating storyboards are described in Xcode 4 User Guide . For now, you need to know some of the essential terminology used when implementing storyboards in your app. A scene represents an onscreen content area that is managed by a view controller. You can think of a scene as a view controller and its associated view hierarchy. View Controller Basics Storyboards Help You Design Your User Interface 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 33You create relationships between scenes in the same storyboard. Relationships are expressed visually in a storyboard as a connection arrow from one scene to another. Interface Builder usually infers the details of a new relationship automatically when you make a connection between two objects. Two important kinds of relationships exist: ● Containment represents a parent-child relationship between two scenes. View controllers contained in other view controllers are instantiated when their parent controller is instantiated. For example, the first connection from a navigation controller to another scene defines the first view controller pushed onto the navigation stack. This controller is automatically instantiated when the navigation controller is instantiated. An advantage to using containment relationships in a storyboard is that Interface Builder can adjust the appearance of the child view controller to reflect the presence of its ancestors. This allowsInterface Builder to display the content view controller as it appears in your final app. ● A segue represents a visual transition from one scene to another. At runtime, segues can be triggered by various actions. When a segue istriggered, it causes a new view controller to be instantiated and transitioned onscreen. Although a segue is always from one view controller to another, sometimes a third object can be involved in the process. This object actually triggersthe segue. For example, if you make a connection from a button in the source view controller’s view hierarchy to the destination view controller, when the user taps the button, the segue is triggered. When a segue is made directly from the source view controller to the destination view controller, it usually represents a segue you intend to trigger programatically. Different kinds of segues provide the common transitions needed between two different view controllers: ● A push segue pushes the destination view controller onto a navigation controller’s stack. ● A modal segue presents the destination view controller. ● A popover segue displays the destination view controller in a popover. ● A custom segue allows you to design your own transition to display the destination view controller. Segues share a common programming model. In this model, the destination controller is instantiated automatically by iOS and then the source view controller is called to configure it. This behavior matches the control flow model described in “Control Flow Represents Overall Coordination Between Content Controllers” (page 31). You can also create connections between a view controller and objects stored in the same scene. These outlets and actions enable you to carefully define the relationships between the view controller and its associated objects. Connections are not normally visible in the storyboard itself but can be viewed in the Connections Inspector of Interface Builder. View Controller Basics Storyboards Help You Design Your User Interface 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 34Whether you are working with view controllers provided by iOS, or with custom controllers you’ve created to show your app’s content, you use a similar set of techniques to actually work with the view controllers. The most common technique for working with view controllers is to place them inside a storyboard. Placing view controllers in a storyboard allows you to directly establish relationships between the view controllers in your app without writing code. You can see the flow of control—from controllers created when your app first launches, to controllers that are instantiated in response to a user’s actions. iOS manages most of this process by instantiating these view controllers only when the app needs them. Sometimes you may need to create a view controller by allocating and initializing it programmatically. When working with view controllers directly, you must write code that instantiates the view controller, configures it, and displays it. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 35 Using View Controllers in Your AppWorking with View Controllers in Storyboards Figure 2-1 shows an example of a storyboard. This storyboard includes view controllers, associated views, and connection arrows that establish relationships between the view controllers. In effect, this storyboard tells a story, starting with one scene and later showing others in response to a user’s actions. Figure 2-1 A storyboard holds a set of view controllers and associated objects A storyboard may designate one view controller to be the initial view controller. If a storyboard represents a specific workflow through part of your UI, the initial view controller represents the first scene in that workflow. You establish relationships from the initial view controller to other view controllers in the storyboard. In turn, you establish relationships from those view controllers to others, eventually connecting most or all of the storyboard’s scenes into a single connected graph. The type of relationship you establish determines when a connected view controller is instantiated by iOS, as follows: ● If the relationship is a segue, the destination view controller is instantiated when the segue is triggered. ● If the relationship represents containment, the child view controller is instantiated when its parent is instantiated. ● If the controller is not the destination or child of another controller, it is never instantiated automatically. You must instantiate it from the storyboard programmatically. Using View Controllers in Your App Working with View Controllers in Storyboards 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 36To identify a specific view controller or segue inside a storyboard, use Interface Builder to assign it an identifier string that uniquely identifies it. To programmatically load a view controller from the storyboard, you must assign it an identifier. Similarly, to trigger a segue programmatically, it must also be assigned an identifier. When a segue is triggered, that segue's identifier is passed to the source view controller, which uses it to determine which segue was triggered. For this reason, consider labeling every segue with an identifier. When you build an app using storyboards, you can use a single storyboard to hold all of its view controllers, or you can create multiple storyboards and implement a portion of the user interface in each. One storyboard in your app is almost always designated as the main storyboard. If there is a main storyboard, iOS loads it automatically; other storyboards must be explicitly loaded by your app. The Main Storyboard Initializes Your App’s User Interface The main storyboard is defined in the app’s Information property list file. If a main storyboard is declared in this file, then when your app launches, iOS performs the following steps: 1. It instantiates a window for you. 2. It loads the main storyboard and instantiates its initial view controller. 3. It assigns the new view controller to the window’s rootViewController property and then makes the window visible on the screen. Your app delegate is called to configure the initial view controller before it is displayed. The precise set of steps iOS uses to load the main storyboard is described in “Coordinating Efforts Between View Controllers” (page 98). Segues Automatically Instantiate the Destination View Controller A segue represents a triggered transition that brings a new view controller into your app’s user interface. Segues contain a lot of information about the transition, including the following: ● The object that caused the segue to be triggered, known as the sender ● The source view controller that starts the segue ● The destination view controller to be instantiated ● The kind of transition that should be used to bring the destination view controller onscreen ● An optional identifier string that identifies that specific segue in the storyboard When a segue is triggered, iOS takes the following actions: 1. It instantiates the destination view controller using the attribute values you provided in the storyboard. Using View Controllers in Your App Working with View Controllers in Storyboards 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 372. It gives the source view controller an opportunity to configure the new controller. 3. It performs the transition configured in the segue. Note: When you implement custom view controllers, each destination view controller declares public properties and methods used by the source view controller to configure its behavior. In return, your custom source view controllers override storyboard methods provided by the base class to configure the destination view controller. The precise details are in “Coordinating Efforts Between View Controllers” (page 98). Triggering a Segue Programmatically A segue is usually triggered because an object associated with the source view controller, such as a control or gesture recognizer, triggered the segue. However, a segue can also be triggered programmatically by your app, as long as the segue has an assigned identifier. For example, if you are implementing a game, you might trigger a segue when a match ends. The destination view controller then displays the match’s final scores. You programmatically trigger the segue by calling the source view controller’s performSegueWithIdentifier:sender: method, passing in the identifier for the segue to be triggered. You also pass in another object that acts as the sender. When the source controller is called to configure the destination view controller, both the sender object and the identifier for the segue are provided to it. Listing 2-1 shows a simple method that triggers a segue. This example is a portion of a larger example described in “Creating an Alternate Landscape Interface” (page 80). In this abbreviated form, you can see that the view controller is receiving an orientation notification. When the view controller is in portrait mode and the device is rotated into landscape orientation, the method uses a segue to present a different view controller onscreen. Because the notification object in this case provides no useful information for performing the segue command, the view controller makes itself the sender. Listing 2-1 Triggering a segue programmatically - (void)orientationChanged:(NSNotification *)notification { UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation; if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView) { [self performSegueWithIdentifier:@"DisplayAlternateView" sender:self]; isShowingLandscapeView = YES; } Using View Controllers in Your App Working with View Controllers in Storyboards 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 38// Remainder of example omitted. } If a segue can be triggered only programmatically, you usually draw the connection arrow directly from the source view controller to the destination view controller. Instantiating a Storyboard’s View Controller Programmatically You may want to programmatically instantiate a view controller without using a segue. A storyboard is still valuable, because you can use it to configure the attributes of the view controller as well as its view hierarchy. However, if you do instantiate a view controller programmatically, you do not get any of the behavior of a segue. To display the view controller, you must implement additional code. For this reason, you should rely on segues where possible and use this technique only when needed. Here are the steps your code needs to implement: 1. Obtain a storyboard object (an object of the UIStoryboard class). If you have an existing view controller instantiated from the same storyboard, read its storyboard property to retrieve the storyboard. To load a different storyboard, call the UIStoryboard class’s storyboardWithName:bundle: class method, passing in the name of the storyboard file and an optional bundle parameter. 2. Call the storyboard object’s instantiateViewControllerWithIdentifier: method, passing in the identifier you defined for the view controller when you created it in Interface Builder. Alternatively, you can use the instantiateInitialViewController method to instantiate the initial view controller in a storyboard, without needing to know its identifier. 3. Configure the new view controller by setting its properties. 4. Display the new view controller. See “Displaying a View Controller’s Contents Programmatically” (page 41). Listing 2-2 shows an example of this technique. It retrieves the storyboard from an existing view controller and instantiates a new view controller using it. Listing 2-2 Instantiating another view controller inside the same storyboard - (IBAction)presentSpecialViewController:(id)sender { UIStoryboard *storyboard = self.storyboard; SpecialViewController *svc = [storyboard instantiateViewControllerWithIdentifier:@"SpecialViewController"]; Using View Controllers in Your App Working with View Controllers in Storyboards 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 39// Configure the new view controller here. [self presentViewController:svc animated:YES completion:nil]; } Listing 2-3 shows another frequently used technique. This example loads a new storyboard and instantiates its initial view controller. It uses this view controller as the root view controller for a new window being placed on an external screen. To display the returned window, your app calls the window’s makeKeyAndVisible method. Listing 2-3 Instantiating a view controller from a new storyboard - (UIWindow*) windowFromStoryboard: (NSString*) storyboardName onScreen: (UIScreen*) screen { UIWindow *window = [[UIWindow alloc] initWithFrame:[screen bounds]]; window.screen = screen; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil]; MainViewController *mainViewController = [storyboard instantiateInitialViewController]; window.rootViewController = mainViewController; // Configure the new view controller here. return window; } Transitioning to a New Storyboard Requires a Programmatic Approach Segues connect only scenes that are stored in the same storyboard. To display a view controller from another storyboard, you must explicitly load the storyboard file and instantiate a view controller inside it. There is no requirement that you create multiple storyboards in your app. Here, though, are a few cases where multiple storyboards might be useful to you: Using View Controllers in Your App Working with View Controllers in Storyboards 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 40● You have a large programming team, with different portions of the user interface assigned to different parts of the team. In this case, each subteam owns a storyboard limiting the number of team members working on any specific storyboard’s contents. ● You purchased or created a library that predefines a collection of view controller types; the contents of those view controllers are defined in a storyboard provided by the library. ● You have content that needs to be displayed on an external screen. In this case, you might keep all of the view controllers associated with the alternate screen inside a separate storyboard. An alternative pattern for the same scenario is to write a custom segue. Containers Automatically Instantiate Their Children When a container in a storyboard is instantiated, its children are automatically instantiated at the same time. The children must be instantiated at the same time to give the container controller some content to display. Similarly, if the child that was instantiated is also a container, its children are also instantiated, and so on, until no more containment relationships can be traced to new controllers. If you place a content controller inside a navigation controller inside a tab bar controller, when the tab bar is instantiated, the three controllers are simultaneously instantiated. The container and its descendants are instantiated before your view controller is called to configure them. Your source view controller (or app delegate) can rely on all the children being instantiated. This instantiation behavior is important, because your custom configuration code rarely configures the container(s). Instead, it configures the content controllers attached to the container. Instantiating a Non-Storyboard View Controller To create a view controller programmatically without the use of the storyboard, you use Objective-C code to allocate and initialize the view controller. You gain none of the benefits of storyboards, meaning you have to implement additional code to configure and display the new view controller. Displaying a View Controller’s Contents Programmatically For a view controller’s content to be useful, it needs to be displayed on screen. There are several options for displaying a view controller’s contents: ● Make the view controller the root view controller of a window. ● Make it a child of a visible container view controller. ● Present it from another visible view controller. Using View Controllers in Your App Instantiating a Non-Storyboard View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 41● Present it using a popover (iPad only). In all cases, you assign the view controller to another object—in this case, a window, a view controller, or a popover controller. This object resizes the view controller’s view and adds it to its own view hierarchy so that it can be displayed. Listing 2-4 showsthe most common case, which isto assign the view controller to a window. This code assumes that a storyboard is not being used, so it performs the same steps that are normally done on your behalf by the operating system: It creates a window and setsthe new controller asthe root view controller. Then it makes the window visible. Listing 2-4 Installing the view controller as a window’s root view controller - (void)applicationDidFinishLaunching:(UIApplication *)application { UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; levelViewController = [[LevelViewController alloc] init]; window.rootViewController = levelViewController; [window makeKeyAndVisible]; } Important: Never install the view controller’s view into a view hierarchy directly. To present and manage views properly, the system makes a note of each view (and its associated view controller) that you display. It uses this information later to report view controller–related events to your app. For example, when the device orientation changes, a window uses this information to identify the frontmost view controller and notify it of the change. If you incorporate a view controller’s view into your hierarchy by other means, the system may handle these events incorrectly. If you are implementing your own custom container controller, you add another view controller’s view to your own view hierarchy, but you also create a parent-child relationship first. This ensures that events are delivered correctly. See “Creating Custom Container View Controllers” (page 111). Using View Controllers in Your App Displaying a View Controller’s Contents Programmatically 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 42Custom content view controllers are the heart of your app. You use them to present your app’s unique content. All apps need at least one custom content view controller. Complex apps divide the workload between multiple content controllers. A view controller has many responsibilities. Some of these responsibilities are things that iOS requires the view controller to do. Other responsibilities are things you assign to the view controller when you define its role in your app. Anatomy of a Content View Controller The UIViewController class provides the fundamental infrastructure for implementing all custom view controllers. You define a custom subclass of UIViewController. That subclass provides the necessary code to populate views with data and respond to user actions. When you want to make adjustments to the default behavior of the view controller, you override methods of the UIViewController class. Your view controller may also interact with other UIKit classes to implement the behavior you want. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 43 Creating Custom Content View ControllersFigure 3-1 shows some of the key objects associated directly with a content view controller. These are the objectsthat are essentially owned and managed by the view controller itself. The view (accessible via the view property) is the only object that must be provided, although most view controllers have additional subviews attached to this view as well as custom objects containing the data they need to display. Figure 3-1 Anatomy of a content view controller View View View View Content view controller Custom data objects When you design a new view controller, it potentially has many responsibilities. Some of those responsibilities look inward, to the views and other objects it controls. Other responsibilities look outward to other controllers. The following sections enumerate many of the common responsibilities for a view controller. View Controllers Manage Resources Some objects are instantiated when the view controller is initialized and are disposed of when your view controller is released. Other objects, like views, are needed only when the view controller’s contents are visible onscreen. As a result, view controllers use resources efficiently and should be prepared to release resources when memory is scarce. Properly implementing this behavior in your app's view controllers makes it so your app uses memory and other resources—such as CPU, GPU, and battery—more efficiently. See “Resource Management in View Controllers” (page 56). Creating Custom Content View Controllers Anatomy of a Content View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 44View Controllers Manage Views View controllers manage their view and its subviews, but the view’s frame—its position and size in its parent’s view—is often determined by other factors, including the orientation of the device, whether or not the status bar is visible and even how the view controller’s view is displayed in the window. Your view controller should be designed to layout its view to fit the frame provided to it. View management has other aspects as well. Your view controller is notified when its view is about to appear and disappear from the screen. Your view controller can use this notification to perform other actions necessary to its operation. See “Resizing the View Controller’s Views” (page 69), “Supporting Multiple Interface Orientations” (page 74), “Responding to Display-Related Notifications” (page 66). View Controllers Respond to Events Your view controller is often the central coordinating object for its views and controls. Typically, you design your user interface so that controls send messages to the controller when a user manipulates them. Your view controller is expected to handle the message, making any necessary changes to the views or data stored in the view controller. Your view controller also participates in the responder chain used to deliver events to your app. You can override methodsin your view controller classto have it participate directly in event handling. View controllers also are good objects to implement other behaviors—such as responding to system notifications, timers or events specific to your app. See “Using View Controllers in the Responder Chain” (page 72). View Controllers Coordinate with Other Controllers Although a view controller may create and manage many other objects, it does not usually need to expose these objects publicly to inspection or modification. It may collaborate with other objects (especially other view controllers), but it should expose the fewest number of properties and methods necessary to allow its collaborators to communicate with it. Exposing too many implementation details in your view controller class makes it difficult to modify your view controller’s implementation. Collaborators that rely on these implementation details would need to be modified to continue to work with your view controller class. See “Coordinating Efforts Between View Controllers” (page 98). Creating Custom Content View Controllers Anatomy of a Content View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 45View Controllers Often Work with Containers If your view controller is placed inside a container view controller, the container imposes additional constraints, as shown in Figure 3-2. The container may ask your view controller to provide other objects used to configure the container’s user interface. For example, a content view controller placed inside a tab view controller provides a tab bar item to display for that tab. Figure 3-2 A container view controller imposes additional demands on its children The properties used to configure the containers provided by UIKit are defined by the UIViewController class. For more information on specific types of containers and the properties you configure to support them, see View Controller Catalog for iOS . View Controllers May Be Presented by Other View Controllers Some view controllers you design are intended to be presented by other view controllers. You might present your view controller directly, or you might make it a child of a container view controller and present the container instead. When presented, it moves onscreen, remaining there until it is dismissed. There are several reasons you might present a view controller: Creating Custom Content View Controllers Anatomy of a Content View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 46● To gather information from the user immediately. ● To present some content temporarily. ● To change work modes temporarily. ● To implement alternate interfaces for different device orientations. ● To present a new view hierarchy with a specific type of animated transition (or no transition). Most of these reasons involve interrupting your app’s workflow temporarily in order to gather or display some information. In almost all cases, the presented view controller implements a delegate. The presented view controller uses the delegate to communicate with the presenting view controller. After your app has the information it needs (or the user finishes viewing the presented information), the presented view controller communicates this back to the presenting view controller. The presenting view controller dismisses the presented view controller to return the app to its previous state. See “Presenting View Controllers from Other View Controllers” (page 88). Designing Your Content View Controller Before writing any code in your view controller, you should be able to answer some basic questions about how you intend to use it. The questions provided below are designed to help you narrow the focus of your view controller and to help you understand the role it plays in your app. In particular, it helps you identify connections—usually to other controllers—your view controller needs to perform its tasks. ● Are you using a storyboard to implement the view controller? ● When is it instantiated? ● What data does it show? ● What tasks does it perform? ● How is its view displayed onscreen? ● How does it collaborate with other view controllers? Your answers to these questions need not be precise if you are still working out the role it plays. Still, it helps to have a general sense of what your view controller does and how other objects interact with it. The questions above don’t ask you to define the appearance of your view controller or to be precise about the implementation details of how it performs the tasks you’ve assigned to it. Those are important questions you need to answer, but neither of these things should affect your view controller’s public interface. You want the flexibility to be able to change the visual design of your view controller without changing the class declaration that defines how other controllers collaborate with it. Creating Custom Content View Controllers Designing Your Content View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 47Use a Storyboard to Implement Your View Controller You might consider whether or not to use a storyboard as an implementation detail, but the approach you take affects how you implement the view controller and how other objects collaborate with it. You always use a storyboard unless you have a strong reason not to. When you use storyboards: ● iOS usually instantiates your view controller for you automatically. ● To finish instantiating it, you override its awakeFromNib method. ● Other objects configure it through its properties. ● You create its view hierarchy and other related objects in Interface Builder. These objects are loaded automatically when the view is needed. ● Relationships with other view controllers are created in the storyboard. If you design your view controller to be used programmatically: ● The view controller is instantiated by allocating and initializing it. ● You create an custom initialization method to initialize the view controller. ● Other objects configure the view controller using itsinitialization method and by configuring its properties. ● You override the loadView method to programmatically create and configure its view hierarchy. ● Relationships with other view controllers are created by writing code. Know When Your Controller Is Instantiated Knowing when your view controller is instantiated usually implies other details for how your app operates. For example, you might know that your view controller is alwaysinstantiated by the same object. Often the objects that instantiate view controllers are themselves view controllers; this is almost always the case in an app that uses storyboards. In any case, knowing when, why, and by what object your view controller is instantiated gives you insight into the information exchanged between your view controller and the object that created it. Know What Data Your View Controller Shows and Returns When you answer these two questions, you are working to understand the data model for your app and also whether that data needs to be exchanged between your view controllers. Here are some common patterns you should expect to see in your view controllers: Creating Custom Content View Controllers Designing Your Content View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 48● The view controller receives data from another controller and displays it, without offering a way to edit it. No data is returned. ● The view controller allows the user to enter new data. After the user finishes editing the data, it sends the new data to another controller. ● The view controller receives data from another controller and allows the user to edit it. After the user finishes editing the data, it sends the new data to another controller. ● The view controller doesn’t send or receive data. Instead, it shows static views. ● The view controller doesn’tsend or receive data. Instead, itsimplementation loadsits data without exposing this mechanism to other view controllers. For example, the GKAchievementViewController class has built-in functionality to determine which player is authenticated on the device. It also knows how to load that player’s data from Game Center. The presenting view controller does not need to know what data is loaded or how it was loaded. You are not constrained to use only these designs. When data travels into or out of your view controller, consider defining a data model class to hold the data to be transferred to the new controller. For example, in Your Second iOS App: Storyboards, the master controller uses a BirdSighting object to send data associated with a sighting to the detail controller. Using an object for this makes it easier to update the data to include additional properties without changing the method signatures in your controller classes. Know What Tasks Your Controller Allows the User to Perform Some view controllers allow users to view, create, or edit data. Other view controllers allow users to navigate to otherscreens of content. And some allow usersto perform tasks provided by the view controller. For example, the MFMailComposeViewController class allows a user to compose and send emails to other users. It handles the low-level details of sending mail messages. As you determine which tasks your view controller performs, decide how much control over those tasks your view controller exposes to other controllers. Many view controllers can perform tasks without exposing configuration data to other controllers. For example, the GKAchievementViewController class displays achievements to the user without exposing any properties to configure how it loads or presents its data. The MFMailComposeViewController class presents a slightly different scenario by exposing some properties that another controller can use to configure the initial content it displays. After that, a user can edit the content and send the email message without giving other controller objects a chance to affect that process. Creating Custom Content View Controllers Designing Your Content View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 49Know How Your View Controller Is Displayed Onscreen Some view controllers are designed to be root view controllers. Others expect to be presented by another view controller or placed in a container controller. Occasionally, you design controllers that can be displayed in multiple ways. For example, a split view controller’s master view is displayed in the split view in landscape mode and in a popover control in portrait mode. Knowing how your view controller is displayed gives you insight into how its view issized and placed onscreen. It also affects other areas, such as determining what other controllers your view controller collaborates with. Know How Your Controller Collaborates with Other Controllers By this point, you already know some things about collaboration. For example, if your view controller is instantiated from a segue, then it probably collaborates with the source view controller that configures it. And if your controller is a child of a container, then it collaborates with the container. But there are relationships in the other direction as well. For example, your view controller might defer some of its work and hand it off to another view controller. It might even exchange data with an existing view controller. With all of these connections, your view controller provides an interface that other controllers use, or it is aware of other controllers and it uses their interfaces. These connections are essential to providing a seamless experience, but they also represent design challenges because they introduce dependencies between classes in your app. Dependencies are a problem because they make it more difficult to change any one class in isolation from the other classes that make up your app. For this reason, you need to balance the needs of your app now against the potential need to keep your app design flexible enough to change later. Examples of Common View Controller Designs Designing a new view controller can be challenging. It helps to look at existing designs and understand what they do and why. This next section talks about some common view controller styles used in iOS apps. Each example includes a description of the role the view controller plays, a brief description of how it works at a high level, and one possible list of answers to the design questions listed above. Example: Game Title Screen Mission Statement A view controller that allows the user to select between different styles of game play. Creating Custom Content View Controllers Examples of Common View Controller Designs 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 50Description When a game is launched, it rarely jumps right into the actual game. Instead, it displays a title screen that identifies the game and presents a set of game variants to the player. For example, a game might offer buttons that allow a player to start a single player or multiplayer game. When the user selects one of the options, the app configures itself appropriately and launches into its gameplay. A title screen is interesting specifically because its contents are static; they don’t need data from another controller. As such, this view controller is almost entirely self-sufficient. It does, however, know about other view controllers, because it instantiates other view controllers to launch its gameplay. Design ● Are you using a storyboard to implement the view controller? Yes. ● When is it instantiated? This view controller is the initial scene in the main storyboard. ● What data does it show? This class displays preconfigured controls and images; it does not present user data. It does not include configurable properties. ● What tasks does it perform? When a user taps on a button, it triggers a segue to instantiate another view controller. Each segue is identified so that the appropriate game play can be configured. ● How is its view displayed onscreen? It isinstalled automatically asthe root view controller of the window. ● How does it collaborate with other view controllers? It instantiates another view controller to present a gameplay screen. When gameplay ends, the other view controller sends a message to the title screen controller to inform it that play has ended. The title screen controller then dismisses the other view controller. Alternative Design Considerations The default answers assume that no user data is displayed. Some games include player data to configure the views or controls. For example: ● You might want the view controller to display the user’s Game Center alias. ● You might want it to enable or disable buttons based on whether the device is connected to Game Center. ● You might want it to enable or disable buttons based on In-App Purchase items the user has purchased. When these additional items are added to the design, the view controller takes on a more traditional role. It might receive data objects or data controllers from the app delegate so that it can query and update this state as necessary. Or, as it is the root view controller for the window, you might simply implement those behaviors directly in the title screen controller. The actual design likely depends on how flexible you need your code to be. Creating Custom Content View Controllers Examples of Common View Controller Designs 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 51Example: Master View Controller Mission Statement The initial view controller of a navigation controller, used to display a list of the app’s available data objects. Description A master view controller is a very common part of a navigation-based app. For example, Your Second iOS App: Storyboards uses a master view to display the list of bird sightings. When a user selects a sighting from the list, the master view controller pushes a new detail controller onto the screen. Because this view controller displays a list of items, it subclasses UITableViewController instead of UIViewController. Design ● Are you using a storyboard to implement the view controller? Yes. ● When is it instantiated? Asthe root view controller of a navigation controller, it isinstantiated at the same time as its parent. ● What data does it show? A high-level view of the app’s data. It implements properties that the app delegate uses to provide data to it. For example, the bird watching app provides a custom data controller object to the master view controller. ● What tasks does it perform? It implements an Add button to allow users to create new records. ● How is its view displayed onscreen? It is a child of a navigation controller. ● How does it collaborate with other view controllers? When the user taps on an item in the list, it uses a push segue to show a detail controller. When the user taps on the Add button, it uses a modal segue to present a new view controller that edits a new record. It receives data back from this modal view controller and sends this data to the data controller to create a new bird sighting. Alternative Design Considerations A navigation controller and an initial view controller is used when building an iPhone app. When designing the same app for the iPad, the master view controller is a child of a split view controller instead. Most other design decisions stay the same. Creating Custom Content View Controllers Examples of Common View Controller Designs 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 52Example: Detail View Controller Mission Statement A controller pushed onto a navigation stack to display the details for a list item selected from the master view controller. Description The detail view controller represents a more detailed view of a list item displayed by the master view controller. As with the master view controller, the list appears inside a nav bar interface. When the user finishes viewing the item they click a button in the nav bar to return to the master view. Your Second iOS App: Storyboards uses the UITableViewController class to implement its detail view. It uses a static table cells, each of which accesses one piece of the bird sighting data. A static table view is a good way to implement this design. Design ● Are you using a storyboard to implement the view controller? Yes. ● When is it instantiated? It is instantiated by a push segue from the master view controller. ● What data does it show? Itshowsthe data stored in a custom data object. It declares properties configured by the source view controller to provide this data. ● What tasks does it perform? It allows the user to dismiss the view. ● How is its view displayed onscreen? It is a child of a navigation controller. ● How does it collaborate with other view controllers? It receives data from the master view controller. Alternative Design Considerations A navigation controller is most often used when building an iPhone app. When designing the same app for the iPad, the detail view controller is a child of a split view controller instead. Many of the other implementation details stay the same. If your app needs more custom view behavior, it mightsubclassthe UIViewController class and implement its own custom view hierarchy. Creating Custom Content View Controllers Examples of Common View Controller Designs 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 53Example: Mail Compose View Controller Mission Statement A view controller that allows the user to compose and send an email. Description The Message UI framework provides the MFMailComposeViewController class. This class allows a user to compose and send an email. This view controller is interesting because it does more than simply show or edit data—it actually sends the email. Another interesting design choice in this class is that it allows an app to provide an initial configuration for the email message. After the initial configuration has been presented, the user can override these choices before sending the mail. Design ● Are you using a storyboard to implement the view controller? No. ● When is it instantiated? It is instantiated programmatically. ● What data does it show? It shows the various parts of an email message, including a recipients list, title, attachments and the email message itself. The class provides propertiesthat allow another view controller to preconfigure the email message. ● What tasks does it perform? It sends email. ● How is its view displayed onscreen? The view controller is presented by another view controller. ● How does it collaborate with other view controllers? It returns status information to its delegate. This status allows the presenting view controller to know whether an email was sent. Implementation Checklist for Custom Content View Controllers For any custom content view controllers you create, there are a few tasks that you must have your view controller handle: ● You must configure the view to be loaded by your view controller. Your custom class may need to override specific methods to manage how its view hierarchy is loaded and unloaded. These same methods might manage other resources that are created at the same time. See “Resource Management in View Controllers” (page 56). Creating Custom Content View Controllers Implementation Checklist for Custom Content View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 54● You must decide which device orientations your view controller supports and how it reacts to a change in device orientation; see “Supporting Multiple Interface Orientations” (page 74). As you implement your view controller, you will likely discover that you need to define action methods or outlets to use with its views. For example, if the view hierarchy contains a table, you probably want to store a pointer to that table in an outletso that you can accessit later. Similarly, if your view hierarchy contains buttons or other controls, you probably want those controls to call an associated action method on the view controller. As you iterate through the definition of your view controller class, you may therefore find that you need to add the following items to your view controller class: ● Declared properties pointing to the objects containing the data to be displayed by the corresponding views ● Public methods and propertiesthat expose your view controller’s custom behavior to other view controllers ● Outlets pointing to views in the view hierarchy with which your view controller must interact ● Action methods that perform tasks associated with buttons and other controls in the view hierarchy Important: Clients of your view controller class do not need to know what views your view controller displays or what actions those views might trigger. Whenever possible, outlets and actions should be declared in a category inside your class’s implementation file. For example, if your class is named MyViewController, you implement the category by adding the following declaration to MyViewController.m: @interface MyViewController() // Outlets and actions here. @end @implementation MyViewController // Implementation of the privately declared category must go here. @end When you declare a category without a name, the properties and actions must be implemented in the same implementation block as any methods or properties declared in your public interface. The outlets and actions defined in the private category are visible to Interface Builder, but not to other classes in your app. This strategy allows you to gain the benefits of Interface Builder without exposing your class’s secrets. If another class needs access to your view controller’s functionality, add public methods and properties to access this functionality instead. Creating Custom Content View Controllers Implementation Checklist for Custom Content View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 55View controllers are an essential part of managing your app’s resources. View controllers allow you to break your app up into multiple parts and instantiate only the parts that are needed. But more than that, a view controller itself manages different resources and instantiates them at different times. For example, a view controller’s view hierarchy is instantiated only when the view is accessed; typically, this occurs only when the view is displayed on screen. If multiple view controllers are pushed onto a navigation stack at the same time, only the topmost view controller’s contents are visible, which means only its views are accessed. Similarly, if a view controller is not presented by a navigation controller, it does not need to instantiate its navigation item. By deferring most resource allocation until it is needed, view controllers use less resources. When memory available to the app runs low, all view controllers are automatically notified by the system. This allows the view controller to purge caches and other objects that can be easily recreated later when memory is more plentiful. The exact behavior varies depending on which version of iOS your app is running on, and this has implications for your view controller design. Carefully managing the resources associated with your view controllers is critical to making your app run efficiently. You should also prefer lazy allocation; objects that are expensive to create or maintain should be allocated later and only when needed. For this reason, your view controllers should separate objects needed throughout the lifetime of the view controller from objects that are only necessary some of the time. When your view controller receives a low-memory warning, it should be prepared to reduce its memory usage if it is not visible onscreen. Initializing a View Controller When a view controller is first instantiated, it creates or loads objects it needs through its lifetime. It should not create its view hierarchy or objects associated with displaying content. It should focus on data objects and objects needed to implement its critical behaviors. Initializing a View Controller Loaded from a Storyboard When you create a view controller in a storyboard, the attributes you configure in Interface Builder are serialized into an archive. Later, when the view controller isinstantiated, this archive isloaded into memory and processed. The result is a set of objects whose attributes match those you set in Interface Builder. The archive is loaded 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 56 Resource Management in View Controllersby calling the view controller’s initWithCoder: method. Then, the awakeFromNib method is called on any object that implements that method. You use this method to perform any configuration steps that require other objects to already be instantiated. For more on archiving and archiving, see Archives and Serializations Programming Guide . Initializing View Controllers Programmatically If a view controller allocatesitsresources programmatically, create a custom initialization method that isspecific to your view controller. This method should call the super class’s init method and then perform any class specific initialization. In general, do not write complex initialization methods. Instead, implement a simple initialization method and then provide properties for clients of your view controller to configure its behaviors. A View Controller Instantiates Its View Hierarchy When Its View is Accessed Whenever some part of your app asks the view controller for its view object and that object is not currently in memory, the view controller loads the view hierarchy into memory and stores it in its view property for future reference. The steps that occur during the load cycle are: 1. The view controller calls its loadView method. The default implementation of the loadView method does one of two things: ● If the view controller is associated with a storyboard, it loads the views from the storyboard. ● If the view controller is not associated with a storyboard, an empty UIView object is created and assigned to the view property. 2. The view controller callsits viewDidLoad method, which enables yoursubclassto perform any additional load-time tasks. Resource Management in View Controllers A View Controller Instantiates Its View Hierarchy When Its View is Accessed 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 57Figure 4-1 shows a visual representation of the load cycle, including several of the methods that are called. Your app can override both the loadView and the viewDidLoad methods as needed to facilitate the behavior you want for your view controller. For example, if your app does not use storyboards but you want additional views to be added to the view hierarchy, you override the loadView method to instantiate these views programatically. Figure 4-1 Loading a view into memory Resource Management in View Controllers A View Controller Instantiates Its View Hierarchy When Its View is Accessed 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 58Loading a View Controller’s View from a Storyboard Most view controllersload their view from an associated storyboard. The advantage of using storyboardsisthat they allow you to lay out and configure your views graphically, making it easier and faster to adjust your layout. You can iterate quickly through different versions of your user interface to end up with a polished and refined design. Creating the View in Interface Builder Interface Builder is part of Xcode and provides an intuitive way to create and configure the views for your view controllers. Using Interface Builder, you assemble views and controls by manipulating them directly, dragging them into the workspace, positioning them, sizing them, and modifying their attributes using an inspector window. The results are then saved in a storyboard file, which stores the collection of objects you assembled along with information about all the customizations you made. Configuring the View Display Attributes in Interface Builder To help you layout the contents of your view properly, Interface Builder provides controls that let you specify whether the view has a navigation bar, a toolbar, or other objectsthat might affect the position of your custom content. If the controller is connected to container controllersin the storyboard, it can infer these settingsfrom the container, making it easier to see exactly how it should appear at runtime. Configuring Actions and Outlets for Your View Controller Using Interface Builder, you create connections between the views in your interface and your view controller. Listing 4-1 shows the declaration of a custom MyViewController class’s two custom outlets (designated by the IBOutlet keyword) and a single action method (designated by the IBAction return type). The declarations are made in a category inside the implementation file. The outlets store references to a button and a text field in the storyboard, while the action method responds to taps in the button. Listing 4-1 Custom view controller class declaration @interface MyViewController() @property (nonatomic) IBOutlet id myButton; @property (nonatomic) IBOutlet id myTextField; - (IBAction)myAction:(id)sender; @end Resource Management in View Controllers A View Controller Instantiates Its View Hierarchy When Its View is Accessed 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 59Figure 4-2 shows the connections you would create among the objects in such a MyViewController class. Figure 4-2 Connections in the storyboard When the previously configured MyViewController class is created and presented, the view controller infrastructure automatically loads the views from the storyboard and reconfigures any outlets or actions. Thus, by the time the view is presented to the user, the outlets and actions of your view controller are set and ready to be used. This ability to bridge between your runtime code and your design-time resource files is one of the things that makes storyboards so powerful. Creating a View Programmatically If you prefer to create views programmatically, instead of using a storyboard, you do so by overriding your view controller’s loadView method. Your implementation of this method should do the following: 1. Create a root view object. The root view contains all other views associated with your view controller. You typically define the frame for this view to match the size of the app window, which itself should fill the screen. However, the frame is adjusted based on how your view controller is displayed. See “Resizing the View Controller’s Views” (page 69). You can use a generic UIView object, a custom view you define, or any other view that can scale to fill the screen. 2. Create additional subviews and add them to the root view. Resource Management in View Controllers A View Controller Instantiates Its View Hierarchy When Its View is Accessed 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 60For each view, you should: a. Create and initialize the view. b. Add the view to a parent view using the addSubview: method. 3. If you are using auto layout, assign sufficient constraints to each of the views you just created to control the position and size of your views. Otherwise, implement the viewWillLayoutSubviews and viewDidLayoutSubviews methods to adjust the frames of the subviews in the view hierarchy. See “Resizing the View Controller’s Views” (page 69). 4. Assign the root view to the view property of your view controller. Listing 4-2 shows an example implementation of the loadView method. This method creates a pair of custom views in a view hierarchy and assigns them to the view controller. Listing 4-2 Creating views programmatically - (void)loadView { CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame]; UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame]; contentView.backgroundColor = [UIColor blackColor]; self.view = contentView; levelView = [[LevelView alloc] initWithFrame:applicationFrame viewController:self]; [self.view addSubview:levelView]; } Note: When overriding the loadView method to create your views programmatically, you should not call super. Doing so initiates the default view-loading behavior and usually just wastes CPU cycles. Your own implementation of the loadView method should do all the work that is needed to create a root view and subviewsfor your view controller. For more information on the view loading process, see “A View Controller Instantiates Its View Hierarchy When Its View is Accessed” (page 57). Managing Memory Efficiently When it comes to view controllers and memory management, there are two issues to consider: ● How to allocate memory efficiently Resource Management in View Controllers Managing Memory Efficiently 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 61● When and how to release memory Although some aspects of memory allocation are strictly yours to decide, the UIViewController class provides some methods that usually have some connection to memory management tasks. Table 4-1 lists the places in your view controller object where you are likely to allocate or deallocate memory, along with information about what you should be doing in each place. Table 4-1 Places to allocate and deallocate memory Task Methods Discussion Your custom initialization method (whether it is named init or something else) is always responsible for putting your view controller object in a known good state. This includes allocating whatever data structures are needed to ensure proper operation. Allocating critical Initialization methods data structures required by your view controller Overriding the loadView method is required only if you intend to create your views programmatically. If you are using storyboards, the views are loaded automatically from the storyboard file. Creating your view loadView objects Although you are free to use other designs, consider using a pattern similar the loadView method. Create a property that holds the method and a matched method to initialize the object. When the property is read and its value is nil, call the associated load method. Custom properties and methods Creating custom objects Data objects are typically provided by configuring your view controller’s properties. Any additional data objects your view controller wants to create should be done by overriding the viewDidLoad method. By the time this method is called, your view objects are guaranteed to exist and to be in a known good state. Allocating or viewDidLoad loading data to be displayed in your view Use this method to deallocate all noncritical objects associated with your view controller. On iOS 6, you can also use this method to release references to view objects. didReceiveMemoryWarning Responding to low-memory notifications Resource Management in View Controllers Managing Memory Efficiently 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 62Task Methods Discussion Override this method only to perform any last-minute cleanup of your view controller class. Objects stored in instance variables and properties are automatically released; you do not need to release them explicitly. Releasing critical dealloc data structures required by your view controller On iOS 6 and Later, a View Controller Unloads Its Own Views When Desired The default behavior for a view controller is to load its view hierarchy when the view property is first accessed and thereafter keep it in memory until the view controller is disposed of. The memory used by a view to draw itself onscreen is potentially quite large. However, the system automatically releasesthese expensive resources when the view is not attached to a window. The remaining memory used by most views is small enough that it is not worth it for the system to automatically purge and recreate the view hierarchy. You can explicitly release the view hierarchy if that additional memory is necessary for your app. Listing 4-3 overrides the didReceiveMemoryWarning method to accomplish this. First, is calls the superclass’s implementation to get any required default behavior. Then, it cleans up the view controller’s resources. Finally, it teststo see if the view controller’s view is not onscreen. If the view is associated with a window, then it cleans up any of the view controller’s strong references to the view and its subviews. If the views stored data that needs to be recreated, the implementation of this method should save that data before releasing any of the references to those views. Listing 4-3 Releasing the views of a view controller not visible on screen - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Add code to clean up any of your own resources that are no longer necessary. if ([self.view window] == nil) { // Add code to preserve data stored in the views that might be // needed later. // Add code to clean up other strong references to the view in // the view hierarchy. self.view = nil; } Resource Management in View Controllers Managing Memory Efficiently 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 63The next time the view property is accessed, the view is reloaded exactly as it was the first time. On iOS 5 and Earlier, the System May Unload Views When Memory Is Low In earlier versions of iOS, the system automatically attempts to unload a view controller’s views when memory is low. The steps that occur during the unload cycle are as follows: 1. The app receives a low-memory warning from the system. 2. Each view controller calls its didReceiveMemoryWarning method. If you override this method, you should use it to release any memory or objects that your view controller object no longer needs. You must call super at some point in your implementation to ensure that the default implementation runs. On iOS 5 and earlier, the default implementation attempts to release the view. On iOS 6 and later, the default implementation exits. 3. If the view cannot be safely released (for example, it is visible onscreen), the default implementation exits. 4. The view controller calls its viewWillUnload method. A subclass typically overrides this method when it needs to save any view properties before the views are destroyed. 5. It sets its view property to nil. 6. The view controller callsits viewDidUnload method. A subclasstypically overridesthis method to release any strong references it has to those views. Resource Management in View Controllers Managing Memory Efficiently 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 64Figure 4-3 shows a visual representation of the unload cycle for a view controller. Figure 4-3 Unloading a view from memory Resource Management in View Controllers Managing Memory Efficiently 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 65When the visibility of a view controller’s view changes, the view controller callssome built-in methodsto notify subclasses of the changes. You can override these methodsto override how yoursubclassreactsto the change. For example, you can use these notifications to change the color and orientation of the status bar so that it matches the presentation style of the view that is about to be displayed. Responding When a View Appears Figure 5-1 shows the sequence of events that occurs when a view controller’s view is added to a window’s view hierarchy. The viewWillAppear: and viewDidAppear: methods give subclasses a chance to perform any additional actions related to the appearance of the view. Figure 5-1 Responding to the appearance of a view 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 66 Responding to Display-Related NotificationsResponding When a View Disappears Figure 5-2 shows the sequence of events that occurs when a view is removed from its window. When the view controller detects that its view is about to be removed or hidden, it calls the viewWillDisappear: and viewDidDisappear: methods to give subclasses a chance to perform any relevant tasks. Figure 5-2 Responding to the disappearance of a view Determining Why a View’s Appearance Changed Occasionally, it can be useful to know why a view is appearing or disappearing. For example, you might want to know whether a view appeared because it was just added to a container or whether it appeared because some other content that obscured it wasremoved. This particular example often appears when using navigation controllers; your content controller’s view may appear because the view controller was just pushed onto the navigation stack or it might appear because controllers previously above it were popped from the stack. The UIViewController class provides methods your view controller can call to determine why the appearance change occurred. Table 5-1 describes the methods and their usage. These methods can be called from inside your implementation of the viewWillAppear:, viewDidAppear:, viewWillDisappear: and viewDidDisappear: methods. Responding to Display-Related Notifications Responding When a View Disappears 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 67Table 5-1 Methods to call to determine why a view’s appearance changed Method Name Usage You call this method inside your viewWillDisappear: and viewDidDisappear: methodsto determine if the view controller’s view is being hidden because the view controller was removed from its container view controller. isMovingFromParentViewController You call this method inside your viewWillAppear: and viewDidAppear: methods to determine if the view controller’s view is being shown because the view controller was just added to a container view controller. isMovingToParentViewController You call this method inside your viewWillAppear: and viewDidAppear: methods to determine if the view controller’s view is being shown because the view controller was just presented by another view controller. isBeingPresented You call this method inside your viewWillDisappear: and viewDidDisappear: methodsto determine if the view controller’s view is being hidden because the view controller was just dismissed. isBeingDismissed Responding to Display-Related Notifications Determining Why a View’s Appearance Changed 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 68A view controller owns its own view and manages the view’s contents. In the process, the view controller also manages the view’s subviews. But in most cases, the view’s frame is not set directly by the view controller. Instead, the view’s frame is determined by how the view controller’s view is displayed. More directly, it is configured by the object used to display it. Other conditions in the app, such as the presence of the status bar, can also cause the frame to change. Because of this, your view controller should be prepared to adjust the contents of its view when the view’s frame changes. A Window Sets the Frame of Its Root View Controller’s View The view associated with the window’s root view controller gets a frame based on the characteristics of the window. The frame set by the window can change based on a number of factors: ● The frame of the window ● Whether or not the status bar is visible ● Whether or not the status bar is showing additional transient information (such as when a phone call is in progress) ● The orientation of the user interface (landscape or portrait) ● The value stored in the root view controller’s wantsFullScreenLayout property If your app displays the status bar, the view shrinks so that it does not underlap the status bar. After all, if the status bar is opaque, there is no way to see or interact with the content lying underneath it. However, if your app displays a translucentstatus bar, you can set the value of your view controller’s wantsFullScreenLayout property to YES to allow your view to be displayed full screen. The status bar is drawn over the top of the view. Full screen is useful when you want to maximize the amount of space available for displaying your content. When displaying content under the status bar, place that content inside a scroll view so that the user can scroll it out from under the status bar. Being able to scroll your content isimportant because the user cannot interact with content that is positioned behind the status bar or any other translucent views (such as translucent navigation bars and toolbars). Navigation bars automatically add a scroll content inset to your scroll view (assuming it is the root view of your view controller) to account for the height of the navigation bar; otherwise, you must manually modify the contentInset property of your scroll view. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 69 Resizing the View Controller’s ViewsA Container Sets the Frames of Its Children’s Views When a view controller is a child of a container view controller, its parent decides which children are visible. When it wants to show the view, it adds it as a subview in its own view hierarchy and sets its frame to fit it into its user interface. For example: ● A tab view controller reserves space at the bottom of its view for the tab bar. It sets the currently visible child’s view to use the remainder of the space. ● A navigation view controller reserves space at the top for the navigation bar. If the currently visible child wants a navigation bar to be displayed, it also places a view at the bottom of the screen. The remainder of its view is given to the child to fill. A child gets its frame from the parent all the way up to the root view controller, which gets its frame from the window. A Presented View Controller Uses a Presentation Context When a view controller is presented by another view controller, the frame it receivesis based on the presentation context used to display the view controller. See “Presentation Contexts Provide the Area Covered by the Presented View Controller” (page 95). A Popover Controller Sets the Size of the Displayed View A view controller displayed by a popover controller can determine the size of its view’s area by setting its own contentSizeForViewInPopover property value to the size it wants. If the popover controller sets its own popoverContentSize property to a different view size, its size value overrides the view controller’s setting. To match the model used by other view controllers, use the popover controller’s properties to control its size and position. How View Controllers Participate in the View Layout Process When the size of a view controller’s view changes, its subviews are repositioned to fit the new space available to them. The views in the controller’s view hierarchy perform most of this work themselves through the use of layout constraints and autoresizing masks. However, the view controller is also called at various points so that it can participate in the process. Here’s what happens: 1. The view controller’s view is resized to the new size. Resizing the View Controller’s Views A Container Sets the Frames of Its Children’s Views 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 702. If autolayout is not in use, the views are resized according to their autoresizing masks. 3. The view controller’s viewWillLayoutSubviews method is called. 4. The view’s layoutSubviews method is called. If autolayout is used to configure the view hierarchy, it updates the layout constraints by executing the following steps: a. The view controller’s updateViewConstraints method is called. b. The UIViewController class’simplementation of the updateViewConstraints method callsthe view’s updateConstraints method. c. After the layout constraints are updated, a new layout is calculated and the views are repositioned. 5. The view controller’s viewDidLayoutSubviews method is called. Ideally, the views themselves perform all of the necessary work to reposition themselves, without requiring the view controller to participate in the process at all. Often, you can configure the layout entirely within Interface Builder. However, if the view controller adds and removes views dynamically, a static layout in Interface Builder may not be possible. In this case, the view controller is a good place to control the process, because often the views themselves only have a limited picture of the other views in the scene. Here are the best approaches to this in your view controller: ● Use layout constraints to automatically position the views (iOS 6 and later). You override updateViewConstraints to add any necessary layout constraints not already configured by the views. Your implementation of this method must call [super updateViewConstraints]. For more information on layout constraints, see Cocoa Auto Layout Guide . ● Use a combination of autoresizing masks and code to manually position the views (iOS 5.x). You override layoutSubviews and use it to reposition any views whose positions cannot be set automatically through the use of resizing masks. For more information on the autoresizing properties of views and how they affect the view, see View Programming Guide for iOS . Resizing the View Controller’s Views How View Controllers Participate in the View Layout Process 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 71View controllers are descendants of the UIResponder class and are therefore capable of handling all sorts of events. When a view does not respond to a given event, it passes that event to its superview, traveling up the view hierarchy all the way to the root view. However, if any view in the chain is managed by a view controller, it passes the event to the view controller object before passing it up to the superview. In this way, the view controller can respond to events that are not handled by its views. If the view controller does not handle the event, that event moves on to the view’s superview as usual. The Responder Chain Defines How Events Are Propagated to the App Figure 7-1 demonstrates the flow of events within a view hierarchy. Suppose you have a custom view that is embedded inside a screen-sized generic view object, which in turn is managed by your view controller. Touch events arriving in your custom view’s frame are delivered to that view for processing. If your view does not 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 72 Using View Controllers in the Responder Chainhandle an event, it is passed along to the parent view. Because the generic view does not handle events, it passes those events along to its view controller first. If the view controller does not handle the event, the event isfurther passed along to the superview of the generic UIView object, which in this case isthe window object. Figure 7-1 Responder chain for view controllers Note: The message-passing relationship between a view controller and its view is managed privately by the view controller and cannot be programmatically modified by your app. Although you might not want to handle touch events specifically in your view controller, you could use it to handle motion-based events. You might also use it to coordinate the setting and changing of the first responder. For more information about how events are distributed and handled in iOS apps, see Event Handling Guide for iOS . Using View Controllers in the Responder Chain The Responder Chain Defines How Events Are Propagated to the App 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 73The accelerometers in iOS–based devices make it possible to determine the current orientation of the device. By default, an app supports both portrait and landscape orientations. When the orientation of an iOS–based device changes, the system sends out a UIDeviceOrientationDidChangeNotification notification to let any interested parties know that the change occurred. By default, the UIKit framework listens for this notification and uses it to update your interface orientation automatically. This means that, with only a few exceptions, you should not need to handle this notification at all. When the user interface rotates, the window is resized to match the new orientation. The window adjusts the frame of its root view controller to match the new size, and this size in turn is propagated down the view hierarchy to other views. Thus, the simplest way to support multiple orientations in your view controller is to configure its view hierarchy so that the positions of subviews are updated whenever its root view’s frame changes. In most cases, you already need this behavior because other conditions may cause the view controller’s visible area to change. For more information on configuring your view layout,see “Resizing the View Controller’s Views” (page 69). If the default behavior is not what you want for your app, you can take control over: ● The orientations supported by your app. ● How a rotation between two orientations is animated onscreen. View controllers that do not fill the screen usually should not care about the orientation of the user interface. Instead, fill the area provided by the parent view controller. A root view controller (or a view controller presented full screen) is more likely to be interested in the orientation of the device. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 74 Supporting Multiple Interface OrientationsControlling What Interface Orientations Are Supported (iOS 6) When UIKit receives an orientation notification, it usesthe UIApplication object and the root view controller to determine whether the new orientation is allowed. If both objects agree that the new orientation issupported, then the user interface is rotated to the new orientation. Otherwise the device orientation is ignored. When a view controller is presented over the root view controller, the system behavior changes in two ways. First, the presented view controller is used instead of the root view controller when determining whether an orientation is supported. Second, the presented view controller can also provide a preferred orientation. If the view controller is presented full screen, the user interface is presented in the preferred orientation. The user is expected to see that the orientation is different from the device orientation and rotate the device. A preferred orientation is most often used when the content must be presented in the new orientation. Declaring a View Controller’s Supported Interface Orientations A view controller that acts as the root view controller of the main window or is presented full screen on the main window can declare what orientations it supports. It does this by overriding the supportedInterfaceOrientations method. By default, view controllers on devices that use the iPad idiom support all four orientations. On devices that use the iPhone idiom, all interface orientations but upside-down portrait are supported. You should always choose the orientations your view supports at design time and implement your code with those orientationsin mind. There is no benefit to choosing which orientations you want to support dynamically based on runtime information. Even if your app did this, you would still have to implement the necessary code to support all possible orientations,so you might as well just choose to support the orientation or not up front. Listing 8-3 shows a fairly typical implementation of the supportedInterfaceOrientations method for a view controller that supports the portrait orientation and the landscape-left orientation. Your own implementation of this method should be just as simple. Listing 8-1 Implementing the supportedInterfaceOrientations method - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft; } Supporting Multiple Interface Orientations Controlling What Interface Orientations Are Supported (iOS 6) 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 75Dynamically Controlling Whether Rotation Occurs Sometimes you may want to dynamically disable automatic rotation. For example, you might do this when you want to suppress rotation completely for a short period of time. You must temporarily disable orientation changes you want to manually control the position of the status bar (such as when you call the setStatusBarOrientation:animated: method). If you want to temporarily disable automatic rotation, avoid manipulating the orientation masks to do this. Instead, override the shouldAutorotate method on the topmost view controller. This method is called before performing any autorotation. If it returns NO, then the rotation is suppressed. Declaring a Preferred Presentation Orientation When a view controller is presented full-screen to show its content, sometimes the content appears best when viewed in a particular orientation in mind. If the content can only be displayed in that orientation, then you simply return that as the only orientation from your supportedInterfaceOrientations method. If the view controller supports multiple orientations but appears better in a different orientation, you can provide a preferred orientation by overriding the preferredInterfaceOrientationForPresentation method. Listing 8-2 shows an example used by a view controller whose content should be presented in landscape orientation. The preferred interface orientation must be one of the orientationssupported by the view controller. Listing 8-2 Implementing the preferredInterfaceOrientationForPresentation method - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return UIInterfaceOrientationLandscapeLeft; } For more on presentation, see “Presenting View Controllers from Other View Controllers” (page 88). Declaring the App’s Supported Interface Orientations The easiest way to set an app’s app’s supported interface orientations is to edit the project’s Info.plist file. As in the case of the view controller, you define which of the four interface orientations are permitted. For more information, see Information Property List Key Reference . Supporting Multiple Interface Orientations Controlling What Interface Orientations Are Supported (iOS 6) 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 76If you restrict the app’s supported orientations, then those restrictions apply globally to all of the app’s view controllers, even when your app uses system view controllers. At any given time, the mask of the topmost view controller is logically ANDed with the app’s mask to determine what orientations are permitted. The result of this calculation must never be 0. If it is, the system throws a UIApplicationInvalidInterfaceOrientationException exception. Because the app’s mask is applied globally, use it sparingly. Important: The combination of the app and the view controller’s orientation masks must result in at least one useable orientation. An exception is thrown if there is no available orientation. Understanding the Rotation Process (iOS 5 and earlier) On iOS 5 and earlier, a view controller can sometimes participate in the rotation process even when it isn’t the topmost full-screen view controller. This generally occurs when a container view controller asks its children for their supported interface orientations. In practice, the ability for children to override the parents is rarely useful. With that in mind, you should consider emulating the iOS 6 behavior as much as possible in an app that must also support iOS 5: ● In a root view controller or a view controller that is presented full screen, choose a subset of interface orientations that make sense for your user interface. ● In a child controller, support all the default resolutions by designing an adaptable view layout. Declaring the Supported Interface Orientations To declare your supported interface orientations, override the shouldAutorotateToInterfaceOrientation:method and indicate which orientations your view supports. You should always choose the orientations your view supports at design time and implement your code with those orientationsin mind. There is no benefit to choosing which orientations you want to support dynamically based on runtime information. Even if you did so, you would still have to implement the necessary code to support all possible orientations, and so you might as well just choose to support the orientation or not up front. Listing 8-3 shows a fairly typical implementation of the shouldAutorotateToInterfaceOrientation: method for a view controller that supports the default portrait orientation and the landscape-left orientation. Your own implementation of this method should be just as simple. Supporting Multiple Interface Orientations Understanding the Rotation Process (iOS 5 and earlier) 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 77Listing 8-3 Implementing the shouldAutorotateToInterfaceOrientation: method - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationLandscapeLeft)) return YES; return NO; } Important: You must always return YES for at least one interface orientation. If your app supports both landscape orientations, you can use the UIInterfaceOrientationIsLandscape macro as a shortcut, instead of explicitly comparing the orientation parameter against both landscape constants. The UIKit framework similarly defines a UIInterfaceOrientationIsPortrait macro to identify both variants of the portrait orientation. Responding to Orientation Changes in a Visible View Controller When a rotation occurs, the view controllers play an integral part of the process. Visible view controllers are notified at various stages of the rotation to give them a chance to perform additional tasks. You might use these methods to hide or show views, reposition or resize views, or notify other parts of your app about the orientation change. Because your custom methods are called during the rotation operation, you should avoid performing any time-consuming operations there. You should also avoid replacing your entire view hierarchy with a new set of views. There are better ways to provide unique views for different orientations, such as presenting a new view controller (as described in “Creating an Alternate Landscape Interface” (page 80)). The rotation methods are sent to the root view controller. The root view controller passes these events on as necessary to its children, and so on down the view controller hierarchy. Here is the sequence of events that occur when a rotation is triggered: 1. The window callsthe root view controller’s willRotateToInterfaceOrientation:duration:method. Container view controllers forward this message on to the currently displayed content view controllers. You can override this method in your custom content view controllersto hide views or make other changes to your view layout before the interface is rotated. Supporting Multiple Interface Orientations Responding to Orientation Changes in a Visible View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 782. The window adjusts the bounds of the view controller’s view. This causes the view to layout its subviews, triggering the view controller’s viewWillLayoutSubviews method. When this method runs, you can query the app object’s statusBarOrientation property to determine the current user interface layout. See “How View Controllers Participate in the View Layout Process” (page 70). 3. The view controller’s willAnimateRotationToInterfaceOrientation:duration: method is called. This method is called from within an animation block so that any property changes you make are animated at the same time as other animations that comprise the rotation. 4. The animation is executed. 5. The window calls the view controller’s didRotateFromInterfaceOrientation: method. Container view controllers forward this message to the currently displayed content view controllers. This action marks the end of the rotation process. You can use this method to show views, change the layout of views, or make other changes to your app. Figure 8-1 shows a visual representation of the preceding steps. It also shows how the interface looks at various stages of the process. Figure 8-1 Processing an interface rotation Supporting Multiple Interface Orientations Responding to Orientation Changes in a Visible View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 79Rotations May Occur When Your View Controller Is Hidden If your view controller’s contents are not onscreen when a rotation occurs, then it does not see the list of rotation messages. For example, consider the following sequence of events: 1. Your view controller presents another view controller’s contents full screen. 2. The user rotates the device so that the user interface orientation changes. 3. Your app dismisses the presented view controller. In this example, the presenting view controller was not visible when the rotation occurred, so it does not receive any rotation events. Instead, when it reappears, its views are simply resized and positioned using the normal view layout process. If your layout code needs to know the current orientation of the device, it can read the app object’s statusBarOrientation property to determine the current orientation. Creating an Alternate Landscape Interface If you want to present the same data differently based on whether a device is in a portrait or landscape orientation, the way to do so is using two separate view controllers. One view controller should manage the display of the data in the primary orientation (typically portrait), while the other manages the display of the data in the alternate orientation. Using two view controllers is simpler and more efficient than making major changes to your view hierarchy each time the orientation changes. It allows each view controller to focus on the presentation of data in one orientation and to manage things accordingly. It also eliminates the need to litter your view controller code with conditional checks for the current orientation. To support an alternate landscape interface, you must do the following: ● Implement two view controller objects. One to present a portrait-only interface, and the other to present a landscape-only interface. ● Register for the UIDeviceOrientationDidChangeNotification notification. In your handler method, present or dismiss the alternate view controller based on the current device orientation. Because view controllers normally manage orientation changesinternally, you have to tell each view controller to display itself in one orientation only. The implementation of the primary view controller then needsto detect device orientation changes and present the alternate view controller when the appropriate orientation change occurs. The primary view controller dismisses the alternate view controller when the orientation returns to the primary orientation. Supporting Multiple Interface Orientations Rotations May Occur When Your View Controller Is Hidden 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 80Listing 8-4 showsthe key methods you need to implement in a primary view controller thatsupports a portrait orientation. When the primary view controller is loaded from the storyboard, it registers to receive orientation-changed notifications from the shared UIDevice object. When such a notification arrives, the orientationChanged: method then presents or dismisses the landscape view controller depending on the current orientation. Listing 8-4 Presenting the landscape view controller @implementation PortraitViewController - (void)awakeFromNib { isShowingLandscapeView = NO; [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; } - (void)orientationChanged:(NSNotification *)notification { UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation; if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView) { [self performSegueWithIdentifier:@"DisplayAlternateView" sender:self]; isShowingLandscapeView = YES; } else if (UIDeviceOrientationIsPortrait(deviceOrientation) && isShowingLandscapeView) { [self dismissViewControllerAnimated:YES completion:nil]; isShowingLandscapeView = NO; } } Supporting Multiple Interface Orientations Creating an Alternate Landscape Interface 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 81Tips for Implementing Your Rotation Code Depending on the complexity of your views, you may need to write a lot of code to support rotations—or no code at all. When figuring out what you need to do, you can use the following tips as a guide for writing your code. ● Disable event delivery temporarily during rotations. Disabling event delivery for your views prevents unwanted code from executing while an orientation change is in progress. ● Store the visible map region. If your app contains a map view, save the visible map region value prior to beginning any rotations. When the rotations finish, use the saved value as needed to ensure that the displayed region is approximately the same as before. ● For complex view hierarchies, replace your views with a snapshot image. If animating large numbers of views is causing performance issues, temporarily replace those views with an image view containing an image of the viewsinstead. After the rotations are complete, reinstall your views and remove the image view. ● Reload the contents of any visible tables after a rotation. Forcing a reload operation when the rotations are finished ensures that any new table rows exposed are filled appropriately. ● Use rotation notifications to update your app’s state information. If your app usesthe current orientation to determine how to present content, use the rotation methods of your view controller (or the corresponding device orientation notifications) to note those changes and make any necessary adjustments. Supporting Multiple Interface Orientations Tips for Implementing Your Rotation Code 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 82Aside from managing a view’s behavior, a view controller can also help control an app’s accessibility. An accessible app is one that can be used by everyone, regardless of disability or physical impairment, while retaining its functionality and usability as a helpful tool. To be accessible, an iOS app must supply information about its user interface elements to VoiceOver users. VoiceOver, a screen-reading technology designed to assist the visually impaired, speaks aloud text, images, and UI controls displayed the screen, so that people who cannot see can still interact with these elements. UIKit objects are accessible by default, but there are still things you can do from the view controller’s perspective to address accessibility. At a high level, this means you should make sure that: ● Every user interface element users can interact with is accessible. Thisincludes elementsthat merely supply information, such as static text, as well as controls that perform actions. ● All accessible elements supply accurate and helpful information. In addition to these fundamentals, a view controller can enhance the VoiceOver user’s experience by setting the position of the VoiceOver focus ring programmatically, responding to special VoiceOver gestures, and observing accessibility notifications. Moving the VoiceOver Cursor to a Specific Element When the layout of a screen changes, the VoiceOver focus ring, also known as the VoiceOver cursor, resets its position to the first element displayed on the screen from left to right and top to bottom. You might decide to change the first element the VoiceOver cursor lands on when views are presented onscreen. For example, when a navigation controller pushes a view controller onto the navigation stack, the VoiceOver cursor falls on the Back button of the navigation bar. Depending on your app, it might make more sense to move it to the heading of the navigation bar instead, or to any other element. To do so, call UIAccessibilityPostNotification using both the notification UIAccessibilityScreenChangedNotification (which tells VoiceOver that the contents of the screen has changed) and the element you’d like to give focus to, as shown in Listing 9-1. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 83 Accessibility from the View Controller’s PerspectiveListing 9-1 Posting an accessibility notification can change the first element read aloud @implementation MyViewController - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, self.myFirstElement); } @end If only the layout changes rather than the contents of the screen, such as when switching from portrait to landscape mode, use the notification UIAccessibilityLayoutChangedNotification instead of UIAccessibilityScreenChangedNotification. Note: Device rotation triggers a layout change, which resets the VoiceOver cursor’s position. Responding to Special VoiceOver Gestures There are special gestures that VoiceOver users can perform to trigger custom actions. These gestures are special because you are allowed to define their behavior, unlike standard VoiceOver gestures. You can detect the gestures by overriding certain methods in your views or view controllers. A gesture first checks the view that has VoiceOver focus for instruction and continues up the responder chain until it finds an implementation of the corresponding VoiceOver gesture method. If no implementation is found, the system default action for that gesture is triggered. For example, the Magic Tap gesture plays and pauses music playback from the Music app if no Magic Tap implementation is found from the current view to the app delegate. Although you can provide any custom logic you want, VoiceOver users expect the actions of these special gestures to follow certain guidelines. Like any gesture, your implementation of a VoiceOver gesture should follow a pattern so that interaction with an accessible app remains intuitive. There are five special VoiceOver gestures: ● Escape. A two-finger Z-shaped gesture that dismisses a modal dialog, or goes back one level in a navigation hierarchy. Accessibility from the View Controller’s Perspective Responding to Special VoiceOver Gestures 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 84● Magic Tap. A two-finger double-tap that performs the most-intended action. ● Three-Finger Scroll. A three-finger swipe that scrolls content vertically or horizontally. ● Increment and Decrement. A one-finger swipe up or down that adds or subtracts a given value from an element with the adjustable trait. Elements with the Adjustable accessibility trait must implement these methods. Note: All special VoiceOver gesture methods return a Boolean value that determine whether to propagate through the responder chain. To halt propagation, return YES; otherwise, return NO. Escape If you present a view that overlays content—such as a modal dialog or an alert—you should override the accessibilityPerformEscape method to dismiss the overlay. The function of the Escape gesture is like the function of the Esc key on a computer keyboard; it cancels a temporary dialog or sheet to reveal the main content. Another use case to override the Escape gesture would be to go back up one level in a navigation hierarchy. UINavigationController implements this functionality by default. If you’re designing your own kind of navigation controller, you should set the Escape gesture to traverse up one level of your navigation stack, because that is the functionality VoiceOver users expect. Magic Tap The purpose of the Magic Tap gesture isto quickly perform an often-used or most-intended action. For example, in the Phone app, it picks up or hangs up a phone call. In the Clock app, it starts and stops the stopwatch. If you want an action to fire from a gesture regardless of the view the VoiceOver cursor is on, you should implement the accessibilityPerformMagicTap method in your view controller. Note: If you’d like the Magic Tap gesture to perform the same action from anywhere within your app, it is more appropriate to implement the accessibilityPerformMagicTap method in your app delegate. Three-Finger Scroll The accessibilityScroll: method fires when a VoiceOver user performs a three-finger scroll. It accepts a UIAccessibilityScrollDirection parameter from which you can determine the direction of the scroll. If you have a custom scrolling view, it may be more appropriate to implement this on the view itself. Accessibility from the View Controller’s Perspective Responding to Special VoiceOver Gestures 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 85Increment and Decrement The accessibilityIncrement and accessibilityDecrement methods are required for elements with the adjustable trait and should be implemented on the views themselves. Observing Accessibility Notifications You can listen for accessibility notifications to trigger callback methods. Under certain circumstances, UIKit fires accessibility notifications which your app can observe to extend its accessible functionality. For example, if you listen for the notification UIAccessibilityAnnouncementDidFinishNotification, you can trigger a method to follow up the completion of VoiceOver’s speech. Apple does this in the iBooks app. iBooks fires a notification when VoiceOver finishes speaking a line in a book that triggers the next line to be spoken. If it is the last line on the page, the logic in the callback tells iBooks to turn the page and continue reading as soon as the last line ends speaking. This allows for a line-by-line degree of granularity for navigating text while providing a seamless, uninterrupted reading experience. To register as an observer for accessibility notifications, use the default notification center. Then create a method with the same name that you provide for the selector argument, as shown in Listing 9-2. Listing 9-2 Registering as an observer for accessibility notifications @implementation MyViewController - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinishAnnouncement:) name:UIAccessibilityAnnouncementDidFinishNotification object:nil]; } - (void)didFinishAnnouncement:(NSNotification *)dict { NSString *valueSpoken = [[dict userInfo] objectForKey:UIAccessibilityAnnouncementKeyStringValue]; Accessibility from the View Controller’s Perspective Observing Accessibility Notifications 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 86NSString *wasSuccessful = [[dict userInfo] objectForKey:UIAccessibilityAnnouncementKeyWasSuccessful]; // ... } @end UIAccessibilityAnnouncementDidFinishNotification expects an NSNotification dictionary as a parameter from which you can determine the value spoken and whether or not the speaking has completed uninterrupted. Speaking may become interrupted if the VoiceOver user performs the stop speech gesture or swipes to another element before the announcement finishes. Another helpful notification to subscribe to is UIAccessibilityVoiceOverStatusChanged. It can detect when VoiceOver becomes toggled on or off. If VoiceOver is toggled outside of your app, you receive the notification when your app is brought back into the foreground. Because UIAccessibilityVoiceOverStatusChanged doesn’t expect any parameters, the method in your selector doesn’t need to append a trailing colon (:). For a full list of possible notifications you can observe, consult“Notifications”in UIAccessibility Protocol Reference . Remember that you may only observe the notifications that can be posted by UIKit, which are NSString objects, and not notifications that can be posted by your app, which are of type int. Accessibility from the View Controller’s Perspective Observing Accessibility Notifications 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 87The ability to present view controllers is a tool that you have at your disposal for interrupting the current workflow and displaying a new set of views. Most commonly, an app presents a view controller as a temporary interruption to obtain important information from the user. However, you can also use presented view controllers to implement alternate interfaces for your app at specific times. How View Controllers Present Other View Controllers A presented view controller is not a specific subclass of UIViewController (as UITabBarController or UINavigationController is). Instead, any view controller can be presented by your app. However, like tab bar and navigation controllers, you present view controllers when you want to convey a specific meaning about the relationship between the previous view hierarchy and the newly presented view hierarchy. When you present a modal view controller, the system creates a relationship between the view controller that did the presenting and the view controller that was presented. Specifically, the view controller that did the presenting updates its presentedViewController property to point to its presented view controller. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 88 Presenting View Controllers from Other View ControllersSimilarly, the presented view controller updates its presentingViewController property to point back to the view controller that presented it. Figure 10-1 showsthe relationship between the view controller managing the main screen in the Calendar app and the presented view controller used to create new events. Figure 10-1 Presented views in the Calendar app. Any view controller object can present a single view controller at a time. This is true even for view controllers that were themselves presented by another view controller. In other words, you can chain presented view controllers together, presenting new view controllers on top of other view controllers as needed. Figure 10-2 shows a visual representation of the chaining process and the actions that initiate it. In this case, when the user taps the icon in the camera view, the app presents a view controller with the user’s photos. Tapping the action button in the photo library’s toolbar prompts the user for an appropriate action and then presents Presenting View Controllers from Other View Controllers How View Controllers Present Other View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 89another view controller (the people picker) in response to that action. Selecting a contact (or canceling the people picker) dismisses that interface and takes the user back to the photo library. Tapping the Done button then dismisses the photo library and takes the user back to the camera interface. Figure 10-2 Creating a chain of modal view controllers Camera view controller Photo library navigation controller Action sheet People picker navigation controller present modally present modally Each view controller in a chain of presented view controllers has pointers to the other objects surrounding it in the chain. In other words, a presented view controller that presents another view controller has valid objects in both its presentingViewController and presentedViewController properties. You can use these relationships to trace through the chain of view controllers as needed. For example, if the user cancels the current operation, you can remove all objects in the chain by dismissing the first presented view controller. Dismissing a view controller dismisses not only that view controller but also any view controllers it presented. In Figure 10-2 (page 90), a point worth noting is that the presented view controllers are both navigation controllers. You can present UINavigationController objects in the same way that you would present a content view controller. When presenting a navigation controller, you always present the UINavigationController object itself, rather than presenting any of the view controllers on its navigation stack. However, individual view controllers on the navigation stack may present other view controllers, including other navigation controllers. Figure 10-3 Presenting View Controllers from Other View Controllers How View Controllers Present Other View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 90shows more detail of the objects that are involved in the preceding example. As you can see, the people picker is not presented by the photo library navigation controller but by one of the content view controllers on its navigation stack. Figure 10-3 Presenting navigation controllers modally Presentation Styles for Modal Views For iPad apps, you can present content using several different styles. In iPhone apps, presented views always cover the visible portion of the window, but when running on an iPad, view controllers use the value in their modalPresentationStyle property to determine their appearance when presented. Different options for this property allow you to present the view controller so that it fills all or only part of the screen. Presenting View Controllers from Other View Controllers Presentation Styles for Modal Views 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 91Figure 10-4 shows the core presentation styles that are available. (The UIModalPresentationCurrentContext style lets a view controller adopt the presentation style of its parent.) In each presentation style, the dimmed areas show the underlying content but do not allow taps in that content. Therefore, unlike a popover, your presented views must still have controls that allow the user to dismiss the view. Figure 10-4 iPad presentation styles For guidance on when to use the different presentation styles, see “Popover (iPad Only)” in iOS Human Interface Guidelines. Presenting View Controllers from Other View Controllers Presentation Styles for Modal Views 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 92Presenting a View Controller and Choosing a Transition Style When a view controller is presented using a storyboard segue, it is automatically instantiated and presented. The presenting view controller can configure the destination view controller before it is presented. For more information, see “Configuring the Destination Controller When a Segue is Triggered” (page 101). If you need to present a view controller programmatically, you must do the following: 1. Create the view controller you want to present. 2. Set the modalTransitionStyle property of the view controller to the desired value. 3. Assign a delegate object to the view controller. Typically, the delegate is the presenting view controller. The delegate is used by the presented view controllers to notify the presenting view controller when it is ready to be dismissed. It may also communicate other information back to the delegate. 4. Call the presentViewController:animated:completion: method of the current view controller, passing in the view controller you want to present. The presentViewController:animated:completion: method presents the view for the specified view controller object and configures the presenting-presented relationships between the new view controller and the current view controller. Unless you are restoring your app to some previous state, you usually want to animate the appearance of the new view controller. The transition style you should use depends on how you plan to use the presented view controller. Table 10-1 lists the transition styles you can assign to the modalTransitionStyle property of the presented view controller and describes how you might use each one. Table 10-1 Transition styles for modal view controllers Transition style Usage Use this style when you want to interrupt the current workflow to gather information from the user. You can also use it to present content that the user might or might not modify. For thisstyle of transition, content view controllersshould provide buttons to dismissthe view controller explicitly. Typically, these are a Done button and an optional Cancel button. If you do not explicitly set a transition style, this style is used by default. UIModalTransitionStyleCoverVertical Use thisstyle to change the work mode of your app temporarily. The most common usage for this style is to display settings that might change frequently, such as in the Stocks and Weather apps. These settings can be meant for the entire app or they can be specific to the current screen. For this style of transition, you usually provide some sort of button to return the user to the normal running mode of your app. UIModalTransitionStyleFlipHorizontal Presenting View Controllers from Other View Controllers Presenting a View Controller and Choosing a Transition Style 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 93Transition style Usage Use this style to present an alternate interface when the device changes orientations. In such a case, your app is responsible for presenting and dismissing the alternate interface in response to orientation change notifications. Media-based apps can also use this style to fade in screens displaying media content. For an example of how to implement an alternate interface in response to device orientation changes, see “Creating an Alternate Landscape Interface” (page 80). UIModalTransitionStyleCrossDissolve Listing 10-1 shows how to present a view controller programmatically. When the user adds a new recipe, the app promptsthe user for basic information about the recipe by presenting a navigation controller. A navigation controller was chosen so that there would be a standard place to put a Cancel and Done button. Using a navigation controller also makes it easier to expand the new recipe interface in the future. All you would have to do is push new view controllers on the navigation stack. Listing 10-1 Presenting a view controller programmatically - (void)add:(id)sender { // Create the root view controller for the navigation controller // The new view controller configures a Cancel and Done button for the // navigation bar. RecipeAddViewController *addController = [[RecipeAddViewController alloc] init]; // Configure the RecipeAddViewController. In this case, it reports any // changes to a custom delegate object. addController.delegate = self; // Create the navigation controller and present it. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:addController]; [self presentViewController:navigationController animated:YES completion: nil]; } Presenting View Controllers from Other View Controllers Presenting a View Controller and Choosing a Transition Style 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 94When the user taps either the Done or the Cancel button from the new recipe entry interface, the app dismisses the view controller and returns the user to the main view. See “Dismissing a Presented View Controller” (page 95). Presentation Contexts Provide the Area Covered by the Presented View Controller The area of the screen used to define the presentation area is determined by the presentation context. By default, the presentation context is provided by the root view controller, whose frame is used to define the frame of the presentation context. However, the presenting view controller, or any other ancestor in the view controller hierarchy, can choose to provide the presentation context instead. In that case, when another view controller provides the presentation context, its frame is used instead to determine the frame of the presented view. This flexibility allows you to limit the modal presentation to a smaller portion of the screen, leaving other content visible. When a view controller is presented, iOS searches for a presentation context. It starts at the presenting view controller by reading its definesPresentationContext property. If the value of this property is YES, then the presenting view controller defines the presentation context. Otherwise, it continues up through the view controller hierarchy until a view controller returns YES or until it reaches the window’s root view controller. When a view controller defines a presentation context, it can also choose to define the presentation style. Normally, the presented view controller determines how it presented using its modalTransitionStyle property. A view controller that sets definesPresentationContext to YES can also set providesPresentationContextTransitionStyle to YES. If providesPresentationContextTransitionStyle is set to YES, iOS uses the presentation context’s modalPresentationStyle to determine how the new view controller is presented. Dismissing a Presented View Controller When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it. Although there are several techniques for notifying the presenting view controller that its presented view controller should be dismissed, the preferred technique is delegation. For more information, see “Using Delegation to Communicate with Other Controllers” (page 103). Presenting View Controllers from Other View Controllers Presentation Contexts Provide the Area Covered by the Presented View Controller 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 95Presenting Standard System View Controllers A number of standard system view controllers are designed to be presented by your app. The basic rules for presenting these view controllers are the same asthe rulesfor presenting your custom content view controllers. However, because your app does not have accessto the view hierarchy managed by the system view controllers, you cannotsimply implement actionsfor the controlsin the views. Interactions with the system view controllers typically take place through a delegate object. Each system view controller defines a corresponding protocol, whose methods you implement in your delegate object. Each delegate usually implements a method to either accept whatever item was selected or cancel the operation. Your delegate object should always be ready to handle both cases. One of the most important things the delegate must do is dismiss the presented view controller by calling the dismissModalViewControllerAnimated: method of the view controller that did the presenting (in other words, the parent of the presented view controller.) Table 10-2 lists several of the standard system view controllers found in iOS. For more information about each of these classes, including the features it provides, see the corresponding class reference documentation. Table 10-2 Standard system view controllers Framework View controllers ABNewPersonViewController ABPeoplePickerNavigationController ABPersonViewController ABUnknownPersonViewController Address Book UI EKEventEditViewController EKEventViewController Event Kit UI GKAchievementViewController GKLeaderboardViewController GKMatchmakerViewController GKPeerPickerController GKTurnBasedMatchmakerViewController Game Kit MFMailComposeViewController MFMessageComposeViewController Message UI MPMediaPickerController MPMoviePlayerViewController Media Player Presenting View Controllers from Other View Controllers Presenting Standard System View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 96Framework View controllers UIImagePickerController UIVideoEditorController UIKit Note: Although the MPMoviePlayerController class in the Media Player framework might technically be thought of as a modal controller, the semantics for using it are slightly different. Instead of presenting the view controller yourself, you initialize it and tell it to play its media file. The view controller then handles all aspects of presenting and dismissing its view. (However, the MPMoviePlayerViewController class can be used instead of MPMoviePlayerController as a standard view controller for playing movies.) Presenting View Controllers from Other View Controllers Presenting Standard System View Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 97Few iOS apps show only a single screenful of content. Instead, they show some content when first launched and then show and hide other content in response to user actions. These transitions provide a single unified user interface that display a lot of content, just not all at once. By convention,smaller pieces of content are managed by different view controller classes. This coding convention allows you to create smaller and simpler controller classes that are easy to implement. However, dividing the work between multiple classesimposes additional requirements on your class designs. To maintain the illusion of a single interface, your view controllers must exchange messages and data to coordinate transitions from controller to another. Thus, even as your view controller classes look inwards to control views and perform the tasks assigned to them, they also look outwards to communicate with other collaborating view controllers. When Coordination Between View Controllers Occurs Communication between view controllers is tied to the role those view controllers play in your app. It would be impossible to describe all of the possible interactions between view controllers, because the number and nature of these relationships is dependent on the design of your app. However, it is possible to describe when these interactions occur and to give some examples of the kinds of coordination that might take place in your app. The lifetime of a view controller has three stages during which it might coordinate with other objects: View controller instantiation. In this stage, when a view controller is created, an existing view controller or another object was responsible for its creation. Usually, this object knows why the view controller was created and what task itshould perform. Thus, after a view controller isinstantiated, thisintent must be communicated to it. The exact details of this initial configuration vary. Sometimes, the existing view controller passes data objects to the new controller. At other times, it may configure the presentation style for that, or establish lasting links between the two view controllers. These links allow further communication later in the view controller’slifetime. During the view controller’s lifetime. In this stage, some view controllers communicate with other view controllers during their lifetime. The recipient of these messages could be the view controller that created it, peers with similar lifetimes, or even a new view controller that it itself created. Here are a few common designs: 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 98 Coordinating Efforts Between View Controllers● The view controllersends notificationsthat the user performed a specific action. Because thisis a notification, the object receiving this message is just being notified that something happened. ● The view controllersends data to another view controller. For example, a tab bar controller doesn’t establish a built-in relationship between its children, but your app might establish such a relationship when the tabs are displaying the same data object, just in different ways. When a user leaves one tab, the view controller associated with that tab sends the selection information to the view controller about to be displayed. In return, the new view controller uses this data to configure its views so that the transition appears seamless. In this particular case, no new view controller is instantiated by the action. Instead, the two view controllers are peers with the same lifetime and can continue to coordinate as the user switches between them. ● A view controller sends messages to give another view controller authority over its actions. For example, if a view controller allows usersto enter data, it mightsend messagesto allow another controller to decide whether the data the user entered is valid. If the data is invalid, the view controller can disallow the user from accepting the invalid data or adjust its interface to display an error. View controller destruction. In this stage, many view controllers send messages when their task completes. These messages are common because the convention is for the controller that created a view controller to also release it. Sometimes, these messages simply convey that the user finished the task. At other times, such as when the task being performed generated new data objects, the message communicatesthe new data back to another controller. During a view controller’s lifetime, it is common for it to exchange information with other view controllers. These messages are used to notify other controllers when things happen, send them data, or even ask them to exert control over the controller’s activities. With Storyboards, a View Controller is Configured When It Is Instantiated Storyboards provide direct support for configuring newly instantiated controllers before they are displayed. When a storyboard instantiates new view controllers automatically, it calls an object in your app to allow it to configure the new controller or to create links to or from the new controller. When your app first launches, the app delegate configures the initial view controller. When a segue is triggered, the source view controller configures the destination view controller. There are a few conventions used to implement destination view controllers: ● A destination view controller exposes properties and methods used to configure it. Coordinating Efforts Between View Controllers With Storyboards, a View Controller is Configured When It Is Instantiated 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 99● A destination view controller communicates as little as possible with view controllers that it did not create personally. When it does so, these communication paths should use delegation. The destination view controller’s delegate is configured as one of its properties. Carefully following these conventions helps organize your configuration code and carefully limitsthe direction of dependencies between view controller classes in your app. By isolating dependencies in your app, you increase the opportunity for code reuse. You also design view controllers that are easier to test in isolation from the rest of your app. Configuring the Initial View Controller at Launch If you define a main storyboard in your project, iOS automatically does a lot of work for you to set up your app. When your app calls the UIApplicationMain function, iOS performs the following actions: 1. It instantiates the app delegate based on the class name you passed into the UIApplicationMain function. 2. It creates a new window attached to the main screen. 3. If your app delegate implements a window property, iOS sets this property to the new window. 4. It loads the main storyboard referenced in the app’s information property list file. 5. It instantiates the main storyboard’s initial view controller. 6. It sets the window’s rootViewController property to the new view controller. 7. It calls the app delegate’s application:didFinishLaunchingWithOptions: method. Your app delegate is expected to configure the initial view controller (and its children, if it is a container view controller). 8. It calls the window’s makeKeyAndVisible method to display the window. Listing 11-1 shows an implementation of the application:didFinishLaunchingWithOptions: method from the Your Second iOS App: Storyboards tutorial. In this example, the storyboard’s initial view controller is a navigation controller with a custom content controller that displays the master view. The code first retrieves references to the view controller it is interested in. Then, it performs any configuration that could not be performed in Interface Builder. In this example, a custom data controller object is provided to the master view controller by a custom data controller object. Listing 11-1 The app delegate configures the controller - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { Coordinating Efforts Between View Controllers With Storyboards, a View Controller is Configured When It Is Instantiated 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 100UINavigationController *navigationController = (UINavigationController*) self.window.rootViewController; BirdsMasterViewController * firstViewController = [[navigationController viewControllers] objectAtIndex:0]; BirdSightingDataController *dataController = [[BirdSightingDataController alloc] init]; firstViewController.dataController = dataController; return YES; } If your project does not identify the main storyboard, the UIApplicationMain function creates the app delegate and calls it but does not perform any of the other steps described earlier. You would need to write code to perform those steps yourself. Listing 11-2 shows the code you might implement if you needed to perform these steps programmatically. Listing 11-2 Creating the window when a main storyboard is not being used - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboard" bundle:nil]; MainViewController *mainViewController = [storyboard instantiateInitialViewController]; self.window.rootViewController = mainViewController; // Code to configure the view controller goes here. [self.window makeKeyAndVisible]; return YES; } Configuring the Destination Controller When a Segue is Triggered iOS performs the following tasks when a segue is triggered: Coordinating Efforts Between View Controllers With Storyboards, a View Controller is Configured When It Is Instantiated 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 1011. It instantiates the destination view controller. 2. It instantiates a new segue object that holds all the information for the segue being triggered. Note: A popover segue also provides a property that identifies the popover controller used to control the destination view controller. 3. It callsthe source view controller’s prepareForSegue:sender: method, passing in the new segue object and the object that triggered the segue. 4. It callsthe segue’s perform method to bring the destination controller onto the screen. The actual behavior depends on the kind ofsegue being performed. For example, a modalsegue tellsthe source view controller to present the destination view controller. 5. It releases the segue object and the segue is complete. The source view controller’s prepareForSegue:sender: method performs any necessary configuration of the destination view controller’s properties, including a delegate if the destination view controller implements one. Listing 11-3 shows an implementation of the prepareForSegue:sender: method from the Your Second iOS App: Storyboards tutorial. Listing 11-3 Configuring the destination controller in a segue - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"ShowSightingsDetails"]) { DetailViewController *detailViewController = [segue destinationViewController]; detailViewController.sighting = [self.dataController objectInListAtIndex:[self.tableView indexPathForSelectedRow].row]; } if ([[segue identifier] isEqualToString:@"ShowAddSightingView"]) { AddSightingViewController *addSightingViewController = [[[segue destinationViewController] viewControllers] objectAtIndex:0]; addSightingViewController.delegate = self; Coordinating Efforts Between View Controllers With Storyboards, a View Controller is Configured When It Is Instantiated 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 102} } This implementation, from the master view controller for the app, actually handles two different segues configured in the storyboard. It distinguishes between the two segues using the segue’s identifier property. In both cases, it follows the coding convention established earlier, by first retrieving the view controller and then configuring it. When the segue is to the detail view controller, the segue occurred because the user selected a row in the table view. In this case, the code transfers enough data to the destination view controllerso that the destination view controller can display the sighting. The code uses the user’s selection to retrieve a sighting object from the master view controller’s data controller. It then assigns this sighting to the destination controller. In the other case, the new view controller allows the user to add a new bird sighting. No data needs to be sent to this view controller. However, the master view controller needs to receive data when the user finishes entering the data. To receive that information, the source view controller implements the delegate protocol defined by the Add view controller (notshown here) and makesitself the destination view controller’s delegate. Using Delegation to Communicate with Other Controllers In a delegate-based model, the view controller defines a protocol for its delegate to implement. The protocol defines methods that are called by the view controller in response to specific actions, such as taps in a Done button. The delegate is then responsible for implementing these methods. For example, when a presented view controller finishesitstask, itsends a message to the presenting view controller and that controller dismisses it. Using delegation to manage interactions with other app objects has key advantages over other techniques: ● The delegate object has the opportunity to validate or incorporate changes from the view controller. ● The use of a delegate promotes better encapsulation because the view controller does not have to know anything about the class of the delegate. This enables you to reuse that view controller in other parts of your app. To illustrate the implementation of a delegate protocol, consider the recipe view controller example that was used in “Presenting a View Controller and Choosing a Transition Style” (page 93). In that example, a recipes app presented a view controller in response to the user wanting to add a new recipe. Prior to presenting the view controller, the current view controller made itself the delegate of the RecipeAddViewController object. Listing 11-4 shows the definition of the delegate protocol for RecipeAddViewController objects. Coordinating Efforts Between View Controllers Using Delegation to Communicate with Other Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 103Listing 11-4 Delegate protocol for dismissing a presented view controller @protocol RecipeAddDelegate // recipe == nil on cancel - (void)recipeAddViewController:(RecipeAddViewController *)recipeAddViewController didAddRecipe:(MyRecipe *)recipe; @end When the user taps the Cancel or Done button in the new recipe interface, the RecipeAddViewController object calls the preceding method on its delegate object. The delegate is then responsible for deciding what course of action to take. Listing 11-5 shows the implementation of the delegate method that handles the addition of new recipes. This method is implemented by the view controller that presented the RecipeAddViewController object. If the user accepted the new recipe—that is, the recipe object is not nil—this method addsthe recipe to itsinternal data structures and tells its table view to refresh itself. (The table view subsequently reloads the recipe data from the same recipesController object shown here.) Then the delegate method dismisses the presented view controller. Listing 11-5 Dismissing a presented view controller using a delegate - (void)recipeAddViewController:(RecipeAddViewController *)recipeAddViewController didAddRecipe:(Recipe *)recipe { if (recipe) { // Add the recipe to the recipes controller. int recipeCount = [recipesController countOfRecipes]; UITableView *tableView = [self tableView]; [recipesController insertObject:recipe inRecipesAtIndex:recipeCount]; [tableView reloadData]; } [self dismissViewControllerAnimated:YES completion: nil]; } Coordinating Efforts Between View Controllers Using Delegation to Communicate with Other Controllers 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 104Guidelines for Managing View Controller Data Carefully managing how data and control flows between your view controllersis critical to understanding how your app operates and avoiding subtle errors. Consider the following guidelines when designing your view controllers: ● A destination view controller’s references to app data should come from the source view controller unless the destination view controller represents a self-contained (and therefore self-configuring) view controller. ● Perform as much configuration as possible using Interface Builder, rather than configuring your controller programmatically in your code. ● Always use a delegate to communicate information back to other controllers. Your content view controller should never need to know the class of the source view controller or any controllers it doesn’t create. ● Avoid unnecessary connections to objects external to your view controller. Each connection represents a dependency that makes it harder to change your app design. For example, the children of a navigation controller should be aware of the parent navigation controller and of the siblings immediately above and below them on the stack. They rarely need to communicate with other siblings. Coordinating Efforts Between View Controllers Guidelines for Managing View Controller Data 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 105You can use the same view controller both to display and to edit content. When the editing mode is toggled, your custom view controller performs the necessary work to transition its view from a display mode to an editing mode (or vice versa). Toggling Between Display and Edit Mode To allow a custom view controller class to be used to both display and edit content, override the setEditing:animated: method. When called, your implementation of this method should add, hide, and adjust the view controller’s views to match the specified mode. For example, you might want to change the content or appearance of views to convey that the view is now editable. If your view controller manages a table, you can also call the table’s own setEditing:animated: method in order to put the table into the appropriate mode. 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 106 Enabling Edit Mode in a View ControllerNote: You typically do not swap out your entire view hierarchy when toggling back and forth between display and edit modes. The point of using the setEditing:animated: method is so that you can make small changes to existing views. If you would prefer to display a new set of views for editing, you should either present a new view controller or use a navigation controller to present the new views. Figure 12-1 shows a view from the Contacts app that supports in-place editing. Tapping the Edit button in the upper-right corner tells the view controller to update itself for editing; the Done button returns the user to display mode. In addition to modifying the table, the view also changes the content of the image view and the view displaying the user’s name. It also configures the assorted views and cells so that tapping them edits their contents instead of performing other actions. Figure 12-1 Display and edit modes of a view The implementation of your own setEditing:animated: method is relatively straightforward—you check to see which mode your view controller is entering and adjust the contents of your view accordingly. - (void)setEditing:(BOOL)flag animated:(BOOL)animated { Enabling Edit Mode in a View Controller Toggling Between Display and Edit Mode 2012-09-19 | © 2012 Apple Inc. All Rights Reserved. 107[super setEditing:flag animated:animated]; if (flag == YES){ // Change views to edit mode. } else { // Save the changes if needed and change the views to noneditable. } } Presenting Editing Options to the User A common place in which to use an editable view is in a navigation interface. When implementing your navigation interface, you can include a special Edit button in the navigation bar when your editable view controller is visible. (You can get this button by calling the editButtonItem method of your view controller.) When tapped, this button automatically toggles between an Edit and Done button and calls your view controller’s setEditing:animated: method with appropriate values. You can also call this method from your own code (or modify the value of your view controller’s editing property) to toggle between modes. For more information about adding an Edit button to a navigation bar, see View Controller Catalog for iOS . Enabling Edit Mode in a