forked from fiveai/goipa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipa.go
411 lines (333 loc) · 8.76 KB
/
ipa.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Copyright 2015 Andrew E. Bruno. All rights reserved.
// Use of this source code is governed by a BSD style
// license that can be found in the LICENSE file.
// Package ipa is a Go client library for FreeIPA
package ipa
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/tustvold/kerby/khttp"
)
const (
IpaClientVersion = "2.156"
IpaDatetimeFormat = "20060102150405Z"
)
var (
ipaCertPool *x509.CertPool
ipaSessionPattern = regexp.MustCompile(`^ipa_session=([^;]+);`)
)
// FreeIPA Client
type Client struct {
Host string
CaCert string
KeyTab string
Insecure bool
session string
}
// FreeIPA Password Policy Error
type ErrPasswordPolicy struct {
}
func (e *ErrPasswordPolicy) Error() string {
return "ipa: password does not conform to policy"
}
// FreeIPA Invalid Password Error
type ErrInvalidPassword struct {
}
func (e *ErrInvalidPassword) Error() string {
return "ipa: invalid current password"
}
// FreeIPA error
type IpaError struct {
Message string
Code int
}
// Custom FreeIPA bool type
type IpaBool bool
// Custom FreeIPA string type
type IpaString string
// Custom FreeIPA int type
type IpaInt int
// Custom FreeIPA float64 type
type IpaFloat float64
// Custom FreeIPA DNSName type
type IpaDNSName string
// Custom FreeIPA datetime type
type IpaDateTime time.Time
// Result returned from a FreeIPA JSON rpc call
type Result struct {
Summary string `json:"summary"`
Value interface{} `json:"value"`
Data json.RawMessage `json:"result"`
}
// Response returned from a FreeIPA JSON rpc call
type Response struct {
Error *IpaError `json:"error"`
Id string `json:"id"`
Principal string `json:"principal"`
Version string `json:"version"`
Result *Result `json:"result"`
}
func init() {
// If ca.crt for ipa exists, use it as the cert pool
// otherwise default to system root ca.
pem, err := ioutil.ReadFile("/etc/ipa/ca.crt")
if err == nil {
ipaCertPool = x509.NewCertPool()
if !ipaCertPool.AppendCertsFromPEM(pem) {
ipaCertPool = nil
}
}
}
// Unmarshal a FreeIPA datetime. Datetimes in FreeIPA are returned using a
// class-hint system. Values are stored as an array with a single element
// indicating the type and value, for example, '[{"__datetime__": "YYYY-MM-DDTHH:MM:SSZ"]}'
func (dt *IpaDateTime) UnmarshalJSON(b []byte) error {
var a []map[string]string
err := json.Unmarshal(b, &a)
if err != nil {
return err
}
if len(a) == 0 {
return nil
}
if str, ok := a[0]["__datetime__"]; ok {
t, err := time.Parse(IpaDatetimeFormat, str)
if err != nil {
return err
}
*dt = IpaDateTime(t)
}
return nil
}
func (dt *IpaDateTime) UnmarshalBinary(data []byte) error {
t := time.Time(*dt)
err := t.UnmarshalBinary(data)
if err != nil {
return err
}
*dt = IpaDateTime(t)
return nil
}
func (dt *IpaDateTime) MarshalBinary() (data []byte, err error) {
return time.Time(*dt).MarshalBinary()
}
func (dt *IpaDateTime) String() string {
return time.Time(*dt).String()
}
func (dt *IpaDateTime) Format(layout string) string {
return time.Time(*dt).Format(layout)
}
// Unmarshal a FreeIPA string from an array of strings. Uses the first value
// in the array as the value of the string.
func (s *IpaString) UnmarshalJSON(b []byte) error {
var a []string
err := json.Unmarshal(b, &a)
if err != nil {
return err
}
if len(a) > 0 {
*s = IpaString(a[0])
}
return nil
}
func (s *IpaString) String() string {
return string(*s)
}
// Unmarshal a FreeIPA string from an array of strings. Uses the first value
// in the array as the value of the string.
func (s *IpaDNSName) UnmarshalJSON(b []byte) error {
var a []map[string]string
err := json.Unmarshal(b, &a)
if err != nil {
return err
}
if len(a) == 0 {
return nil
}
*s = IpaDNSName(a[0]["__dns_name__"])
return nil
}
func (s *IpaDNSName) String() string {
return string(*s)
}
// Unmarshal a FreeIPA Int from an array of strings. Uses the first value
// in the array as the value of the string.
func (s *IpaInt) UnmarshalJSON(b []byte) error {
var a []string
err := json.Unmarshal(b, &a)
if err != nil {
return err
}
if len(a) == 0 {
return nil
}
val, err := strconv.Atoi(a[0])
if err != nil {
return err
}
*s = IpaInt(val)
return nil
}
// Unmarshal a FreeIPA Float from an array of strings. Uses the first value
// in the array as the value of the string.
func (s *IpaFloat) UnmarshalJSON(b []byte) error {
var a []string
err := json.Unmarshal(b, &a)
if err != nil {
return err
}
if len(a) == 0 {
return nil
}
val, err := strconv.ParseFloat(a[0], 64)
if err != nil {
return err
}
*s = IpaFloat(val)
return nil
}
// Unmarshal a FreeIPA DNS Name from an array of strings. Uses the first value
// in the array as the value of the bool.
func (s *IpaBool) UnmarshalJSON(b []byte) error {
var a []string
err := json.Unmarshal(b, &a)
if err != nil {
return err
}
if len(a) == 0 {
return nil
}
*s = IpaBool(s.parseBool(a[0]))
return nil
}
// Unmarshal a FreeIPA bool from an array of strings. Uses the first value
// in the array as the value of the bool.
func (s *IpaBool) parseBool(val string) bool {
switch val {
case "TRUE":
return true
case "FALSE":
return false
default:
return false
}
}
func (e *IpaError) Error() string {
return fmt.Sprintf("ipa: error %d - %s", e.Code, e.Message)
}
// Set FreeIPA session id
func (c *Client) SetSession(sid string) {
c.session = sid
}
// Clears out FreeIPA session id
func (c *Client) ClearSession() {
c.session = ""
}
func (c *Client) rpc(method string, params []string, options map[string]interface{}) (*Response, error) {
options["version"] = IpaClientVersion
var data []interface{} = make([]interface{}, 2)
data[0] = params
data[1] = options
payload := map[string]interface{}{
"method": method,
"params": data}
b, err := json.Marshal(payload)
if err != nil {
return nil, err
}
ipaUrl := fmt.Sprintf("https://%s/ipa/json", c.Host)
if len(c.session) > 0 {
ipaUrl = fmt.Sprintf("https://%s/ipa/session/json", c.Host)
}
req, err := http.NewRequest("POST", ipaUrl, bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Referer", fmt.Sprintf("https://%s/ipa", c.Host))
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: ipaCertPool, InsecureSkipVerify: c.Insecure}}
client := &http.Client{Transport: tr}
if len(c.session) > 0 {
// If session is set, use the session id
req.Header.Set("Cookie", fmt.Sprintf("ipa_session=%s", c.session))
} else {
// default to using Kerberos auth (SPNEGO)
client.Transport = &khttp.Transport{Next: tr, KeyTab: c.KeyTab}
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, fmt.Errorf("IPA RPC called failed with HTTP status code: %d", res.StatusCode)
}
// XXX use the stream decoder here instead of reading entire body?
//decoder := json.NewDecoder(res.Body)
rawJson, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var ipaRes Response
err = json.Unmarshal(rawJson, &ipaRes)
if err != nil {
return nil, err
}
if ipaRes.Error != nil {
return nil, ipaRes.Error
}
return &ipaRes, nil
}
// Ping FreeIPA server to check connection
func (c *Client) Ping() (*Response, error) {
options := map[string]interface{}{}
res, err := c.rpc("ping", []string{}, options)
if err != nil {
return nil, err
}
return res, nil
}
// Login to FreeIPA with uid/passwd and set the FreeIPA session id on the
// client for subsequent requests.
func (c *Client) Login(uid, passwd string) (string, error) {
ipaUrl := fmt.Sprintf("https://%s/ipa/session/login_password", c.Host)
form := url.Values{"user": {uid}, "password": {passwd}}
req, err := http.NewRequest("POST", ipaUrl, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Referer", fmt.Sprintf("https://%s/ipa", c.Host))
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: ipaCertPool, InsecureSkipVerify: c.Insecure}}
client := &http.Client{Transport: tr}
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return "", fmt.Errorf("IPA login failed with HTTP status code: %d", res.StatusCode)
}
cookie := res.Header.Get("Set-Cookie")
if len(cookie) == 0 {
return "", errors.New("ipa: login failed emtpy set-cookie header")
}
ipaSession := ""
matches := ipaSessionPattern.FindStringSubmatch(cookie)
if len(matches) == 2 {
ipaSession = matches[1]
}
if len(ipaSession) == 32 || strings.HasPrefix(ipaSession, "MagBearerToken") {
c.session = ipaSession
} else {
return "", errors.New("ipa: login failed invalid set-cookie header")
}
return ipaSession, nil
}