13 "github.com/mjl-/mox/admin"
14 "github.com/mjl-/mox/smtp"
17// Apple software isn't good at autoconfig/autodiscovery, but it can import a
18// device management profile containing account settings.
20// See https://developer.apple.com/documentation/devicemanagement/mail.
21type deviceManagementProfile struct {
22 XMLName xml.Name `xml:"plist"`
23 Version string `xml:"version,attr"`
24 Dict dict `xml:"dict"`
29type dict map[string]any
31// MarshalXML marshals as <dict> with multiple pairs of <key> and a value of various types.
32func (m dict) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
33 // The plist format isn't that easy to generate with Go's xml package, it's leaving
34 // out reasonable structure, instead just concatenating key/value pairs. Perhaps
35 // there is a better way?
37 if err := e.EncodeToken(xml.StartElement{Name: xml.Name{Local: "dict"}}); err != nil {
40 l := slices.Sorted(maps.Keys(m))
42 tokens := []xml.Token{
43 xml.StartElement{Name: xml.Name{Local: "key"}},
44 xml.CharData([]byte(k)),
45 xml.EndElement{Name: xml.Name{Local: "key"}},
47 for _, t := range tokens {
48 if err := e.EncodeToken(t); err != nil {
54 switch v := m[k].(type) {
57 xml.StartElement{Name: xml.Name{Local: "string"}},
58 xml.CharData([]byte(v)),
59 xml.EndElement{Name: xml.Name{Local: "string"}},
63 xml.StartElement{Name: xml.Name{Local: "integer"}},
64 xml.CharData(fmt.Appendf(nil, "%d", v)),
65 xml.EndElement{Name: xml.Name{Local: "integer"}},
73 xml.StartElement{Name: xml.Name{Local: tag}},
74 xml.EndElement{Name: xml.Name{Local: tag}},
77 if err := e.EncodeToken(xml.StartElement{Name: xml.Name{Local: "array"}}); err != nil {
81 if err := d.MarshalXML(e, xml.StartElement{Name: xml.Name{Local: "array"}}); err != nil {
85 if err := e.EncodeToken(xml.EndElement{Name: xml.Name{Local: "array"}}); err != nil {
89 return fmt.Errorf("unexpected dict value of type %T", v)
91 for _, t := range tokens {
92 if err := e.EncodeToken(t); err != nil {
97 if err := e.EncodeToken(xml.EndElement{Name: xml.Name{Local: "dict"}}); err != nil {
103// MobileConfig returns a device profile for a macOS Mail email account. The file
104// should have a .mobileconfig extension. Opening the file adds it to Profiles in
105// System Preferences, where it can be installed. This profile does not contain a
106// password because sending opaque files containing passwords around to users seems
107// like bad security practice.
109// Multiple addresses can be passed, the first is used for IMAP/submission login,
110// and likely seen as primary account by Apple software.
112// The config is not signed, so users must ignore warnings about unsigned profiles.
113func MobileConfig(addresses []string, fullName string) ([]byte, error) {
114 if len(addresses) == 0 {
115 return nil, fmt.Errorf("need at least 1 address")
117 addr, err := smtp.ParseAddress(addresses[0])
119 return nil, fmt.Errorf("parsing address: %v", err)
122 config, err := admin.ClientConfigDomain(addr.Domain)
124 return nil, fmt.Errorf("getting config for domain: %v", err)
127 // Apple software wants identifiers...
128 t := strings.Split(addr.Domain.Name(), ".")
130 reverseAddr := strings.Join(t, ".") + "." + addr.Localpart.String()
132 // Apple software wants UUIDs... We generate them deterministically based on address
133 // and our code (through key, which we must change if code changes).
135 uuid := func(prefix string) string {
136 mac := hmac.New(sha256.New, []byte(key))
137 mac.Write([]byte(prefix + "\n" + "\n" + strings.Join(addresses, ",")))
139 uuid := fmt.Sprintf("%x-%x-%x-%x-%x", sum[0:4], sum[4:6], sum[6:8], sum[8:10], sum[10:16])
143 uuidConfig := uuid("config")
144 uuidAccount := uuid("account")
146 // The "UseSSL" fields are underspecified in Apple's format. They say "If true,
147 // enables SSL for authentication on the incoming mail server.". I'm assuming they
148 // want to know if they should start immediately with a handshake, instead of
149 // starting out plain. There is no way to require STARTTLS though. You could even
150 // interpret their wording as this field enable authentication through client-side
151 // TLS certificates, given their "on the incoming mail server", instead of "of the
152 // incoming mail server".
155 p := deviceManagementProfile{
157 Dict: dict(map[string]any{
158 "PayloadDisplayName": fmt.Sprintf("%s email account", addresses[0]),
159 "PayloadIdentifier": reverseAddr + ".email",
160 "PayloadType": "Configuration",
161 "PayloadUUID": uuidConfig,
163 "PayloadContent": array{
165 "EmailAccountDescription": addresses[0],
166 "EmailAccountName": fullName,
167 "EmailAccountType": "EmailTypeIMAP",
168 // Comma-separated multiple addresses are not documented at Apple, but seem to
170 "EmailAddress": strings.Join(addresses, ","),
171 "IncomingMailServerAuthentication": "EmailAuthCRAMMD5", // SCRAM not an option at time of writing..
172 "IncomingMailServerUsername": addresses[0],
173 "IncomingMailServerHostName": config.IMAP.Host.ASCII,
174 "IncomingMailServerPortNumber": config.IMAP.Port,
175 "IncomingMailServerUseSSL": config.IMAP.TLSMode == admin.TLSModeImmediate,
176 "OutgoingMailServerAuthentication": "EmailAuthCRAMMD5", // SCRAM not an option at time of writing...
177 "OutgoingMailServerHostName": config.Submission.Host.ASCII,
178 "OutgoingMailServerPortNumber": config.Submission.Port,
179 "OutgoingMailServerUsername": addresses[0],
180 "OutgoingMailServerUseSSL": config.Submission.TLSMode == admin.TLSModeImmediate,
181 "OutgoingPasswordSameAsIncomingPassword": true,
182 "PayloadIdentifier": reverseAddr + ".email.account",
183 "PayloadType": "com.apple.mail.managed",
184 "PayloadUUID": uuidAccount,
190 if _, err := fmt.Fprint(&w, xml.Header); err != nil {
193 if _, err := fmt.Fprint(&w, "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"); err != nil {
196 enc := xml.NewEncoder(&w)
198 if err := enc.Encode(p); err != nil {
201 if _, err := fmt.Fprintln(&w); err != nil {
204 return w.Bytes(), nil