This repository has been archived by the owner on Apr 11, 2020. It is now read-only.
/
UEAuthentication.go
316 lines (269 loc) · 13.2 KB
/
UEAuthentication.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
package ausf_producer
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"github.com/bronze1man/radius"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
// Nudm_UEAU "free5gc/lib/Nudm_UEAuthentication"
"free5gc/lib/UeauCommon"
"free5gc/lib/openapi/models"
"free5gc/src/ausf/ausf_context"
"free5gc/src/ausf/ausf_handler/ausf_message"
"free5gc/src/ausf/logger"
"math/rand"
"net/http"
"strings"
"time"
)
func HandleEapAuthComfirmRequest(respChan chan ausf_message.HandlerResponseMessage, id string, body models.EapSession) {
var response models.EapSession
if !ausf_context.CheckIfSuciSupiPairExists(id) {
logger.Auth5gAkaComfirmLog.Infoln("supiSuciPair does not exist, confirmation failed")
var problemDetails models.ProblemDetails
problemDetails.Cause = "USER_NOT_FOUND"
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusBadRequest, problemDetails)
return
}
currentSupi := ausf_context.GetSupiFromSuciSupiMap(id)
if !ausf_context.CheckIfAusfUeContextExists(currentSupi) {
logger.Auth5gAkaComfirmLog.Infoln("SUPI does not exist, confirmation failed")
var problemDetails models.ProblemDetails
problemDetails.Cause = "USER_NOT_FOUND"
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusBadRequest, problemDetails)
return
}
ausfCurrentContext := ausf_context.GetAusfUeContext(currentSupi)
servingNetworkName := ausfCurrentContext.ServingNetworkName
eapPayload, _ := base64.StdEncoding.DecodeString(body.EapPayload)
// fmt.Printf("eapPayload = %x\n", eapPayload)
eapGoPkt := gopacket.NewPacket(eapPayload, layers.LayerTypeEAP, gopacket.Default)
eapLayer := eapGoPkt.Layer(layers.LayerTypeEAP)
eapContent, _ := eapLayer.(*layers.EAP)
// fmt.Printf("d.Code=%x,\nd.Identitifier=%x,\nd.Type=%x,\nd.Data=%x\n", eapContent.Code, eapContent.Id, eapContent.Type, eapContent.TypeData)
if eapContent.Code != layers.EAPCodeResponse {
logConfirmFailureAndInformUDM(id, models.AuthType_EAP_AKA_PRIME, servingNetworkName, "eap packet code error", ausfCurrentContext.UdmUeauUrl)
ausfCurrentContext.AuthStatus = models.AuthResult_FAILURE
response.AuthResult = models.AuthResult_ONGOING
failEapAkaNoti := ConstructFailEapAkaNotification(eapContent.Id)
response.EapPayload = failEapAkaNoti
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusOK, response)
return
}
switch ausfCurrentContext.AuthStatus {
case models.AuthResult_ONGOING:
response.KSeaf = ausfCurrentContext.Kseaf
response.Supi = currentSupi
Kautn := ausfCurrentContext.K_aut
XRES := ausfCurrentContext.XRES
RES, decodeOK := decodeResMac(eapContent.TypeData, eapContent.Contents, Kautn)
if !decodeOK {
ausfCurrentContext.AuthStatus = models.AuthResult_FAILURE
response.AuthResult = models.AuthResult_ONGOING
logConfirmFailureAndInformUDM(id, models.AuthType_EAP_AKA_PRIME, servingNetworkName, "eap packet decode error", ausfCurrentContext.UdmUeauUrl)
failEapAkaNoti := ConstructFailEapAkaNotification(eapContent.Id)
response.EapPayload = failEapAkaNoti
} else if XRES == string(RES) { // decodeOK && XRES == res, auth success
logger.EapAuthComfirmLog.Infoln("Correct RES value, EAP-AKA' auth succeed")
response.AuthResult = models.AuthResult_SUCCESS
eapSuccPkt := ConstructEapNoTypePkt(radius.EapCodeSuccess, eapContent.Id)
response.EapPayload = eapSuccPkt
udmUrl := ausfCurrentContext.UdmUeauUrl
if sendErr := sendAuthResultToUDM(id, models.AuthType_EAP_AKA_PRIME, true, servingNetworkName, udmUrl); sendErr != nil {
logger.EapAuthComfirmLog.Infoln(sendErr.Error())
var problemDetails models.ProblemDetails
problemDetails.Cause = "UPSTREAM_SERVER_ERROR"
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusInternalServerError, problemDetails)
return
}
ausfCurrentContext.AuthStatus = models.AuthResult_SUCCESS
} else { // decodeOK but XRES != res, auth failed
// fmt.Printf("XRES = %x\nstring(RES) = %x\n", XRES, RES)
ausfCurrentContext.AuthStatus = models.AuthResult_FAILURE
response.AuthResult = models.AuthResult_ONGOING
logConfirmFailureAndInformUDM(id, models.AuthType_EAP_AKA_PRIME, servingNetworkName, "Wrong RES value, EAP-AKA' auth failed", ausfCurrentContext.UdmUeauUrl)
failEapAkaNoti := ConstructFailEapAkaNotification(eapContent.Id)
response.EapPayload = failEapAkaNoti
}
case models.AuthResult_FAILURE:
eapFailPkt := ConstructEapNoTypePkt(radius.EapCodeFailure, uint8(eapPayload[1]))
response.EapPayload = eapFailPkt
response.AuthResult = models.AuthResult_FAILURE
}
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusOK, response)
}
func HandleAuth5gAkaComfirmRequest(respChan chan ausf_message.HandlerResponseMessage, id string, body models.ConfirmationData) {
var response models.ConfirmationDataResponse
success := false
response.AuthResult = models.AuthResult_FAILURE
if !ausf_context.CheckIfSuciSupiPairExists(id) {
logger.Auth5gAkaComfirmLog.Infof("supiSuciPair does not exist, confirmation failed (queried by %s)\n", id)
var problemDetails models.ProblemDetails
problemDetails.Cause = "USER_NOT_FOUND"
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusBadRequest, problemDetails)
return
}
currentSupi := ausf_context.GetSupiFromSuciSupiMap(id)
if !ausf_context.CheckIfAusfUeContextExists(currentSupi) {
logger.Auth5gAkaComfirmLog.Infof("SUPI does not exist, confirmation failed (queried by %s)\n", currentSupi)
var problemDetails models.ProblemDetails
problemDetails.Cause = "USER_NOT_FOUND"
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusBadRequest, problemDetails)
return
}
ausfCurrentContext := ausf_context.GetAusfUeContext(currentSupi)
servingNetworkName := ausfCurrentContext.ServingNetworkName
// Compare the received RES* with the stored XRES*
logger.Auth5gAkaComfirmLog.Infof("res*: %x\nXres*: %x\n", body.ResStar, ausfCurrentContext.XresStar)
if strings.Compare(body.ResStar, ausfCurrentContext.XresStar) == 0 {
ausfCurrentContext.AuthStatus = models.AuthResult_SUCCESS
response.AuthResult = models.AuthResult_SUCCESS
success = true
logger.Auth5gAkaComfirmLog.Infoln("5G AKA confirmation succeeded")
response.Kseaf = ausfCurrentContext.Kseaf
} else {
ausfCurrentContext.AuthStatus = models.AuthResult_FAILURE
response.AuthResult = models.AuthResult_FAILURE
logConfirmFailureAndInformUDM(id, models.AuthType__5_G_AKA, servingNetworkName, "5G AKA confirmation failed", ausfCurrentContext.UdmUeauUrl)
}
if sendErr := sendAuthResultToUDM(id, models.AuthType__5_G_AKA, success, servingNetworkName, ausfCurrentContext.UdmUeauUrl); sendErr != nil {
logger.Auth5gAkaComfirmLog.Infoln(sendErr.Error())
var problemDetails models.ProblemDetails
problemDetails.Cause = "UPSTREAM_SERVER_ERROR"
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusInternalServerError, problemDetails)
return
}
response.Supi = currentSupi
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusOK, response)
}
func HandleUeAuthPostRequest(respChan chan ausf_message.HandlerResponseMessage, body models.AuthenticationInfo) {
var response models.UeAuthenticationCtx
var authInfoReq models.AuthenticationInfoRequest
supiOrSuci := body.SupiOrSuci
// fmt.Println("Got supi:", supiOrSuci)
// check if SEAF is authorized to use the serving network name as in 33501 clause 6.1.2
snName := body.ServingNetworkName
servingNetworkAuthorized := ausf_context.IsServingNetworkAuthorized(snName)
if !servingNetworkAuthorized {
var problemDetails models.ProblemDetails
problemDetails.Cause = "SERVING_NETWORK_NOT_AUTHORIZED"
logger.UeAuthPostLog.Infoln("403 forbidden: serving network NOT AUTHORIZED")
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusForbidden, problemDetails)
return
}
logger.UeAuthPostLog.Infoln("Serving network authorized")
response.ServingNetworkName = snName
authInfoReq.ServingNetworkName = snName
self := ausf_context.GetSelf()
authInfoReq.AusfInstanceId = self.GetSelfID()
udmUrl := getUdmUrl(self.NrfUri)
client := createClientToUdmUeau(udmUrl)
authInfoResult, _, err := client.GenerateAuthDataApi.GenerateAuthData(context.Background(), supiOrSuci, authInfoReq)
if err != nil {
logger.UeAuthPostLog.Infoln(err.Error())
var problemDetails models.ProblemDetails
if authInfoResult.AuthenticationVector == nil {
problemDetails.Cause = "AV_GENERATION_PROBLEM"
} else {
problemDetails.Cause = "UPSTREAM_SERVER_ERROR"
}
ausf_message.SendHttpResponseMessage(respChan, nil, http.StatusInternalServerError, problemDetails)
return
}
ueid := authInfoResult.Supi
ausfUeContext := ausf_context.NewAusfUeContext(ueid)
ausf_context.AddAusfUeContextToPool(ausfUeContext)
ausfUeContext.ServingNetworkName = snName
ausfUeContext.AuthStatus = models.AuthResult_ONGOING
ausfUeContext.UdmUeauUrl = udmUrl
logger.UeAuthPostLog.Infof("Add SuciSupiPair (%s, %s) to map.\n", supiOrSuci, ueid)
ausf_context.AddSuciSupiPairToMap(supiOrSuci, ueid)
locationURI := self.Url + "/nausf-auth/v1/ue-authentications/" + supiOrSuci
putLink := locationURI
if authInfoResult.AuthType == models.AuthType__5_G_AKA {
logger.UeAuthPostLog.Infoln("Use 5G AKA auth method")
putLink += "/5g-aka-confirmation"
// Derive HXRES* from XRES*
concat := authInfoResult.AuthenticationVector.Rand + authInfoResult.AuthenticationVector.XresStar
hxresStarBytes, _ := hex.DecodeString(concat)
hxresStarAll := sha256.Sum256(hxresStarBytes)
hxresStar := hex.EncodeToString(hxresStarAll[16:]) // last 128 bits
// logger.Auth5gAkaComfirmLog.Infof("5G AV Rand: %s, Autn: %s\n", authInfoResult.AuthenticationVector.Rand, authInfoResult.AuthenticationVector.Autn)
logger.Auth5gAkaComfirmLog.Infof("XresStar = %x\n", authInfoResult.AuthenticationVector.XresStar)
// logger.Auth5gAkaComfirmLog.Infof("hxresStar = %x\n", hxresStar) // 231b3f2e0a8a5082c19fdd6735888c4a
// Derive Kseaf from Kausf
// Test data
// P0 := "internet"
Kausf := authInfoResult.AuthenticationVector.Kausf
KausfDecode, _ := hex.DecodeString(Kausf)
P0 := []byte(snName)
Kseaf := UeauCommon.GetKDFValue(KausfDecode, UeauCommon.FC_FOR_KSEAF_DERIVATION, P0, UeauCommon.KDFLen(P0))
ausfUeContext.XresStar = authInfoResult.AuthenticationVector.XresStar
ausfUeContext.Kausf = Kausf
ausfUeContext.Kseaf = hex.EncodeToString(Kseaf)
var av5gAka models.Av5gAka
av5gAka.Rand = authInfoResult.AuthenticationVector.Rand
av5gAka.Autn = authInfoResult.AuthenticationVector.Autn
av5gAka.HxresStar = hxresStar
response.Var5gAuthData = av5gAka
} else if authInfoResult.AuthType == models.AuthType_EAP_AKA_PRIME {
logger.UeAuthPostLog.Infoln("Use EAP-AKA' auth method")
putLink += "/eap-session"
identity := ueid
ikPrime := authInfoResult.AuthenticationVector.IkPrime
ckPrime := authInfoResult.AuthenticationVector.CkPrime
RAND := authInfoResult.AuthenticationVector.Rand
AUTN := authInfoResult.AuthenticationVector.Autn
XRES := authInfoResult.AuthenticationVector.Xres
ausfUeContext.XRES = XRES
// Test data
// identity = "0555444333222111"
K_encr, K_aut, K_re, MSK, EMSK := eapAkaPrimePrf(ikPrime, ckPrime, identity)
_, _, _, _, _ = K_encr, K_aut, K_re, MSK, EMSK
ausfUeContext.K_aut = K_aut
Kausf := EMSK[0:32]
ausfUeContext.Kausf = Kausf
KausfDecode, _ := hex.DecodeString(Kausf)
P0 := []byte(snName)
Kseaf := UeauCommon.GetKDFValue(KausfDecode, UeauCommon.FC_FOR_KSEAF_DERIVATION, P0, UeauCommon.KDFLen(P0))
ausfUeContext.Kseaf = hex.EncodeToString(Kseaf)
var eapPkt radius.EapPacket
var randIdentifier int
rand.Seed(time.Now().Unix())
eapPkt.Code = radius.EapCode(1)
randIdentifier = rand.Intn(256)
eapPkt.Identifier = uint8(randIdentifier)
eapPkt.Type = radius.EapType(50) // accroding to RFC5448 6.1
atRand, _ := EapEncodeAttribute("AT_RAND", RAND)
atAutn, _ := EapEncodeAttribute("AT_AUTN", AUTN)
atKdf, _ := EapEncodeAttribute("AT_KDF", snName)
atKdfInput, _ := EapEncodeAttribute("AT_KDF_INPUT", snName)
atMAC, _ := EapEncodeAttribute("AT_MAC", "")
dataArrayBeforeMAC := atRand + atAutn + atMAC + atKdf + atKdfInput
eapPkt.Data = []byte(dataArrayBeforeMAC)
encodedPktBeforeMAC := eapPkt.Encode()
MACvalue := CalculateAtMAC([]byte(K_aut), encodedPktBeforeMAC)
// fmt.Printf("MAC value = %x\n", MACvalue)
atMacNum := fmt.Sprintf("%02x", ausf_context.AT_MAC_ATTRIBUTE)
atMACfirstRow, _ := hex.DecodeString(atMacNum + "05" + "0000")
wholeAtMAC := append(atMACfirstRow, MACvalue...)
atMAC = string(wholeAtMAC)
dataArrayAfterMAC := atRand + atAutn + atMAC + atKdf + atKdfInput
eapPkt.Data = []byte(dataArrayAfterMAC)
encodedPktAfterMAC := eapPkt.Encode()
response.Var5gAuthData = base64.StdEncoding.EncodeToString(encodedPktAfterMAC)
// fmt.Printf("p.Code=%x,\np.Identitifier=%x,\np.Type=%x,\np.Data=%x\n", byte(eapPkt.Code), byte(eapPkt.Identifier), byte(eapPkt.Type), eapPkt.Data)
// fmt.Printf("encodedPktAfterMAC: %x\n", encodedPktAfterMAC)
// fmt.Printf("Var5gAuthData: %x\n", response.Var5gAuthData)
}
var linksValue = models.LinksValueSchema{Href: putLink}
response.Links = make(map[string]models.LinksValueSchema)
response.Links["link"] = linksValue
response.AuthType = authInfoResult.AuthType
respHeader := make(http.Header)
respHeader.Set("Location", locationURI)
ausf_message.SendHttpResponseMessage(respChan, respHeader, http.StatusCreated, response)
}