acme.sh 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269
  1. #!/usr/bin/env bash
  2. VER=2.1.1
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  7. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  8. DEFAULT_USER_AGENT="$PROJECT_ENTRY client: $PROJECT"
  9. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  10. VTYPE_HTTP="http-01"
  11. VTYPE_DNS="dns-01"
  12. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  13. END_CSR="-----END CERTIFICATE REQUEST-----"
  14. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  15. END_CERT="-----END CERTIFICATE-----"
  16. if [[ -z "$AGREEMENT" ]] ; then
  17. AGREEMENT="$DEFAULT_AGREEMENT"
  18. fi
  19. _info() {
  20. if [[ -z "$2" ]] ; then
  21. echo "[$(date)] $1"
  22. else
  23. echo "[$(date)] $1"="'$2'"
  24. fi
  25. }
  26. _err() {
  27. _info "$@" >&2
  28. return 1
  29. }
  30. _debug() {
  31. if [[ -z "$DEBUG" ]] ; then
  32. return
  33. fi
  34. _err "$@"
  35. return 0
  36. }
  37. _debug2() {
  38. if [[ "$DEBUG" ]] && [[ "$DEBUG" -ge "2" ]] ; then
  39. _debug "$@"
  40. fi
  41. return
  42. }
  43. _startswith(){
  44. _str="$1"
  45. _sub="$2"
  46. echo $_str | grep ^$_sub >/dev/null 2>&1
  47. }
  48. _contains(){
  49. _str="$1"
  50. _sub="$2"
  51. echo $_str | grep $_sub >/dev/null 2>&1
  52. }
  53. _exists(){
  54. cmd="$1"
  55. if [[ -z "$cmd" ]] ; then
  56. _err "Usage: _exists cmd"
  57. return 1
  58. fi
  59. if type command >/dev/null 2>&1 ; then
  60. command -v $cmd >/dev/null 2>&1
  61. else
  62. type $cmd >/dev/null 2>&1
  63. fi
  64. ret="$?"
  65. _debug2 "$cmd exists=$ret"
  66. return $ret
  67. }
  68. _h2b() {
  69. hex=$(cat)
  70. i=1
  71. j=2
  72. while [ '1' ] ; do
  73. h=$(printf $hex | cut -c $i-$j)
  74. if [[ -z "$h" ]] ; then
  75. break;
  76. fi
  77. printf "\x$h"
  78. let "i+=2"
  79. let "j+=2"
  80. done
  81. }
  82. #options file
  83. _sed_i() {
  84. options="$1"
  85. filename="$2"
  86. if [[ -z "$filename" ]] ; then
  87. _err "Usage:_sed_i options filename"
  88. return 1
  89. fi
  90. if sed -h 2>&1 | grep "\-i[SUFFIX]" ; then
  91. _debug "Using sed -i"
  92. sed -i ""
  93. else
  94. _debug "No -i support in sed"
  95. text="$(cat $filename)"
  96. echo "$text" | sed "$options" > "$filename"
  97. fi
  98. }
  99. #Usage: file startline endline
  100. _getfile() {
  101. filename="$1"
  102. startline="$2"
  103. endline="$3"
  104. if [[ -z "$endline" ]] ; then
  105. _err "Usage: file startline endline"
  106. return 1
  107. fi
  108. i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
  109. if [[ -z "$i" ]] ; then
  110. _err "Can not find start line: $startline"
  111. return 1
  112. fi
  113. let "i+=1"
  114. _debug i $i
  115. j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
  116. if [[ -z "$j" ]] ; then
  117. _err "Can not find end line: $endline"
  118. return 1
  119. fi
  120. let "j-=1"
  121. _debug j $j
  122. sed -n $i,${j}p "$filename"
  123. }
  124. #Usage: multiline
  125. _base64() {
  126. if [[ "$1" ]] ; then
  127. openssl base64 -e
  128. else
  129. openssl base64 -e | tr -d '\r\n'
  130. fi
  131. }
  132. #Usage: multiline
  133. _dbase64() {
  134. if [[ "$1" ]] ; then
  135. openssl base64 -d -A
  136. else
  137. openssl base64 -d
  138. fi
  139. }
  140. #Usage: hashalg
  141. #Output Base64-encoded digest
  142. _digest() {
  143. alg="$1"
  144. if [[ -z "$alg" ]] ; then
  145. _err "Usage: _digest hashalg"
  146. return 1
  147. fi
  148. if [[ "$alg" == "sha256" ]] ; then
  149. openssl dgst -sha256 -binary | _base64
  150. else
  151. _err "$alg is not supported yet"
  152. return 1
  153. fi
  154. }
  155. #Usage: keyfile hashalg
  156. #Output: Base64-encoded signature value
  157. _sign() {
  158. keyfile="$1"
  159. alg="$2"
  160. if [[ -z "$alg" ]] ; then
  161. _err "Usage: _sign keyfile hashalg"
  162. return 1
  163. fi
  164. if [[ "$alg" == "sha256" ]] ; then
  165. openssl dgst -sha256 -sign "$keyfile" | _base64
  166. else
  167. _err "$alg is not supported yet"
  168. return 1
  169. fi
  170. }
  171. _ss() {
  172. _port="$1"
  173. if _exists "ss" ; then
  174. _debug "Using: ss"
  175. ss -ntpl | grep :$_port" "
  176. return 0
  177. fi
  178. if _exists "netstat" ; then
  179. _debug "Using: netstat"
  180. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  181. #for windows version netstat tool
  182. netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
  183. else
  184. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  185. netstat -an -p tcp | grep LISTEN | grep :$_port" "
  186. else
  187. netstat -ntpl | grep :$_port" "
  188. fi
  189. fi
  190. return 0
  191. fi
  192. return 1
  193. }
  194. toPkcs() {
  195. domain="$1"
  196. pfxPassword="$2"
  197. if [[ -z "$domain" ]] ; then
  198. echo "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  199. return 1
  200. fi
  201. _initpath "$domain"
  202. if [[ "$pfxPassword" ]] ; then
  203. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  204. else
  205. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  206. fi
  207. if [[ "$?" == "0" ]] ; then
  208. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  209. fi
  210. }
  211. #domain [2048]
  212. createAccountKey() {
  213. _info "Creating account key"
  214. if [[ -z "$1" ]] ; then
  215. echo Usage: $PROJECT_ENTRY --createAccountKey -d domain.com [--accountkeylength 2048]
  216. return
  217. fi
  218. account=$1
  219. length=$2
  220. _debug account "$account"
  221. _debug length "$length"
  222. if _startswith "$length" "ec-" ; then
  223. length=2048
  224. fi
  225. if [[ -z "$2" ]] || [[ "$2" == "no" ]] ; then
  226. _info "Use default length 2048"
  227. length=2048
  228. fi
  229. _initpath
  230. if [[ -f "$ACCOUNT_KEY_PATH" ]] ; then
  231. _info "Account key exists, skip"
  232. return
  233. else
  234. #generate account key
  235. openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
  236. fi
  237. }
  238. #domain length
  239. createDomainKey() {
  240. _info "Creating domain key"
  241. if [[ -z "$1" ]] ; then
  242. echo Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]
  243. return
  244. fi
  245. domain=$1
  246. length=$2
  247. isec=""
  248. if _startswith "$length" "ec-" ; then
  249. isec="1"
  250. length=$(printf $length | cut -d '-' -f 2-100)
  251. eccname="$length"
  252. fi
  253. if [[ -z "$length" ]] ; then
  254. if [[ "$isec" ]] ; then
  255. length=256
  256. else
  257. length=2048
  258. fi
  259. fi
  260. _info "Use length $length"
  261. if [[ "$isec" ]] ; then
  262. if [[ "$length" == "256" ]] ; then
  263. eccname="prime256v1"
  264. fi
  265. if [[ "$length" == "384" ]] ; then
  266. eccname="secp384r1"
  267. fi
  268. if [[ "$length" == "521" ]] ; then
  269. eccname="secp521r1"
  270. fi
  271. _info "Using ec name: $eccname"
  272. fi
  273. _initpath $domain
  274. if [[ ! -f "$CERT_KEY_PATH" ]] || ( [[ "$FORCE" ]] && ! [[ "$IS_RENEW" ]] ); then
  275. #generate account key
  276. if [[ "$isec" ]] ; then
  277. openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
  278. else
  279. openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
  280. fi
  281. else
  282. if [[ "$IS_RENEW" ]] ; then
  283. _info "Domain key exists, skip"
  284. return 0
  285. else
  286. _err "Domain key exists, do you want to overwrite the key?"
  287. _err "Add '--force', and try again."
  288. return 1
  289. fi
  290. fi
  291. }
  292. # domain domainlist
  293. createCSR() {
  294. _info "Creating csr"
  295. if [[ -z "$1" ]] ; then
  296. echo Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]
  297. return
  298. fi
  299. domain=$1
  300. _initpath $domain
  301. domainlist=$2
  302. if [[ -f "$CSR_PATH" ]] && [[ "$IS_RENEW" ]] && [[ -z "$FORCE" ]]; then
  303. _info "CSR exists, skip"
  304. return
  305. fi
  306. if [[ -z "$domainlist" ]] || [[ "$domainlist" == "no" ]]; then
  307. #single domain
  308. _info "Single domain" $domain
  309. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
  310. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  311. else
  312. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  313. #multi
  314. _info "Multi domain" "$alt"
  315. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
  316. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  317. fi
  318. }
  319. _urlencode() {
  320. __n=$(cat)
  321. echo $__n | tr '/+' '_-' | tr -d '= '
  322. }
  323. _time2str() {
  324. #BSD
  325. if date -u -d@$1 2>/dev/null ; then
  326. return
  327. fi
  328. #Linux
  329. if date -u -r $1 2>/dev/null ; then
  330. return
  331. fi
  332. }
  333. _stat() {
  334. #Linux
  335. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  336. return
  337. fi
  338. #BSD
  339. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  340. return
  341. fi
  342. }
  343. #keyfile
  344. _calcjwk() {
  345. keyfile="$1"
  346. if [[ -z "$keyfile" ]] ; then
  347. _err "Usage: _calcjwk keyfile"
  348. return 1
  349. fi
  350. EC_SIGN=""
  351. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  352. _debug "RSA key"
  353. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  354. if [[ "${#pub_exp}" == "5" ]] ; then
  355. pub_exp=0$pub_exp
  356. fi
  357. _debug2 pub_exp "$pub_exp"
  358. e=$(echo $pub_exp | _h2b | _base64)
  359. _debug2 e "$e"
  360. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  361. n=$(echo $modulus| _h2b | _base64 | _urlencode )
  362. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  363. _debug2 jwk "$jwk"
  364. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  365. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  366. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  367. _debug "EC key"
  368. EC_SIGN="1"
  369. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  370. _debug2 crv $crv
  371. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  372. _debug2 pubi $pubi
  373. let "pubi=pubi+1"
  374. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  375. _debug2 pubj $pubj
  376. let "pubj=pubj-1"
  377. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  378. _debug2 pubtext "$pubtext"
  379. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  380. let "xlen=xlen/4"
  381. _debug2 xlen $xlen
  382. let "xend=xlen+1"
  383. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  384. _debug2 x $x
  385. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  386. _debug2 x64 $x64
  387. let "xend+=1"
  388. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  389. _debug2 y $y
  390. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  391. _debug2 y64 $y64
  392. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  393. _debug2 jwk "$jwk"
  394. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  395. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  396. else
  397. _err "Only RSA or EC key is supported."
  398. return 1
  399. fi
  400. _debug2 HEADER "$HEADER"
  401. }
  402. # body url [needbase64]
  403. _post() {
  404. body="$1"
  405. url="$2"
  406. needbase64="$3"
  407. if _exists "curl" ; then
  408. CURL="$CURL --dump-header $HTTP_HEADER "
  409. if [[ "$needbase64" ]] ; then
  410. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url | _base64)"
  411. else
  412. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url)"
  413. fi
  414. else
  415. if [[ "$needbase64" ]] ; then
  416. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
  417. else
  418. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER")"
  419. fi
  420. _sed_i "s/^ *//g" "$HTTP_HEADER"
  421. fi
  422. echo -n "$response"
  423. }
  424. # url getheader
  425. _get() {
  426. url="$1"
  427. onlyheader="$2"
  428. _debug url $url
  429. if _exists "curl" ; then
  430. if [[ "$onlyheader" ]] ; then
  431. $CURL -I -A "User-Agent: $USER_AGENT" $url
  432. else
  433. $CURL -A "User-Agent: $USER_AGENT" $url
  434. fi
  435. else
  436. _debug "WGET" "$WGET"
  437. if [[ "$onlyheader" ]] ; then
  438. eval $WGET --user-agent=\"$USER_AGENT\" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  439. else
  440. eval $WGET --user-agent=\"$USER_AGENT\" -O - $url
  441. fi
  442. fi
  443. ret=$?
  444. return $ret
  445. }
  446. # url payload needbase64 keyfile
  447. _send_signed_request() {
  448. url=$1
  449. payload=$2
  450. needbase64=$3
  451. keyfile=$4
  452. if [[ -z "$keyfile" ]] ; then
  453. keyfile="$ACCOUNT_KEY_PATH"
  454. fi
  455. _debug url $url
  456. _debug payload "$payload"
  457. if ! _calcjwk "$keyfile" ; then
  458. return 1
  459. fi
  460. payload64=$(echo -n $payload | _base64 | _urlencode)
  461. _debug2 payload64 $payload64
  462. nonceurl="$API/directory"
  463. nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
  464. _debug nonce "$nonce"
  465. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  466. _debug2 protected "$protected"
  467. protected64="$(printf "$protected" | _base64 | _urlencode)"
  468. _debug2 protected64 "$protected64"
  469. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  470. _debug2 sig "$sig"
  471. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  472. _debug2 body "$body"
  473. response="$(_post "$body" $url "$needbase64" )"
  474. responseHeaders="$(cat $HTTP_HEADER)"
  475. _debug2 responseHeaders "$responseHeaders"
  476. _debug2 response "$response"
  477. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  478. _debug code $code
  479. }
  480. #setopt "file" "opt" "=" "value" [";"]
  481. _setopt() {
  482. __conf="$1"
  483. __opt="$2"
  484. __sep="$3"
  485. __val="$4"
  486. __end="$5"
  487. if [[ -z "$__opt" ]] ; then
  488. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  489. return
  490. fi
  491. if [[ ! -f "$__conf" ]] ; then
  492. touch "$__conf"
  493. fi
  494. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  495. _debug2 OK
  496. if _contains "$__val" "&" ; then
  497. __val="$(echo $__val | sed 's/&/\\&/g')"
  498. fi
  499. text="$(cat $__conf)"
  500. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  501. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  502. if _contains "$__val" "&" ; then
  503. __val="$(echo $__val | sed 's/&/\\&/g')"
  504. fi
  505. text="$(cat $__conf)"
  506. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  507. else
  508. _debug2 APP
  509. echo "$__opt$__sep$__val$__end" >> "$__conf"
  510. fi
  511. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  512. }
  513. #_savedomainconf key value
  514. #save to domain.conf
  515. _savedomainconf() {
  516. key="$1"
  517. value="$2"
  518. if [[ "$DOMAIN_CONF" ]] ; then
  519. _setopt $DOMAIN_CONF "$key" "=" "$value"
  520. else
  521. _err "DOMAIN_CONF is empty, can not save $key=$value"
  522. fi
  523. }
  524. #_saveaccountconf key value
  525. _saveaccountconf() {
  526. key="$1"
  527. value="$2"
  528. if [[ "$ACCOUNT_CONF_PATH" ]] ; then
  529. _setopt $ACCOUNT_CONF_PATH "$key" "=" "\"$value\""
  530. else
  531. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  532. fi
  533. }
  534. _startserver() {
  535. content="$1"
  536. _debug "startserver: $$"
  537. nchelp="$(nc -h 2>&1)"
  538. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  539. _NC="nc -q 1 -l"
  540. else
  541. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  542. _NC="nc -c -l"
  543. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  544. _NC="nc -N -l"
  545. else
  546. _NC="nc -l"
  547. fi
  548. fi
  549. _debug "_NC" "$_NC"
  550. # while true ; do
  551. if [[ "$DEBUG" ]] ; then
  552. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort -vv ; then
  553. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort -vv ;
  554. fi
  555. else
  556. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  557. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  558. fi
  559. fi
  560. if [[ "$?" != "0" ]] ; then
  561. _err "nc listen error."
  562. exit 1
  563. fi
  564. # done
  565. }
  566. _stopserver(){
  567. pid="$1"
  568. _debug "pid" "$pid"
  569. if [[ -z "$pid" ]] ; then
  570. return
  571. fi
  572. if [[ "$(ps | grep "$pid")" ]] ; then
  573. _debug "Found proc process, kill it."
  574. kill -s 9 $pid > /dev/null
  575. fi
  576. for ncid in $(echo $(ps | grep nc) | cut -d " " -f 1) ; do
  577. _debug "kill $ncid"
  578. kill -s 9 $ncid > /dev/null
  579. done
  580. _get "http://localhost:$Le_HTTPPort" >/dev/null 2>&1
  581. }
  582. _initpath() {
  583. if [[ -z "$LE_WORKING_DIR" ]] ; then
  584. LE_WORKING_DIR=$HOME/.$PROJECT_NAME
  585. fi
  586. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  587. if [[ -z "$ACCOUNT_CONF_PATH" ]] ; then
  588. if [[ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]] ; then
  589. source "$_DEFAULT_ACCOUNT_CONF_PATH"
  590. fi
  591. fi
  592. if [[ -z "$ACCOUNT_CONF_PATH" ]] ; then
  593. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  594. fi
  595. if [[ -f "$ACCOUNT_CONF_PATH" ]] ; then
  596. source "$ACCOUNT_CONF_PATH"
  597. fi
  598. if [[ "$IN_CRON" ]] ; then
  599. if [[ ! "$_USER_PATH_EXPORTED" ]] ; then
  600. _USER_PATH_EXPORTED=1
  601. export PATH="$USER_PATH:$PATH"
  602. fi
  603. fi
  604. if [[ -z "$API" ]] ; then
  605. if [[ -z "$STAGE" ]] ; then
  606. API="$DEFAULT_CA"
  607. else
  608. API="$STAGE_CA"
  609. _info "Using stage api:$API"
  610. fi
  611. fi
  612. if [[ -z "$ACME_DIR" ]] ; then
  613. ACME_DIR="/home/.acme"
  614. fi
  615. if [[ -z "$APACHE_CONF_BACKUP_DIR" ]] ; then
  616. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  617. fi
  618. if [[ -z "$USER_AGENT" ]] ; then
  619. USER_AGENT="$DEFAULT_USER_AGENT"
  620. fi
  621. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  622. WGET="wget -q"
  623. if [[ "$DEBUG" ]] && [[ "$DEBUG" -ge "2" ]] ; then
  624. WGET="$WGET -d "
  625. fi
  626. dp="$LE_WORKING_DIR/curl.dump"
  627. CURL="curl -L --silent"
  628. if [[ "$DEBUG" ]] && [[ "$DEBUG" -ge "2" ]] ; then
  629. CURL="$CURL -L --trace-ascii $dp "
  630. fi
  631. _DEFAULT_ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  632. if [[ -z "$ACCOUNT_KEY_PATH" ]] ; then
  633. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  634. fi
  635. domain="$1"
  636. if [[ -z "$domain" ]] ; then
  637. return 0
  638. fi
  639. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  640. if [[ -z "$CERT_HOME" ]] ; then
  641. CERT_HOME="$_DEFAULT_CERT_HOME"
  642. fi
  643. domainhome="$CERT_HOME/$domain"
  644. mkdir -p "$domainhome"
  645. if [[ -z "$DOMAIN_PATH" ]] ; then
  646. DOMAIN_PATH="$domainhome"
  647. fi
  648. if [[ -z "$DOMAIN_CONF" ]] ; then
  649. DOMAIN_CONF="$domainhome/$domain.conf"
  650. fi
  651. if [[ -z "$DOMAIN_SSL_CONF" ]] ; then
  652. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  653. fi
  654. if [[ -z "$CSR_PATH" ]] ; then
  655. CSR_PATH="$domainhome/$domain.csr"
  656. fi
  657. if [[ -z "$CERT_KEY_PATH" ]] ; then
  658. CERT_KEY_PATH="$domainhome/$domain.key"
  659. fi
  660. if [[ -z "$CERT_PATH" ]] ; then
  661. CERT_PATH="$domainhome/$domain.cer"
  662. fi
  663. if [[ -z "$CA_CERT_PATH" ]] ; then
  664. CA_CERT_PATH="$domainhome/ca.cer"
  665. fi
  666. if [[ -z "$CERT_FULLCHAIN_PATH" ]] ; then
  667. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  668. fi
  669. if [[ -z "$CERT_PFX_PATH" ]] ; then
  670. CERT_PFX_PATH="$domainhome/$domain.pfx"
  671. fi
  672. }
  673. _apachePath() {
  674. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  675. if _startswith "$httpdconfname" '/' ; then
  676. httpdconf="$httpdconfname"
  677. httpdconfname="$(basename $httpdconfname)"
  678. else
  679. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  680. httpdconf="$httpdroot/$httpdconfname"
  681. fi
  682. if [[ ! -f $httpdconf ]] ; then
  683. _err "Apache Config file not found" $httpdconf
  684. return 1
  685. fi
  686. return 0
  687. }
  688. _restoreApache() {
  689. if [[ -z "$usingApache" ]] ; then
  690. return 0
  691. fi
  692. _initpath
  693. if ! _apachePath ; then
  694. return 1
  695. fi
  696. if [[ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]] ; then
  697. _debug "No config file to restore."
  698. return 0
  699. fi
  700. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  701. _debug "Restored: $httpdconf."
  702. if ! apachectl -t ; then
  703. _err "Sorry, restore apache config error, please contact me."
  704. return 1;
  705. fi
  706. _debug "Restored successfully."
  707. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  708. return 0
  709. }
  710. _setApache() {
  711. _initpath
  712. if ! _apachePath ; then
  713. return 1
  714. fi
  715. #backup the conf
  716. _debug "Backup apache config file" $httpdconf
  717. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  718. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  719. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  720. _info "The backup file will be deleted on sucess, just forget it."
  721. #add alias
  722. apacheVer="$(apachectl -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  723. _debug "apacheVer" "$apacheVer"
  724. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  725. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  726. if [[ "$apacheVer" ]] && [[ "$apacheMajer" -ge "2" ]] && [[ "$apacheMinor" -ge "4" ]] ; then
  727. echo "
  728. Alias /.well-known/acme-challenge $ACME_DIR
  729. <Directory $ACME_DIR >
  730. Require all granted
  731. </Directory>
  732. " >> $httpdconf
  733. else
  734. echo "
  735. Alias /.well-known/acme-challenge $ACME_DIR
  736. <Directory $ACME_DIR >
  737. Order allow,deny
  738. Allow from all
  739. </Directory>
  740. " >> $httpdconf
  741. fi
  742. if ! apachectl -t ; then
  743. _err "Sorry, apache config error, please contact me."
  744. _restoreApache
  745. return 1;
  746. fi
  747. if [[ ! -d "$ACME_DIR" ]] ; then
  748. mkdir -p "$ACME_DIR"
  749. chmod 755 "$ACME_DIR"
  750. fi
  751. if ! apachectl graceful ; then
  752. _err "Sorry, apachectl graceful error, please contact me."
  753. _restoreApache
  754. return 1;
  755. fi
  756. usingApache="1"
  757. return 0
  758. }
  759. _clearup() {
  760. _stopserver $serverproc
  761. serverproc=""
  762. _restoreApache
  763. }
  764. # webroot removelevel tokenfile
  765. _clearupwebbroot() {
  766. __webroot="$1"
  767. if [[ -z "$__webroot" ]] ; then
  768. _debug "no webroot specified, skip"
  769. return 0
  770. fi
  771. if [[ "$2" == '1' ]] ; then
  772. _debug "remove $__webroot/.well-known"
  773. rm -rf "$__webroot/.well-known"
  774. elif [[ "$2" == '2' ]] ; then
  775. _debug "remove $__webroot/.well-known/acme-challenge"
  776. rm -rf "$__webroot/.well-known/acme-challenge"
  777. elif [[ "$2" == '3' ]] ; then
  778. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  779. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  780. else
  781. _info "Skip for removelevel:$2"
  782. fi
  783. return 0
  784. }
  785. issue() {
  786. if [[ -z "$2" ]] ; then
  787. echo "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  788. return 1
  789. fi
  790. Le_Webroot="$1"
  791. Le_Domain="$2"
  792. Le_Alt="$3"
  793. Le_Keylength="$4"
  794. Le_RealCertPath="$5"
  795. Le_RealKeyPath="$6"
  796. Le_RealCACertPath="$7"
  797. Le_ReloadCmd="$8"
  798. Le_RealFullChainPath="$9"
  799. _initpath $Le_Domain
  800. if [[ -f "$DOMAIN_CONF" ]] ; then
  801. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  802. if [[ -z "$FORCE" ]] && [[ "$Le_NextRenewTime" ]] && [[ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ]] ; then
  803. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  804. return 2
  805. fi
  806. fi
  807. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  808. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  809. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  810. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  811. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  812. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  813. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  814. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  815. _setopt "$DOMAIN_CONF" "Le_RealFullChainPath" "=" "\"$Le_RealFullChainPath\""
  816. if [[ "$Le_Alt" == "no" ]] ; then
  817. Le_Alt=""
  818. fi
  819. if [[ "$Le_Keylength" == "no" ]] ; then
  820. Le_Keylength=""
  821. fi
  822. if [[ "$Le_RealCertPath" == "no" ]] ; then
  823. Le_RealCertPath=""
  824. fi
  825. if [[ "$Le_RealKeyPath" == "no" ]] ; then
  826. Le_RealKeyPath=""
  827. fi
  828. if [[ "$Le_RealCACertPath" == "no" ]] ; then
  829. Le_RealCACertPath=""
  830. fi
  831. if [[ "$Le_ReloadCmd" == "no" ]] ; then
  832. Le_ReloadCmd=""
  833. fi
  834. if [[ "$Le_RealFullChainPath" == "no" ]] ; then
  835. Le_RealFullChainPath=""
  836. fi
  837. if _contains "$Le_Webroot" "no" ; then
  838. _info "Standalone mode."
  839. if ! _exists "nc" ; then
  840. _err "Please install netcat(nc) tools first."
  841. return 1
  842. fi
  843. if [[ -z "$Le_HTTPPort" ]] ; then
  844. Le_HTTPPort=80
  845. fi
  846. _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
  847. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  848. if [[ "$netprc" ]] ; then
  849. _err "$netprc"
  850. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  851. _err "Please stop it first"
  852. return 1
  853. fi
  854. fi
  855. if _contains "$Le_Webroot" "apache" ; then
  856. if ! _setApache ; then
  857. _err "set up apache error. Report error to me."
  858. return 1
  859. fi
  860. else
  861. usingApache=""
  862. fi
  863. if [[ ! -f "$ACCOUNT_KEY_PATH" ]] ; then
  864. if ! createAccountKey $Le_Domain $Le_Keylength ; then
  865. _err "Create account key error."
  866. if [[ "$usingApache" ]] ; then
  867. _restoreApache
  868. fi
  869. return 1
  870. fi
  871. fi
  872. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  873. if [[ "$usingApache" ]] ; then
  874. _restoreApache
  875. fi
  876. return 1
  877. fi
  878. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  879. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  880. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  881. accountkeyhash="$(echo $accountkeyhash$API | _digest "sha256" )"
  882. if [[ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ]] ; then
  883. _info "Registering account"
  884. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  885. if [[ "$ACCOUNT_EMAIL" ]] ; then
  886. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  887. fi
  888. _send_signed_request "$API/acme/new-reg" "$regjson"
  889. if [[ "$code" == "" ]] || [[ "$code" == '201' ]] ; then
  890. _info "Registered"
  891. echo $response > $LE_WORKING_DIR/account.json
  892. elif [[ "$code" == '409' ]] ; then
  893. _info "Already registered"
  894. else
  895. _err "Register account Error: $response"
  896. _clearup
  897. return 1
  898. fi
  899. ACCOUNT_KEY_HASH="$accountkeyhash"
  900. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  901. else
  902. _info "Skip register account key"
  903. fi
  904. if [[ ! -f "$CERT_KEY_PATH" ]] ; then
  905. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  906. _err "Create domain key error."
  907. _clearup
  908. return 1
  909. fi
  910. fi
  911. if ! createCSR $Le_Domain $Le_Alt ; then
  912. _err "Create CSR error."
  913. _clearup
  914. return 1
  915. fi
  916. vlist="$Le_Vlist"
  917. # verify each domain
  918. _info "Verify each domain"
  919. sep='#'
  920. if [[ -z "$vlist" ]] ; then
  921. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  922. _index=1
  923. _currentRoot=""
  924. for d in $alldomains
  925. do
  926. _info "Getting webroot for domain" $d
  927. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  928. _debug _w "$_w"
  929. if [[ "$_w" ]] ; then
  930. _currentRoot="$_w"
  931. fi
  932. _debug "_currentRoot" "$_currentRoot"
  933. let "_index+=1"
  934. vtype="$VTYPE_HTTP"
  935. if _startswith "$_currentRoot" "dns" ; then
  936. vtype="$VTYPE_DNS"
  937. fi
  938. _info "Getting token for domain" $d
  939. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  940. if [[ ! -z "$code" ]] && [[ ! "$code" == '201' ]] ; then
  941. _err "new-authz error: $response"
  942. _clearup
  943. return 1
  944. fi
  945. entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  946. _debug entry "$entry"
  947. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  948. _debug token $token
  949. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  950. _debug uri $uri
  951. keyauthorization="$token.$thumbprint"
  952. _debug keyauthorization "$keyauthorization"
  953. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  954. _debug dvlist "$dvlist"
  955. vlist="$vlist$dvlist,"
  956. done
  957. #add entry
  958. dnsadded=""
  959. ventries=$(echo "$vlist" | tr ',' ' ' )
  960. for ventry in $ventries
  961. do
  962. d=$(echo $ventry | cut -d $sep -f 1)
  963. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  964. vtype=$(echo $ventry | cut -d $sep -f 4)
  965. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  966. if [[ "$vtype" == "$VTYPE_DNS" ]] ; then
  967. dnsadded='0'
  968. txtdomain="_acme-challenge.$d"
  969. _debug txtdomain "$txtdomain"
  970. txt="$(echo -e -n $keyauthorization | _digest "sha256" | _urlencode)"
  971. _debug txt "$txt"
  972. #dns
  973. #1. check use api
  974. d_api=""
  975. if [[ -f "$LE_WORKING_DIR/$d/$_currentRoot" ]] ; then
  976. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  977. elif [[ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ]] ; then
  978. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  979. elif [[ -f "$LE_WORKING_DIR/$_currentRoot" ]] ; then
  980. d_api="$LE_WORKING_DIR/$_currentRoot"
  981. elif [[ -f "$LE_WORKING_DIR/$_currentRoot.sh" ]] ; then
  982. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  983. elif [[ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ]] ; then
  984. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  985. elif [[ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ]] ; then
  986. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  987. fi
  988. _debug d_api "$d_api"
  989. if [[ "$d_api" ]] ; then
  990. _info "Found domain api file: $d_api"
  991. else
  992. _err "Add the following TXT record:"
  993. _err "Domain: $txtdomain"
  994. _err "TXT value: $txt"
  995. _err "Please be aware that you prepend _acme-challenge. before your domain"
  996. _err "so the resulting subdomain will be: $txtdomain"
  997. continue
  998. fi
  999. (
  1000. if ! source $d_api ; then
  1001. _err "Load file $d_api error. Please check your api file and try again."
  1002. return 1
  1003. fi
  1004. addcommand="$_currentRoot-add"
  1005. if ! _exists $addcommand ; then
  1006. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1007. return 1
  1008. fi
  1009. if ! $addcommand $txtdomain $txt ; then
  1010. _err "Error add txt for domain:$txtdomain"
  1011. return 1
  1012. fi
  1013. )
  1014. if [[ "$?" != "0" ]] ; then
  1015. _clearup
  1016. return 1
  1017. fi
  1018. dnsadded='1'
  1019. fi
  1020. done
  1021. if [[ "$dnsadded" == '0' ]] ; then
  1022. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  1023. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1024. _err "Please add the TXT records to the domains, and retry again."
  1025. _clearup
  1026. return 1
  1027. fi
  1028. fi
  1029. if [[ "$dnsadded" == '1' ]] ; then
  1030. _info "Sleep 60 seconds for the txt records to take effect"
  1031. sleep 60
  1032. fi
  1033. _debug "ok, let's start to verify"
  1034. ventries=$(echo "$vlist" | tr ',' ' ' )
  1035. for ventry in $ventries
  1036. do
  1037. d=$(echo $ventry | cut -d $sep -f 1)
  1038. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1039. uri=$(echo $ventry | cut -d $sep -f 3)
  1040. vtype=$(echo $ventry | cut -d $sep -f 4)
  1041. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1042. _info "Verifying:$d"
  1043. _debug "d" "$d"
  1044. _debug "keyauthorization" "$keyauthorization"
  1045. _debug "uri" "$uri"
  1046. removelevel=""
  1047. token=""
  1048. _debug "_currentRoot" "$_currentRoot"
  1049. if [[ "$vtype" == "$VTYPE_HTTP" ]] ; then
  1050. if [[ "$_currentRoot" == "no" ]] ; then
  1051. _info "Standalone mode server"
  1052. _startserver "$keyauthorization" &
  1053. if [[ "$?" != "0" ]] ; then
  1054. _clearup
  1055. return 1
  1056. fi
  1057. serverproc="$!"
  1058. sleep 2
  1059. _debug serverproc $serverproc
  1060. else
  1061. if [[ "$_currentRoot" == "apache" ]] ; then
  1062. wellknown_path="$ACME_DIR"
  1063. else
  1064. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1065. if [[ ! -d "$_currentRoot/.well-known" ]] ; then
  1066. removelevel='1'
  1067. elif [[ ! -d "$_currentRoot/.well-known/acme-challenge" ]] ; then
  1068. removelevel='2'
  1069. else
  1070. removelevel='3'
  1071. fi
  1072. fi
  1073. _debug wellknown_path "$wellknown_path"
  1074. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  1075. _debug "writing token:$token to $wellknown_path/$token"
  1076. mkdir -p "$wellknown_path"
  1077. echo -n "$keyauthorization" > "$wellknown_path/$token"
  1078. if [[ ! "$usingApache" ]] ; then
  1079. webroot_owner=$(_stat $_currentRoot)
  1080. _debug "Changing owner/group of .well-known to $webroot_owner"
  1081. chown -R $webroot_owner "$_currentRoot/.well-known"
  1082. fi
  1083. fi
  1084. fi
  1085. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  1086. if [[ ! -z "$code" ]] && [[ ! "$code" == '202' ]] ; then
  1087. _err "$d:Challenge error: $response"
  1088. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1089. _clearup
  1090. return 1
  1091. fi
  1092. waittimes=0
  1093. if [[ -z "$MAX_RETRY_TIMES" ]] ; then
  1094. MAX_RETRY_TIMES=30
  1095. fi
  1096. while [[ "1" ]] ; do
  1097. let "waittimes+=1"
  1098. if [[ "$waittimes" -ge "$MAX_RETRY_TIMES" ]] ; then
  1099. _err "$d:Timeout"
  1100. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1101. _clearup
  1102. return 1
  1103. fi
  1104. _debug "sleep 5 secs to verify"
  1105. sleep 5
  1106. _debug "checking"
  1107. response="$(_get $uri)"
  1108. if [[ "$?" != "0" ]] ; then
  1109. _err "$d:Verify error:$response"
  1110. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1111. _clearup
  1112. return 1
  1113. fi
  1114. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1115. if [[ "$status" == "valid" ]] ; then
  1116. _info "Success"
  1117. _stopserver $serverproc
  1118. serverproc=""
  1119. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1120. break;
  1121. fi
  1122. if [[ "$status" == "invalid" ]] ; then
  1123. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  1124. _err "$d:Verify error:$error"
  1125. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1126. _clearup
  1127. return 1;
  1128. fi
  1129. if [[ "$status" == "pending" ]] ; then
  1130. _info "Pending"
  1131. else
  1132. _err "$d:Verify error:$response"
  1133. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1134. _clearup
  1135. return 1
  1136. fi
  1137. done
  1138. done
  1139. _clearup
  1140. _info "Verify finished, start to sign."
  1141. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1142. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1143. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1144. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  1145. if [[ "$Le_LinkCert" ]] ; then
  1146. echo "$BEGIN_CERT" > "$CERT_PATH"
  1147. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1148. echo "$END_CERT" >> "$CERT_PATH"
  1149. _info "Cert success."
  1150. cat "$CERT_PATH"
  1151. _info "Your cert is in $CERT_PATH"
  1152. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1153. if [[ ! "$USER_PATH" ]] || [[ ! "$IN_CRON" ]] ; then
  1154. USER_PATH="$PATH"
  1155. _saveaccountconf "USER_PATH" "$USER_PATH"
  1156. fi
  1157. fi
  1158. if [[ -z "$Le_LinkCert" ]] ; then
  1159. response="$(echo $response | _dbase64 "multiline" )"
  1160. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1161. return 1
  1162. fi
  1163. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  1164. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1165. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  1166. if [[ "$Le_LinkIssuer" ]] ; then
  1167. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1168. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1169. echo "$END_CERT" >> "$CA_CERT_PATH"
  1170. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1171. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1172. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1173. fi
  1174. Le_CertCreateTime=$(date -u "+%s")
  1175. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  1176. Le_CertCreateTimeStr=$(date -u )
  1177. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  1178. if [[ -z "$Le_RenewalDays" ]] || [[ "$Le_RenewalDays" -lt "0" ]] || [[ "$Le_RenewalDays" -gt "80" ]] ; then
  1179. Le_RenewalDays=80
  1180. fi
  1181. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  1182. let "Le_NextRenewTime=Le_CertCreateTime+Le_RenewalDays*24*60*60"
  1183. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  1184. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1185. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  1186. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1187. }
  1188. renew() {
  1189. Le_Domain="$1"
  1190. if [[ -z "$Le_Domain" ]] ; then
  1191. _err "Usage: $PROJECT_ENTRY --renew -d domain.com"
  1192. return 1
  1193. fi
  1194. _initpath $Le_Domain
  1195. if [[ ! -f "$DOMAIN_CONF" ]] ; then
  1196. _info "$Le_Domain is not a issued domain, skip."
  1197. return 0;
  1198. fi
  1199. source "$DOMAIN_CONF"
  1200. if [[ -z "$FORCE" ]] && [[ "$Le_NextRenewTime" ]] && [[ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ]] ; then
  1201. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1202. return 2
  1203. fi
  1204. IS_RENEW="1"
  1205. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1206. local res=$?
  1207. IS_RENEW=""
  1208. return $res
  1209. }
  1210. renewAll() {
  1211. _initpath
  1212. _info "renewAll"
  1213. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1214. d=$(echo $d | cut -d '/' -f 1)
  1215. _info "renew $d"
  1216. Le_LinkCert=""
  1217. Le_Domain=""
  1218. Le_Alt="no"
  1219. Le_Webroot=""
  1220. Le_Keylength=""
  1221. Le_LinkIssuer=""
  1222. Le_CertCreateTime=""
  1223. Le_CertCreateTimeStr=""
  1224. Le_RenewalDays=""
  1225. Le_NextRenewTime=""
  1226. Le_NextRenewTimeStr=""
  1227. Le_RealCertPath=""
  1228. Le_RealKeyPath=""
  1229. Le_RealCACertPath=""
  1230. Le_ReloadCmd=""
  1231. Le_RealFullChainPath=""
  1232. DOMAIN_PATH=""
  1233. DOMAIN_CONF=""
  1234. DOMAIN_SSL_CONF=""
  1235. CSR_PATH=""
  1236. CERT_KEY_PATH=""
  1237. CERT_PATH=""
  1238. CA_CERT_PATH=""
  1239. CERT_PFX_PATH=""
  1240. CERT_FULLCHAIN_PATH=""
  1241. ACCOUNT_KEY_PATH=""
  1242. wellknown_path=""
  1243. renew "$d"
  1244. done
  1245. }
  1246. installcert() {
  1247. Le_Domain="$1"
  1248. if [[ -z "$Le_Domain" ]] ; then
  1249. echo "Usage: $PROJECT_ENTRY --installcert -d domain.com [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  1250. return 1
  1251. fi
  1252. Le_RealCertPath="$2"
  1253. Le_RealKeyPath="$3"
  1254. Le_RealCACertPath="$4"
  1255. Le_ReloadCmd="$5"
  1256. Le_RealFullChainPath="$6"
  1257. _initpath $Le_Domain
  1258. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  1259. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  1260. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  1261. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  1262. _setopt "$DOMAIN_CONF" "Le_RealFullChainPath" "=" "\"$Le_RealFullChainPath\""
  1263. if [[ "$Le_RealCertPath" ]] ; then
  1264. if [[ -f "$Le_RealCertPath" ]] ; then
  1265. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  1266. fi
  1267. cat "$CERT_PATH" > "$Le_RealCertPath"
  1268. fi
  1269. if [[ "$Le_RealCACertPath" ]] ; then
  1270. if [[ "$Le_RealCACertPath" == "$Le_RealCertPath" ]] ; then
  1271. echo "" >> "$Le_RealCACertPath"
  1272. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1273. else
  1274. if [[ -f "$Le_RealCACertPath" ]] ; then
  1275. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1276. fi
  1277. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1278. fi
  1279. fi
  1280. if [[ "$Le_RealKeyPath" ]] ; then
  1281. if [[ -f "$Le_RealKeyPath" ]] ; then
  1282. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1283. fi
  1284. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1285. fi
  1286. if [[ "$Le_RealFullChainPath" ]] ; then
  1287. if [[ -f "$Le_RealFullChainPath" ]] ; then
  1288. cp -p "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  1289. fi
  1290. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  1291. fi
  1292. if [[ "$Le_ReloadCmd" ]] ; then
  1293. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1294. (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
  1295. fi
  1296. }
  1297. installcronjob() {
  1298. _initpath
  1299. if ! _exists "crontab" ; then
  1300. _err "crontab doesn't exist, so, we can not install cron jobs."
  1301. _err "All your certs will not be renewed automatically."
  1302. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  1303. return 1
  1304. fi
  1305. _info "Installing cron job"
  1306. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  1307. if [[ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]] ; then
  1308. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  1309. else
  1310. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  1311. return 1
  1312. fi
  1313. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  1314. fi
  1315. if [[ "$?" != "0" ]] ; then
  1316. _err "Install cron job failed. You need to manually renew your certs."
  1317. _err "Or you can add cronjob by yourself:"
  1318. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  1319. return 1
  1320. fi
  1321. }
  1322. uninstallcronjob() {
  1323. if ! _exists "crontab" ; then
  1324. return
  1325. fi
  1326. _info "Removing cron job"
  1327. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  1328. if [[ "$cr" ]] ; then
  1329. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  1330. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  1331. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1332. fi
  1333. _initpath
  1334. }
  1335. revoke() {
  1336. Le_Domain="$1"
  1337. if [[ -z "$Le_Domain" ]] ; then
  1338. echo "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  1339. return 1
  1340. fi
  1341. _initpath $Le_Domain
  1342. if [[ ! -f "$DOMAIN_CONF" ]] ; then
  1343. _err "$Le_Domain is not a issued domain, skip."
  1344. return 1;
  1345. fi
  1346. if [[ ! -f "$CERT_PATH" ]] ; then
  1347. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1348. return 1
  1349. fi
  1350. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1351. if [[ -z "$cert" ]] ; then
  1352. _err "Cert for $Le_Domain is empty found, skip."
  1353. return 1
  1354. fi
  1355. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1356. uri="$API/acme/revoke-cert"
  1357. _info "Try domain key first."
  1358. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1359. if [[ -z "$response" ]] ; then
  1360. _info "Revoke success."
  1361. rm -f $CERT_PATH
  1362. return 0
  1363. else
  1364. _err "Revoke error by domain key."
  1365. _err "$resource"
  1366. fi
  1367. fi
  1368. _info "Then try account key."
  1369. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1370. if [[ -z "$response" ]] ; then
  1371. _info "Revoke success."
  1372. rm -f $CERT_PATH
  1373. return 0
  1374. else
  1375. _err "Revoke error."
  1376. _debug "$resource"
  1377. fi
  1378. fi
  1379. return 1
  1380. }
  1381. # Detect profile file if not specified as environment variable
  1382. _detect_profile() {
  1383. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  1384. echo "$PROFILE"
  1385. return
  1386. fi
  1387. local DETECTED_PROFILE
  1388. DETECTED_PROFILE=''
  1389. local SHELLTYPE
  1390. SHELLTYPE="$(basename "/$SHELL")"
  1391. if [[ "$SHELLTYPE" = "bash" ]] ; then
  1392. if [[ -f "$HOME/.bashrc" ]] ; then
  1393. DETECTED_PROFILE="$HOME/.bashrc"
  1394. elif [[ -f "$HOME/.bash_profile" ]] ; then
  1395. DETECTED_PROFILE="$HOME/.bash_profile"
  1396. fi
  1397. elif [[ "$SHELLTYPE" = "zsh" ]] ; then
  1398. DETECTED_PROFILE="$HOME/.zshrc"
  1399. fi
  1400. if [[ -z "$DETECTED_PROFILE" ]] ; then
  1401. if [[ -f "$HOME/.profile" ]] ; then
  1402. DETECTED_PROFILE="$HOME/.profile"
  1403. elif [[ -f "$HOME/.bashrc" ]] ; then
  1404. DETECTED_PROFILE="$HOME/.bashrc"
  1405. elif [[ -f "$HOME/.bash_profile" ]] ; then
  1406. DETECTED_PROFILE="$HOME/.bash_profile"
  1407. elif [[ -f "$HOME/.zshrc" ]] ; then
  1408. DETECTED_PROFILE="$HOME/.zshrc"
  1409. fi
  1410. fi
  1411. if [[ ! -z "$DETECTED_PROFILE" ]] ; then
  1412. echo "$DETECTED_PROFILE"
  1413. fi
  1414. }
  1415. _initconf() {
  1416. _initpath
  1417. if [[ ! -f "$ACCOUNT_CONF_PATH" ]] ; then
  1418. echo "#ACCOUNT_CONF_PATH=xxxx
  1419. #Account configurations:
  1420. #Here are the supported macros, uncomment them to make them take effect.
  1421. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1422. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1423. #CERT_HOME=\"/path/to/cert/home\"
  1424. #STAGE=1 # Use the staging api
  1425. #FORCE=1 # Force to issue cert
  1426. #DEBUG=1 # Debug mode
  1427. #ACCOUNT_KEY_HASH=account key hash
  1428. USER_AGENT=\"$USER_AGENT\"
  1429. #USER_PATH=""
  1430. #dns api
  1431. #######################
  1432. #Cloudflare:
  1433. #api key
  1434. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1435. #account email
  1436. #CF_Email=\"xxxx@sss.com\"
  1437. #######################
  1438. #Dnspod.cn:
  1439. #api key id
  1440. #DP_Id=\"1234\"
  1441. #api key
  1442. #DP_Key=\"sADDsdasdgdsf\"
  1443. #######################
  1444. #Cloudxns.com:
  1445. #CX_Key=\"1234\"
  1446. #
  1447. #CX_Secret=\"sADDsdasdgdsf\"
  1448. " > $ACCOUNT_CONF_PATH
  1449. fi
  1450. }
  1451. _precheck() {
  1452. if ! _exists "curl" && ! _exists "wget"; then
  1453. _err "Please install curl or wget first, we need to access http resources."
  1454. return 1
  1455. fi
  1456. if ! _exists "crontab" ; then
  1457. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1458. _err "We need to set cron job to renew the certs automatically."
  1459. _err "Otherwise, your certs will not be able to be renewed automatically."
  1460. if [[ -z "$FORCE" ]] ; then
  1461. _err "Please add '--force' and try install again to go without crontab."
  1462. _err "./$PROJECT_ENTRY --install --force"
  1463. return 1
  1464. fi
  1465. fi
  1466. if ! _exists "openssl" ; then
  1467. _err "Please install openssl first."
  1468. _err "We need openssl to generate keys."
  1469. return 1
  1470. fi
  1471. if ! _exists "nc" ; then
  1472. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1473. _err "We use nc for standalone server if you use standalone mode."
  1474. _err "If you don't use standalone mode, just ignore this warning."
  1475. fi
  1476. return 0
  1477. }
  1478. install() {
  1479. if ! _initpath ; then
  1480. _err "Install failed."
  1481. return 1
  1482. fi
  1483. if ! _precheck ; then
  1484. _err "Pre-check failed, can not install."
  1485. return 1
  1486. fi
  1487. #convert from le
  1488. if [[ -d "$HOME/.le" ]] ; then
  1489. for envfile in "le.env" "le.sh.env"
  1490. do
  1491. if [[ -f "$HOME/.le/$envfile" ]] ; then
  1492. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  1493. _upgrading="1"
  1494. _info "You are upgrading from le.sh"
  1495. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  1496. mv "$HOME/.le" "$LE_WORKING_DIR"
  1497. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1498. break;
  1499. fi
  1500. fi
  1501. done
  1502. fi
  1503. _info "Installing to $LE_WORKING_DIR"
  1504. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1505. _err "Can not craete working dir: $LE_WORKING_DIR"
  1506. return 1
  1507. fi
  1508. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  1509. if [[ "$?" != "0" ]] ; then
  1510. _err "Install failed, can not copy $PROJECT_ENTRY"
  1511. return 1
  1512. fi
  1513. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  1514. _profile="$(_detect_profile)"
  1515. if [[ "$_profile" ]] ; then
  1516. _debug "Found profile: $_profile"
  1517. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1518. if [[ "$_upgrading" == "1" ]] ; then
  1519. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  1520. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  1521. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  1522. fi
  1523. _setopt "$_envfile" "LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  1524. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1525. echo "" >> "$_profile"
  1526. _setopt "$_profile" "source \"$LE_WORKING_DIR/$PROJECT_NAME.env\""
  1527. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  1528. else
  1529. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  1530. fi
  1531. if [[ -d "dnsapi" ]] ; then
  1532. mkdir -p $LE_WORKING_DIR/dnsapi
  1533. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1534. fi
  1535. #to keep compatible mv the .acc file to .key file
  1536. if [[ -f "$LE_WORKING_DIR/account.acc" ]] ; then
  1537. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1538. fi
  1539. if [[ ! -f "$ACCOUNT_CONF_PATH" ]] ; then
  1540. _initconf
  1541. fi
  1542. if [[ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]] ; then
  1543. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  1544. fi
  1545. if [[ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]] ; then
  1546. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  1547. fi
  1548. if [[ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]] ; then
  1549. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  1550. fi
  1551. installcronjob
  1552. _info OK
  1553. }
  1554. uninstall() {
  1555. uninstallcronjob
  1556. _initpath
  1557. _profile="$(_detect_profile)"
  1558. if [[ "$_profile" ]] ; then
  1559. text="$(cat $_profile)"
  1560. echo "$text" | sed "s|^source.*$PROJECT_NAME.env.*$||" > "$_profile"
  1561. fi
  1562. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  1563. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1564. }
  1565. cron() {
  1566. IN_CRON=1
  1567. renewAll
  1568. IN_CRON=""
  1569. }
  1570. version() {
  1571. echo "$PROJECT"
  1572. echo "v$VER"
  1573. }
  1574. showhelp() {
  1575. version
  1576. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  1577. Commands:
  1578. --help, -h Show this help message.
  1579. --version, -v Show version info.
  1580. --install Install $PROJECT_NAME to your system.
  1581. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  1582. --issue Issue a cert.
  1583. --installcert Install the issued cert to apache/nginx or any other server.
  1584. --renew, -r Renew a cert.
  1585. --renewAll Renew all the certs
  1586. --revoke Revoke a cert.
  1587. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1588. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  1589. --cron Run cron job to renew all the certs.
  1590. --toPkcs Export the certificate and key to a pfx file.
  1591. --createAccountKey, -cak Create an account private key, professional use.
  1592. --createDomainKey, -cdk Create an domain private key, professional use.
  1593. --createCSR, -ccsr Create CSR , professional use.
  1594. Parameters:
  1595. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  1596. --force, -f Used to force to install or force to renew a cert immediately.
  1597. --staging, --test Use staging server, just for test.
  1598. --debug Output debug info.
  1599. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  1600. --standalone Use standalone mode.
  1601. --apache Use apache mode.
  1602. --dns [dns-cf|dns-dp|dns-cx|/path/to/api/file] Use dns mode or dns api.
  1603. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  1604. --accountkeylength, -ak [2048] Specifies the account key length.
  1605. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  1606. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  1607. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  1608. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  1609. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  1610. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  1611. --accountconf Specifies a customized account config file.
  1612. --home Specifies the home dir for $PROJECT_NAME .
  1613. --certhome Specifies the home dir to save all the certs.
  1614. --useragent Specifies the user agent string. it will be saved for future use too.
  1615. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  1616. --accountkey Specifies the account key path, Only valid for the '--install' command.
  1617. --days Specifies the days to renew the cert when using '--issue' command. The max value is 80 days.
  1618. "
  1619. }
  1620. _installOnline() {
  1621. _info "Installing from online archive."
  1622. if [[ ! "$BRANCH" ]] ; then
  1623. BRANCH="master"
  1624. fi
  1625. _initpath
  1626. target="$PROJECT/archive/$BRANCH.tar.gz"
  1627. _info "Downloading $target"
  1628. localname="$BRANCH.tar.gz"
  1629. if ! _get "$target" > $localname ; then
  1630. _debug "Download error."
  1631. return 1
  1632. fi
  1633. _info "Extracting $localname"
  1634. tar xzf $localname
  1635. cd "$PROJECT_NAME-$BRANCH"
  1636. chmod +x $PROJECT_ENTRY
  1637. if ./$PROJECT_ENTRY install ; then
  1638. _info "Install success!"
  1639. fi
  1640. cd ..
  1641. rm -rf "$PROJECT_NAME-$BRANCH"
  1642. rm -f "$localname"
  1643. }
  1644. _process() {
  1645. _CMD=""
  1646. _domain=""
  1647. _altdomains="no"
  1648. _webroot=""
  1649. _keylength="no"
  1650. _accountkeylength="no"
  1651. _certpath="no"
  1652. _keypath="no"
  1653. _capath="no"
  1654. _fullchainpath="no"
  1655. _reloadcmd="no"
  1656. _password=""
  1657. _accountconf=""
  1658. _useragent=""
  1659. _accountemail=""
  1660. _accountkey=""
  1661. _certhome=""
  1662. while [[ ${#} -gt 0 ]] ; do
  1663. case "${1}" in
  1664. --help|-h)
  1665. showhelp
  1666. return
  1667. ;;
  1668. --version|-v)
  1669. version
  1670. return
  1671. ;;
  1672. --install)
  1673. _CMD="install"
  1674. ;;
  1675. --uninstall)
  1676. _CMD="uninstall"
  1677. ;;
  1678. --issue)
  1679. _CMD="issue"
  1680. ;;
  1681. --installcert|-i)
  1682. _CMD="installcert"
  1683. ;;
  1684. --renew|-r)
  1685. _CMD="renew"
  1686. ;;
  1687. --renewAll|-renewall)
  1688. _CMD="renewAll"
  1689. ;;
  1690. --revoke)
  1691. _CMD="revoke"
  1692. ;;
  1693. --installcronjob)
  1694. _CMD="installcronjob"
  1695. ;;
  1696. --uninstallcronjob)
  1697. _CMD="uninstallcronjob"
  1698. ;;
  1699. --cron)
  1700. _CMD="cron"
  1701. ;;
  1702. --toPkcs)
  1703. _CMD="toPkcs"
  1704. ;;
  1705. --createAccountKey|--createaccountkey|-cak)
  1706. _CMD="createAccountKey"
  1707. ;;
  1708. --createDomainKey|--createdomainkey|-cdk)
  1709. _CMD="createDomainKey"
  1710. ;;
  1711. --createCSR|--createcsr|-ccr)
  1712. _CMD="createCSR"
  1713. ;;
  1714. --domain|-d)
  1715. _dvalue="$2"
  1716. if [[ -z "$_dvalue" ]] || _startswith "$_dvalue" "-" ; then
  1717. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  1718. return 1
  1719. fi
  1720. if [[ -z "$_domain" ]] ; then
  1721. _domain="$_dvalue"
  1722. else
  1723. if [[ "$_altdomains" == "no" ]] ; then
  1724. _altdomains="$_dvalue"
  1725. else
  1726. _altdomains="$_altdomains,$_dvalue"
  1727. fi
  1728. fi
  1729. shift
  1730. ;;
  1731. --force|-f)
  1732. FORCE="1"
  1733. ;;
  1734. --staging|--test)
  1735. STAGE="1"
  1736. ;;
  1737. --debug)
  1738. if [[ -z "$2" ]] || _startswith "$2" "-" ; then
  1739. DEBUG="1"
  1740. else
  1741. DEBUG="$2"
  1742. shift
  1743. fi
  1744. ;;
  1745. --webroot|-w)
  1746. wvalue="$2"
  1747. if [[ -z "$_webroot" ]] ; then
  1748. _webroot="$wvalue"
  1749. else
  1750. _webroot="$_webroot,$wvalue"
  1751. fi
  1752. shift
  1753. ;;
  1754. --standalone)
  1755. wvalue="no"
  1756. if [[ -z "$_webroot" ]] ; then
  1757. _webroot="$wvalue"
  1758. else
  1759. _webroot="$_webroot,$wvalue"
  1760. fi
  1761. ;;
  1762. --apache)
  1763. wvalue="apache"
  1764. if [[ -z "$_webroot" ]] ; then
  1765. _webroot="$wvalue"
  1766. else
  1767. _webroot="$_webroot,$wvalue"
  1768. fi
  1769. ;;
  1770. --dns)
  1771. wvalue="dns"
  1772. if ! _startswith "$2" "-" ; then
  1773. wvalue="$2"
  1774. shift
  1775. fi
  1776. if [[ -z "$_webroot" ]] ; then
  1777. _webroot="$wvalue"
  1778. else
  1779. _webroot="$_webroot,$wvalue"
  1780. fi
  1781. ;;
  1782. --keylength|-k)
  1783. _keylength="$2"
  1784. accountkeylength="$2"
  1785. shift
  1786. ;;
  1787. --accountkeylength|-ak)
  1788. accountkeylength="$2"
  1789. shift
  1790. ;;
  1791. --certpath)
  1792. _certpath="$2"
  1793. shift
  1794. ;;
  1795. --keypath)
  1796. _keypath="$2"
  1797. shift
  1798. ;;
  1799. --capath)
  1800. _capath="$2"
  1801. shift
  1802. ;;
  1803. --fullchainpath)
  1804. _fullchainpath="$2"
  1805. shift
  1806. ;;
  1807. --reloadcmd|--reloadCmd)
  1808. _reloadcmd="$2"
  1809. shift
  1810. ;;
  1811. --password)
  1812. _password="$2"
  1813. shift
  1814. ;;
  1815. --accountconf)
  1816. _accountconf="$2"
  1817. ACCOUNT_CONF_PATH="$_accountconf"
  1818. shift
  1819. ;;
  1820. --home)
  1821. LE_WORKING_DIR="$2"
  1822. shift
  1823. ;;
  1824. --certhome)
  1825. _certhome="$2"
  1826. CERT_HOME="$_certhome"
  1827. shift
  1828. ;;
  1829. --useragent)
  1830. _useragent="$2"
  1831. USER_AGENT="$_useragent"
  1832. shift
  1833. ;;
  1834. --accountemail )
  1835. _accountemail="$2"
  1836. ACCOUNT_EMAIL="$_accountemail"
  1837. shift
  1838. ;;
  1839. --accountkey )
  1840. _accountkey="$2"
  1841. ACCOUNT_KEY_PATH="$_accountkey"
  1842. shift
  1843. ;;
  1844. --days )
  1845. _days="$2"
  1846. Le_RenewalDays="$_days"
  1847. shift
  1848. ;;
  1849. *)
  1850. _err "Unknown parameter : $1"
  1851. return 1
  1852. ;;
  1853. esac
  1854. shift 1
  1855. done
  1856. case "${_CMD}" in
  1857. install) install ;;
  1858. uninstall) uninstall ;;
  1859. issue)
  1860. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1861. ;;
  1862. installcert)
  1863. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1864. ;;
  1865. renew)
  1866. renew "$_domain"
  1867. ;;
  1868. renewAll)
  1869. renewAll
  1870. ;;
  1871. revoke)
  1872. revoke "$_domain"
  1873. ;;
  1874. installcronjob) installcronjob ;;
  1875. uninstallcronjob) uninstallcronjob ;;
  1876. cron) cron ;;
  1877. toPkcs)
  1878. toPkcs "$_domain" "$_password"
  1879. ;;
  1880. createAccountKey)
  1881. createAccountKey "$_domain" "$_accountkeylength"
  1882. ;;
  1883. createDomainKey)
  1884. createDomainKey "$_domain" "$_keylength"
  1885. ;;
  1886. createCSR)
  1887. createCSR "$_domain" "$_altdomains"
  1888. ;;
  1889. *)
  1890. _err "Invalid command: $_CMD"
  1891. showhelp;
  1892. return 1
  1893. ;;
  1894. esac
  1895. if [[ "$_useragent" ]] ; then
  1896. _saveaccountconf "USER_AGENT" "$_useragent"
  1897. fi
  1898. if [[ "$_accountemail" ]] ; then
  1899. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  1900. fi
  1901. }
  1902. if [[ "$INSTALLONLINE" ]] ; then
  1903. INSTALLONLINE=""
  1904. _installOnline $BRANCH
  1905. exit
  1906. fi
  1907. if [[ -z "$1" ]] ; then
  1908. showhelp
  1909. else
  1910. if echo "$1" | grep "^-" >/dev/null 2>&1 ; then
  1911. _process "$@"
  1912. else
  1913. "$@"
  1914. fi
  1915. fi